text
stringlengths
10
2.72M
package com.lvmama.www.android_listview.ItemBean; import android.content.Context; import android.media.Image; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.TextView; import com.lvmama.www.android_listview.R; import java.util.List; /** * Created by shiyaorong on 15/12/28. */ public class MyAdapter extends BaseAdapter { private List<ItemBean> mList; private LayoutInflater mInflater; private ImageLoader mImageLoader; public MyAdapter(Context context, List<ItemBean> list) { mList = list; mInflater = LayoutInflater.from(context); mImageLoader = new ImageLoader(); //只初始化一次 } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // 逗比式 --------------------- //返回每一项的显示内容 // View view = mInflater.inflate(R.layout.listview_itemlayout, null); // ImageView imageView = (ImageView)view.findViewById(R.id.iv_image); // TextView tv = (TextView)view.findViewById(R.id.tv_title); // TextView content = (TextView)view.findViewById(R.id.tv_content); // // ItemBean itemBean = mList.get(position); // imageView.setBackgroundResource(itemBean.ItemImageResid); // tv.setText(itemBean.ItemTitle); // content.setText(itemBean.ItemContent); // // return view; // 逗比式 --------------------- // 普通式 --------------------- // if (convertView == null) { //读取缓存 // convertView = mInflater.inflate(R.layout.listview_itemlayout, null); // } // ImageView imageView = (ImageView)convertView.findViewById(R.id.iv_image); // TextView tv = (TextView)convertView.findViewById(R.id.tv_title); // TextView content = (TextView)convertView.findViewById(R.id.tv_content); // // ItemBean itemBean = mList.get(position); // imageView.setBackgroundResource(itemBean.ItemImageResid); // tv.setText(itemBean.ItemTitle); // content.setText(itemBean.ItemContent); // return convertView; // 普通式 --------------------- // 文艺式 --------------------- ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = mInflater.inflate(R.layout.listview_itemlayout, null); viewHolder.imageView = (ImageView)convertView.findViewById(R.id.iv_image); viewHolder.title = (TextView)convertView.findViewById(R.id.tv_title); viewHolder.content = (TextView)convertView.findViewById(R.id.tv_content); convertView.setTag(viewHolder); //建立关系 } else { viewHolder = (ViewHolder)convertView.getTag(); } ItemBean itemBean = mList.get(position); //读取网络图片 String url = itemBean.ItemImageUrl; viewHolder.imageView.setTag(url); //根据tag绑定 //使用多线程 // new ImageLoader().showImageByThread(viewHolder.imageView, url); //使用AsyncTask加载 // new ImageLoader().getShowImageByAsyncTask(viewHolder.imageView, url); //每次都创建ImageLoader 不行,要弄成成员变量,只初始化一次 mImageLoader.getShowImageByAsyncTask(viewHolder.imageView, url); viewHolder.imageView.setImageResource(itemBean.ItemImageResid); viewHolder.title.setText(itemBean.ItemTitle); viewHolder.content.setText(itemBean.ItemContent); return convertView; // 文艺式 --------------------- } class ViewHolder { public ImageView imageView; public TextView title; public TextView content; } }
import java.util.Scanner; public class homework_13{ public static void main(String[] args){ System.out.println("name:cck, number:20151681310210"); System.out.println("welcome to java"); System.out.print("Enter the rows and columns in the array: "); Scanner input = new Scanner(System.in); int input_row = input.nextInt(); int input_column = input.nextInt(); double[][] array = new double[input_row][input_column]; System.out.println("Enter the array: "); for(int i=0;i<input_row;++i){ for(int j=0;j<input_column;++j){ array[i][j] = input.nextDouble(); } } Location output = locateLargest(array,input_row,input_column); System.out.println("The location of the largest element is "+output.maxValue+" at ("+output.row+","+output.column+")" ); } public static Location locateLargest(double[][] a,int input_row,int input_column){ Location result = new Location(); result.row = 0; result.column = 0; result.maxValue = a[0][0]; for(int i=0;i<input_row;++i){ for(int j=0;j<input_column;++j){ if(a[i][j]>result.maxValue){ result.row = i; result.column = j; result.maxValue = a[i][j]; } } } return result; } } class Location{ int row; int column; double maxValue; }
package br.com.fatec.proximatrilha.service.provider; import static br.com.fatec.proximatrilha.utils.ValidateUtils.notNullParameter; import java.sql.Timestamp; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import br.com.fatec.proximatrilha.model.Multimedia; import br.com.fatec.proximatrilha.model.TrailDot; import br.com.fatec.proximatrilha.repository.MultimediaRepository; import br.com.fatec.proximatrilha.service.MultimediaService; import br.com.fatec.proximatrilha.service.TrailDotService; import br.com.fatec.proximatrilha.validator.service.MultimediaValidatorService; @Service("multimediaService") @Transactional public class MultimediaServiceProvider implements MultimediaService { @Autowired private MultimediaRepository multimediaRepository; @Autowired private MultimediaValidatorService multimediaValidatorService; @Autowired private TrailDotService trailDotService; public static Logger logger = Logger.getLogger("trail"); public void setTrailDotService(TrailDotService trailDotService) { this.trailDotService = trailDotService; } public void setMultimediaRepository(MultimediaRepository multimediaRepository) { this.multimediaRepository = multimediaRepository; } public void setMultimediaValidatorService(MultimediaValidatorService multimediaValidatorService) { this.multimediaValidatorService = multimediaValidatorService; } @Override public Collection<Multimedia> getAll(final Long trailId, final Long trailDotId) { notNullParameter(trailId, "trailId"); notNullParameter(trailDotId, "trailDotId"); TrailDot trailDot = trailDotService.getById(trailId, trailDotId); return trailDot.getMultimedias(); } @Override public Multimedia getById(final Long multimediaId) { return multimediaRepository.findOne(multimediaId); } @Override public Multimedia create(final Long trailId, final Long trailDotId, Multimedia multimedia) { Multimedia multimediaCreated = null; TrailDot trailDot = trailDotService.getById(trailId, trailDotId); multimediaValidatorService.validateCreateMultimedia(trailId, trailDotId, trailDot, multimedia); try { multimedia.setInsertDate(new Timestamp(System.currentTimeMillis())); multimedia.setUpdateDate(new Timestamp(System.currentTimeMillis())); multimedia.setTrailDot(trailDot); multimediaCreated = multimediaRepository.save(multimedia); }catch(Exception ex) { logger.log(Level.SEVERE, "Ocorreu erro ao inserir um arquivo de multimidia." + ex.getStackTrace()); } return multimediaCreated; } @Override public Multimedia update(final Long trailId, final Long trailDotId, final Long multimediaId, Multimedia multimedia) { Multimedia multimediaUpdated = null; TrailDot trailDot = trailDotService.getById(trailId, trailDotId); multimediaValidatorService.validateUpdateTrail(trailId, trailDotId, trailDot, multimediaId, multimedia); try { multimedia.setUpdateDate(new Timestamp(System.currentTimeMillis())); multimedia.setTrailDot(trailDot); multimediaUpdated = multimediaRepository.save(multimedia); }catch(Exception ex) { logger.log(Level.SEVERE, "Ocorreu erro ao atualizar as informa&ccedil;&otilde;es do arquivo de multimidia." +ex.getStackTrace()); } return multimediaUpdated; } @Override public void delete(final Long trailId, final Long trailDotId, final Long multimediaId) { notNullParameter(multimediaId, "trailId"); multimediaValidatorService.existMultimedia(multimediaId); try { Multimedia multimedia = getById(multimediaId); multimediaValidatorService.validateDeleteMultimedia(multimedia); multimediaRepository.delete(multimedia); }catch(Exception ex) { logger.log(Level.SEVERE, "Ocorreu erro ao remover o arquivo de multimidia." +ex.getStackTrace()); } } @Override @Transactional public void delete(final Long trailId, final Long trailDotId, final Collection<Multimedia> multimedias) { multimediaRepository.delete(multimedias); } public void uploadArchive() { } }
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sandy.user.facade; import com.sandy.infrastructure.util.PagingList; import com.sandy.user.dto.AccountDTO; /** * @category <blockquote> * @author Sandy * @version 1.0.0 04th 12 2018 */ public interface IAccountServiceFacade { /** * findById * @param id * @return UserDTO */ public AccountDTO findById(Long id); /** * find user by mobile * @param mobile * @return UserDTO */ public AccountDTO findByMobile(String mobile); /** * find user by email * @param email * @return userDTO */ public AccountDTO findByEmail(String email); /** * query find by user user name * @param userName * @return userDTO */ public AccountDTO findByUserName(String userName); /** * get list * @param regionId * @param userName * @param page * @param pageSize * @return PageList<UserDTO> */ public PagingList<AccountDTO> list(Long regionId, String userName, Integer page, Integer pageSize); /** * create new user * @param user * @return UserDTO */ public AccountDTO add(AccountDTO user); /** * update user information by id * @param user * @return UserDTO */ public AccountDTO update(AccountDTO user); /** * delete by user id * @param id * @return boolean */ public boolean delete(Long id); }
package com.baizhi.controller; import com.baizhi.entity.User; import com.baizhi.service.UserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; @Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService; @PostMapping("login") public String login(User user, HttpSession session){ //User login = userService.login(user); try { Subject subject = SecurityUtils.getSubject(); subject.login(new UsernamePasswordToken(user.getUsername(),user.getPassword())); return "redirect:/file/findAll"; }catch (UnknownAccountException e){ e.printStackTrace(); System.out.println("用户名错误!"); }catch (IncorrectCredentialsException e){ e.printStackTrace(); System.out.println("密码错误!"); } return "redirect:/index"; } @PostMapping("register") public String login(User user){ userService.register(user); return "redirect:/index"; } @GetMapping("logout") public String logout(){ SecurityUtils.getSubject().logout(); return "redirect:/index"; } }
package br.cefetrj.sca.service.util; import java.util.ArrayList; @SuppressWarnings("serial") public class SolicitaInclusaoDisciplinaResponse extends ArrayList<SolicitaInclusaoDisciplinaResponse.Item>{ public class Item { private String nomeDepartamento; private String codigoDepartamento; public Item(String nomeDepartamento, String codigoDepartamento) { this.codigoDepartamento = codigoDepartamento; this.nomeDepartamento = nomeDepartamento; } public String getNomeDepartamento() { return nomeDepartamento; } public String getCodigoDepartamento() { return codigoDepartamento; } } }
package scalagoon; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ShortSpares { @Parameters public static List<IntListVal> shortSpares() { return Arrays.asList(new IntListVal(10, 1, 9), new IntListVal(10, 1, 9, 0, 0), new IntListVal(15, 1, 9, 0, 5), new IntListVal(21, 1, 9, 3, 5, 0), new IntListVal(30, 1, 9, 3, 7, 2, 3)); } private final IntListVal input; public ShortSpares(IntListVal input) { this.input = input; } @Test public void test() { assertEquals(input.expected, new BowlingGame(input.vals).score()); } }
package sop.utils; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import dwz.common.util.StringUtils; import sop.util.lang.StringUtil; /** * @Author: LCF * @Date: 2020/1/9 11:32 * @Package: sop.utils */ public class TemplateCodegen { public static void main(String[] args) { FileInputStream is = null; try { is = new FileInputStream("D:/rrr/qc-forms20150706/Re_ BOM 标准化的资料---2016.7.6/c.xls"); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); int rows = sheet.getLastRowNum(); for (int i = 0; i < rows + 1; i++) { readRow(sheet, i); } } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } public static void readRow(HSSFSheet sheet, int row) { int cols = sheet.getPhysicalNumberOfRows(); for (int i = 0; i < cols; i++) { String s = readCell(sheet, i, row); System.out.println(s); } } public static String readCell(HSSFSheet sheet, int colIndex, int rowIndex) { StringBuilder sb = new StringBuilder(); String val = PoiUtil.getCellValue(sheet, colIndex, rowIndex); System.out.println(val); if (!StringUtils.isBlank(val)) { if (val.contains(";")) { sb.append(optionTemplate(val.split(";"))); } if (val.contains("、")) { sb.append(optionTemplate(val.split("、"))); } } return sb.toString(); } private static String optionTemplate(String[] options) { StringBuilder sb = new StringBuilder(); sb.append("<select id=\"${idPrefix}${idx}2\" class=\"detailInputData textInput\" ${fieldDisable} value=\"${detailVo[field]}\" >\n"); sb.append("<option value=\"\">--</option>\n"); for (String s : options) { sb.append("<option ${detailVo[field] eq '" + s + "'?'selected':''}>" + s + "</option>\n"); } sb.append("</select>\n"); return sb.toString(); } }
/* * Merge HRIS API * The unified API for building rich integrations with multiple HR Information System platforms. * * The version of the OpenAPI document: 1.0 * Contact: hello@merge.dev * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package merge_hris_client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * AccountIntegration */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-06-09T12:47:41.903246-07:00[America/Los_Angeles]") public class AccountIntegration { public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) private String name; /** * Gets or Sets categories */ @JsonAdapter(CategoriesEnum.Adapter.class) public enum CategoriesEnum { HRIS("hris"), ATS("ats"), ACCOUNTING("accounting"); private String value; CategoriesEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static CategoriesEnum fromValue(String value) { for (CategoriesEnum b : CategoriesEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } public static class Adapter extends TypeAdapter<CategoriesEnum> { @Override public void write(final JsonWriter jsonWriter, final CategoriesEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public CategoriesEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return CategoriesEnum.fromValue(value); } } } public static final String SERIALIZED_NAME_CATEGORIES = "categories"; @SerializedName(SERIALIZED_NAME_CATEGORIES) private List<CategoriesEnum> categories = null; public static final String SERIALIZED_NAME_IMAGE = "image"; @SerializedName(SERIALIZED_NAME_IMAGE) private URI image; public static final String SERIALIZED_NAME_SQUARE_IMAGE = "square_image"; @SerializedName(SERIALIZED_NAME_SQUARE_IMAGE) private URI squareImage; public static final String SERIALIZED_NAME_COLOR = "color"; @SerializedName(SERIALIZED_NAME_COLOR) private String color; public static final String SERIALIZED_NAME_SLUG = "slug"; @SerializedName(SERIALIZED_NAME_SLUG) private String slug; public AccountIntegration name(String name) { this.name = name; return this; } /** * Company name. * @return name **/ @ApiModelProperty(required = true, value = "Company name.") public String getName() { return name; } public void setName(String name) { this.name = name; } public AccountIntegration categories(List<CategoriesEnum> categories) { this.categories = categories; return this; } public AccountIntegration addCategoriesItem(CategoriesEnum categoriesItem) { if (this.categories == null) { this.categories = new ArrayList<CategoriesEnum>(); } this.categories.add(categoriesItem); return this; } /** * Category or categories this integration belongs to. Multiple categories should be comma separated.&lt;br/&gt;&lt;br&gt;Example: For [ats, hris], enter &lt;i&gt;ats,hris&lt;/i&gt; * @return categories **/ @javax.annotation.Nullable @ApiModelProperty(value = "Category or categories this integration belongs to. Multiple categories should be comma separated.<br/><br>Example: For [ats, hris], enter <i>ats,hris</i>") public List<CategoriesEnum> getCategories() { return categories; } public void setCategories(List<CategoriesEnum> categories) { this.categories = categories; } public AccountIntegration image(URI image) { this.image = image; return this; } /** * Company logo in rectangular shape. &lt;b&gt;Upload an image with a clear background.&lt;/b&gt; * @return image **/ @javax.annotation.Nullable @ApiModelProperty(value = "Company logo in rectangular shape. <b>Upload an image with a clear background.</b>") public URI getImage() { return image; } public void setImage(URI image) { this.image = image; } public AccountIntegration squareImage(URI squareImage) { this.squareImage = squareImage; return this; } /** * Company logo in square shape. &lt;b&gt;Upload an image with a white background.&lt;/b&gt; * @return squareImage **/ @javax.annotation.Nullable @ApiModelProperty(value = "Company logo in square shape. <b>Upload an image with a white background.</b>") public URI getSquareImage() { return squareImage; } public void setSquareImage(URI squareImage) { this.squareImage = squareImage; } public AccountIntegration color(String color) { this.color = color; return this; } /** * The color of this integration used for buttons and text throughout the app and landing pages. &lt;b&gt;Choose a darker, saturated color.&lt;/b&gt; * @return color **/ @javax.annotation.Nullable @ApiModelProperty(value = "The color of this integration used for buttons and text throughout the app and landing pages. <b>Choose a darker, saturated color.</b>") public String getColor() { return color; } public void setColor(String color) { this.color = color; } /** * Get slug * @return slug **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getSlug() { return slug; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AccountIntegration accountIntegration = (AccountIntegration) o; return Objects.equals(this.name, accountIntegration.name) && Objects.equals(this.categories, accountIntegration.categories) && Objects.equals(this.image, accountIntegration.image) && Objects.equals(this.squareImage, accountIntegration.squareImage) && Objects.equals(this.color, accountIntegration.color) && Objects.equals(this.slug, accountIntegration.slug); } @Override public int hashCode() { return Objects.hash(name, categories, image, squareImage, color, slug); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AccountIntegration {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" categories: ").append(toIndentedString(categories)).append("\n"); sb.append(" image: ").append(toIndentedString(image)).append("\n"); sb.append(" squareImage: ").append(toIndentedString(squareImage)).append("\n"); sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" slug: ").append(toIndentedString(slug)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.fz.dao; import com.fz.pojo.ProductInfo; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * @author: FZ * @date: 2021/4/15 16:27 * @description: */ public interface ProductInfoDao extends JpaRepository<ProductInfo,String> { List<ProductInfo> findByProductStatus(Integer productStatus); }
package com.himanshu.springboot2.angular.orders.dao; import com.himanshu.springboot2.angular.orders.entity.Customer; import org.springframework.data.repository.CrudRepository; public interface CustomerDao extends CrudRepository<Customer, Long> { }
package graph; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.EnumMap; import util.Enums.ColorMode; import util.Enums.DisplayMode; /** * * @author Joachim * * @Implementation * The GraphWindow class is intended to be define graphWindow component in a GraphPanel object. The GraphWidow class * can be used to create a regular graph as well as a expanded graph (a zoomed version of the regular graph) */ public class GraphWindow { private Rectangle dimensions; private int x; private int y; private int width; private int height; private BufferedImage roiOverlay; private BufferedImage markerOverlay; private BufferedImage spectrum; public GraphMarker leftMarker = new GraphMarker(); public GraphMarker centroidMarker = new GraphMarker(); public GraphMarker rightMarker = new GraphMarker(); private int windowHeight = 500; private int windowWidth = 1074; private int graphIndent = 25; private int stepLength; private int expandFactor; private double dataMax = 1; //Initilializes the GraphWindow, its position, drawing parameters and markers. public void init(int x, int y, int width, int height, int expandFactor, int stepLength) { this.x = x; this.y = y; this.width = width; this.height = height; this.stepLength = stepLength; this.expandFactor = expandFactor; dimensions = new Rectangle(x, y, width, height); spectrum = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); roiOverlay = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); markerOverlay = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); dimensions = new Rectangle(x, y, width, height); leftMarker.init(0, 0, 0, 0, 0, ColorMode.WHITE); centroidMarker.init(0, 0, 0, 0, 0, ColorMode.WHITE); rightMarker.init(0, 0, 0, 0, 0, ColorMode.WHITE); } //Resets the state of the GraphWindow. public void reset(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; dimensions = new Rectangle(x, y, width, height); spectrum = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); roiOverlay = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); markerOverlay = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); dimensions = new Rectangle(x, y, width, height); leftMarker.setHeight(height); centroidMarker.setHeight(height); rightMarker.setHeight(height); } //Sets the state of one of the graphMarkers. Possible types are "left", "centroid" and "right". public void setMarker(String type, int x, int y, int channel, int width, int height, ColorMode colorMode) { if (type.equals("left")) { leftMarker.init(x, y, channel, width, height, colorMode); redrawMarkers(); } else if (type.equals("centroid")) { centroidMarker.init(x, y, channel, width, height, colorMode); redrawMarkers(); } else if (type.equals("right")) { rightMarker.init(x, y, channel, width, height, colorMode); redrawMarkers(); } } public boolean contains(Point point) { return dimensions.contains(point); } //Redraws the ROI buffered image. public void redrawROIs(ArrayList<Double> data, EnumMap<DisplayMode, Boolean> displayMode, ColorMode colorMode, ArrayList<Point> ROIs) { Graphics2D g = roiOverlay.createGraphics(); g.setBackground(new Color(255, 255, 255, 0)); g.clearRect(0, 0, width, height); g.setColor(getColor(colorMode)); dataMax = getMax(data, displayMode.get(DisplayMode.LOG)); for (int i = 0; i < ROIs.size(); i++) { ArrayList<Double> roiData = new ArrayList<Double>(); int ch1 = ROIs.get(i).x; int ch2 = ROIs.get(i).y; for (int ch = ch1; ch <= ch2; ch++) { roiData.add(data.get(ch - 1)); } ArrayList<Double> plotData = yCalc(roiData, displayMode); if (displayMode.get(DisplayMode.POINTS)) { for (int j = 0; j < plotData.size(); j++) { int x; if (expandFactor / 4 == 0) { x = (ch1 - 1 + j) / 4 + graphIndent; } else { x = (ch1 - 1 + j) * (expandFactor / 4) + graphIndent * expandFactor; } g.fillRect(x, (int) (double) plotData.get(j), 1, 1); } } else if (displayMode.get(DisplayMode.ENVELOPE)) { for (int j = 0; j < plotData.size() - stepLength; j++) { int x1; int x2; if (expandFactor / 4 == 0) { x1 = ((ch1 - 1 + j) / 4 + graphIndent); x2 = (ch1 - 1 + j + stepLength) / 4 + graphIndent; } else { x1 = (ch1 - 1 + j) * (expandFactor / 4) + graphIndent * expandFactor; x2 = (ch1 - 1 + j + stepLength) * (expandFactor / 4) + graphIndent * expandFactor; } g.drawLine((int) x1, (int) (double) plotData.get(j), (int) x2, (int) (double) plotData.get(j + stepLength)); } } } } //redraws the markers buffered image. public void redrawMarkers() { Graphics2D g = markerOverlay.createGraphics(); g.setBackground(new Color(255, 255, 255, 0)); g.clearRect(0, 0, width, height); redrawLeftMarker(g); redrawRightMarker(g); redrawCentroidMarker(g); g.dispose(); } public void redrawLeftMarker(Graphics2D g) { g.setColor(getColor(leftMarker.getColorMode())); if (expandFactor / 4 == 0) { leftMarker.setDrawX(leftMarker.getX()); g.fillRect(leftMarker.getDrawX(), leftMarker.getY(), leftMarker.getWidth(), 1); g.fillRect(leftMarker.getDrawX(), leftMarker.getY() + leftMarker.getHeight() - 1, leftMarker.getWidth(), 1); g.fillRect(leftMarker.getDrawX() + leftMarker.getWidth(), leftMarker.getY(), 1, leftMarker.getHeight()); } else { leftMarker.setDrawX(((leftMarker.getX() + leftMarker.getWidth() * expandFactor - leftMarker.getWidth()) / (expandFactor / 4)) * (expandFactor / 4)); g.fillRect(leftMarker.getDrawX(), leftMarker.getY(), leftMarker.getWidth(), 1); g.fillRect(leftMarker.getDrawX(), leftMarker.getY() + leftMarker.getHeight() - 1, leftMarker.getWidth(), 1); g.fillRect(leftMarker.getDrawX() + leftMarker.getWidth(), leftMarker.getY(), 1, leftMarker.getHeight()); } } public void redrawCentroidMarker(Graphics2D g) { g.setColor(getColor(centroidMarker.getColorMode())); g.fillRect(centroidMarker.getX(), centroidMarker.getY(), 1, centroidMarker.getHeight()); } public void redrawRightMarker(Graphics2D g) { g.setColor(getColor(rightMarker.getColorMode())); if (expandFactor / 4 == 0) { rightMarker.setDrawX(rightMarker.getX()); g.fillRect(rightMarker.getDrawX(), rightMarker.getY(), rightMarker.getWidth(), 1); g.fillRect(rightMarker.getDrawX(), rightMarker.getY() + rightMarker.getHeight() - 1, rightMarker.getWidth(), 1); g.fillRect(rightMarker.getDrawX(), rightMarker.getY(), 1, rightMarker.getHeight()); } else { rightMarker.setDrawX((rightMarker.getX() / (expandFactor / 4)) * (expandFactor / 4)); g.fillRect(rightMarker.getDrawX(), rightMarker.getY(), rightMarker.getWidth(), 1); g.fillRect(rightMarker.getDrawX(), rightMarker.getY() + rightMarker.getHeight() - 1, rightMarker.getWidth(), 1); g.fillRect(rightMarker.getDrawX(), rightMarker.getY(), 1, rightMarker.getHeight()); } } //Redraws the spectrum buffered image public void redrawSpectrum(ArrayList<Double> data, EnumMap<DisplayMode, Boolean> displayMode, ColorMode backgroundColor, ColorMode dataColor) { dataMax = getMax(data, displayMode.get(DisplayMode.LOG)); ArrayList<Double> plotData = yCalc(data, displayMode); Graphics2D g = spectrum.createGraphics(); g.setColor(getColor(backgroundColor)); g.fillRect(0, 0, spectrum.getWidth(), spectrum.getHeight()); g.setColor(getColor(dataColor)); if (plotData.size() > 0) { if (displayMode.get(DisplayMode.POINTS)) { for (int i = 0; i < plotData.size(); i += stepLength) { int x; if (expandFactor / 4 == 0) { x = i / 4 + graphIndent; } else { x = i * (expandFactor / 4) + graphIndent * expandFactor; } g.fillRect(x, (int) (double) plotData.get(i), 1, 1); } } else if (displayMode.get(DisplayMode.ENVELOPE)) { for (int i = 0; i < plotData.size() - stepLength; i += stepLength) { int x1; int x2; if (expandFactor / 4 == 0) { x1 = (i / 4 + graphIndent); x2 = (i + stepLength) / 4 + graphIndent; } else { x1 = i * (expandFactor / 4) + graphIndent * expandFactor; x2 = (i + stepLength) * (expandFactor / 4) + graphIndent * expandFactor; } g.drawLine(x1, (int) (double) plotData.get(i), x2, (int) (double) plotData.get(i + stepLength)); } } g.setColor(getColor(dataColor)); g.dispose(); } } //Accepts graphData and scales it to be properly displayed in the GraphWindow. private ArrayList<Double> yCalc(ArrayList<Double> data, EnumMap<DisplayMode, Boolean> displayMode) { ArrayList<Double> plotData = new ArrayList<Double>(); for (int i = 0; i < data.size(); i++) { double y = data.get(i); if (displayMode.get(DisplayMode.LOG)) { y = Math.log(y); } // Normalize y = y / dataMax; // Scale to fit window y = y * (height - 2 * graphIndent); // Off set by indent y = y + graphIndent; // Invert direction y = height - y; // If y is negative, which can happen when using log scale, y i set // to // be plotted as 0. if (y > height) { y = height - graphIndent; } plotData.add(y); } return plotData; } private Color getColor(ColorMode colorMode) { switch (colorMode) { case RED: return Color.red; case BLACK: return Color.black; case WHITE: return Color.white; case YELLOW: return Color.yellow; case GREEN: return new Color(0, 100, 0); case MAGENTA: return Color.magenta; case CYAN: return Color.cyan; case BLUE: return Color.blue; default: return Color.yellow; } } //Gets the maximum value in the ArrayList data. The return value is altered by the boolean logMode. private double getMax(ArrayList<Double> data, boolean logMode) { double max = 0; for (int i = 0; i < data.size(); i++) { if (Math.log(data.get(i)) > max && logMode) { max = Math.log(data.get(i)); } else if (data.get(i) > max && !logMode) { max = data.get(i); } } return max; } public int getHeight() { return height; } public int getWidth() { return width; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } //Draws the buffered image layers on the Graphics g argument. The graphCamera defines a sub area of the graphWindow which is //to be displayed. An expanded graph window is oversized (to big to actually fit a screen), the graphCamera should //define an area which fits the GraphWindow. public void draw(Graphics g, GraphCamera graphCamera) { BufferedImage spectrumCameraImage = spectrum.getSubimage((int) ((graphCamera.x) * (expandFactor)), 0, (int) (graphCamera.width * (expandFactor)), height); BufferedImage roiCameraImage = roiOverlay.getSubimage((int) ((graphCamera.x) * (expandFactor)), 0, (int) (graphCamera.width * (expandFactor)), height); BufferedImage markerCameraImage = markerOverlay.getSubimage((int) ((graphCamera.x) * (expandFactor)), 0, (int) ((graphCamera.width) * (expandFactor)), height); g.drawImage(spectrumCameraImage, x, y, (int) (graphCamera.width * (expandFactor)), height, null); g.drawImage(roiCameraImage, x, y, (int) (graphCamera.width * (expandFactor)), height, null); g.drawImage(markerCameraImage, x, y, (int) (graphCamera.width * (expandFactor)), height, null); } //Draws the buffered image layers on the Graphics g argument. public void draw(Graphics g) { g.drawImage(spectrum, x, y, windowWidth, height, null); g.drawImage(roiOverlay, x, y, windowWidth, height, null); g.drawImage(markerOverlay, x, y, windowWidth, height, null); } }
package fr.campusacademy.oopcourse.tetrisproject.game; import org.newdawn.slick.BasicGame; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; public class SimpleSlickGame extends BasicGame { public SimpleSlickGame(String gamename) { super(gamename); } @Override public void init(GameContainer gc) throws SlickException {} @Override public void update(GameContainer gc, int i) throws SlickException {} @Override public void render(GameContainer gc, Graphics g) throws SlickException { g.drawString("Hello WORLD !", 100, 100); } }
package com.gxtc.huchuan.im.bean.dao; import com.gxtc.huchuan.im.bean.RemoteMessageBean; import com.gxtc.huchuan.im.bean.RemoteMessageBeanDao; import org.greenrobot.greendao.DaoException; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.OrderBy; import org.greenrobot.greendao.annotation.ToMany; import java.util.List; import com.gxtc.huchuan.bean.DaoSession; /** * Created by Gubr on 2017/4/26. */ @Entity public class ChatInfoBean { @Id private Long id; @ToMany(referencedJoinProperty = "targetId") @OrderBy("id ASC") private List<RemoteMessageBean> oders; /** Used to resolve relations */ @Generated(hash = 2040040024) private transient DaoSession daoSession; /** Used for active entity operations. */ @Generated(hash = 323600364) private transient ChatInfoBeanDao myDao; @Generated(hash = 591846069) public ChatInfoBean(Long id) { this.id = id; } @Generated(hash = 1948775465) public ChatInfoBean() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } /** * To-many relationship, resolved on first access (and after reset). * Changes to to-many relations are not persisted, make changes to the target entity. */ @Generated(hash = 1284088838) public List<RemoteMessageBean> getOders() { if (oders == null) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } RemoteMessageBeanDao targetDao = daoSession.getRemoteMessageBeanDao(); List<RemoteMessageBean> odersNew = targetDao._queryChatInfoBean_Oders(id); synchronized (this) { if (oders == null) { oders = odersNew; } } } return oders; } /** Resets a to-many relationship, making the next get call to query for a fresh result. */ @Generated(hash = 347137610) public synchronized void resetOders() { oders = null; } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 128553479) public void delete() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.delete(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 1942392019) public void refresh() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.refresh(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 713229351) public void update() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.update(this); } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 106133703) public void __setDaoSession(DaoSession daoSession) { this.daoSession = daoSession; myDao = daoSession != null ? daoSession.getChatInfoBeanDao() : null; } }
package com.thepoofy.website_searcher.csv.writer; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import com.thepoofy.website_searcher.models.MozResults; /** * * @author wvanderhoef */ public interface MozWriter { public void toFile(String fileName, List<MozResults> mozData) throws IOException, FileNotFoundException; }
package org.vpontus.vuejs.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; /** * @author vpontus */ public class OperationNotAllowedException extends AbstractThrowableProblem { public OperationNotAllowedException(String message) { super(ErrorConstants.OPERATION_NOT_ALLOWED,message, Status.NOT_ACCEPTABLE); } }
package servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import model.Professor; import service.PersonService; /** * Servlet implementation class searchProfessorServlet */ @WebServlet("/searchProfessorServlet") public class searchProfessorServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public searchProfessorServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8") ; response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); String title=""; String department=""; if(!request.getParameter("title").equals("")){ title=request.getParameter("title"); } if(!request.getParameter("department").equals("")){ department=request.getParameter("department"); } Professor professor=new Professor(); professor.setTitle(title); professor.setDepartment(department); try { PersonService personService=new PersonService(); List<Professor> results=personService.findProfessor(professor); JSONArray json = new JSONArray(); for (Professor result : results) { JSONObject jo = new JSONObject(); jo.put("ssn", result.getSsn()); jo.put("name", result.getName()); jo.put("department", result.getDepartment()); jo.put("title", result.getTitle()); json.put(jo); // System.out.println("jo"+jo); } //System.out.println(json); pw.println(json); } catch (SQLException | JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.kwik.repositories.product; import java.util.List; import com.kwik.models.Product; public interface ProductRepository { Product add(Product product); Product update(Product product); List<Product> listAll(); List<Product> findBy(List<Long> ids); Product findBy(Long id); void destroy(Product product); }
package old.Data20180411; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class WordBreakII { ArrayList<String> list = new ArrayList<>(); public static void main(String[] args) { String s = "catsanddog"; Set<String> dict = new HashSet<String>(); dict.add("cat"); dict.add("cats"); dict.add("and"); dict.add("sand"); dict.add("dog"); long ss = System.currentTimeMillis(); ArrayList<String> list = new WordBreakII().wordBreak2(s, dict); System.out.println(System.currentTimeMillis() - ss); ss = System.currentTimeMillis(); list = new WordBreakII().wordBreak(s, dict); System.out.println(System.currentTimeMillis() - ss); for(String s1 : list) { System.out.println(s1); } } public ArrayList<String> wordBreak(String s, Set<String> wordDict) { return DFS(s, wordDict, new HashMap<String, ArrayList<String>>()); } private ArrayList<String> DFS(String s, Set<String> wordDict, HashMap<String, ArrayList<String>> map) { if (map.containsKey(s)) return map.get(s); ArrayList<String> res = new ArrayList<String>(); if (s.length() == 0){ res.add(""); return res; } for (String subStr : wordDict) { if (s.startsWith(subStr)) { for (String str : DFS(s.substring(subStr.length()), wordDict, map)) { res.add(subStr + (str == "" ? "" : " ")+ str); } } } map.put(s, res); return res; } public ArrayList<String> wordBreak2(String s, Set<String> dict) { if(s.length() == 0) return list; boolean[][] dp = new boolean[s.length() + 1][s.length() + 1]; dp[0][0] = true; for(int i = 0; i < s.length(); i++){ for(int j = 0; j <= i; j++){ if(dp[j][i] == true){ for(int k = i + 1; k <= s.length(); k++){ String str = s.substring(i, k); if(dict.contains(str)){ dp[i][k] = true; } } } } } for(int i = 1; i < s.length(); i++){ if(dp[0][i] == true){ StringBuilder tempSb = new StringBuilder(); tempSb.append(s.substring(0, i)); addString(tempSb, dp, s, i); } } return list; } private void addString(StringBuilder sb, boolean[][] dp, String s, int start){ if(start == s.length()){ list.add(sb.toString()); return; } for(int i = start + 1; i <= s.length(); i++){ if(dp[start][i] == true){ StringBuilder tempSb = new StringBuilder(sb); tempSb.append(' ' + s.substring(start, i)); addString(tempSb, dp, s, i); } } } }
package com.mobdeve.s11.g32.tindergree.Adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.mobdeve.s11.g32.tindergree.Models.Chat; import com.mobdeve.s11.g32.tindergree.R; import com.mobdeve.s11.g32.tindergree.ViewHolders.CardViewHolder; import com.mobdeve.s11.g32.tindergree.ViewHolders.ChatViewHolder; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; public class ChatAdapter extends RecyclerView.Adapter<ChatViewHolder> { private ArrayList<Chat> chatDataset; private String uid; private String kachatName; public ChatAdapter(ArrayList<Chat> chatDataset, String uid, String kachatName) { this.chatDataset = chatDataset; this.uid = uid; this.kachatName = kachatName; } @NonNull @NotNull @Override public ChatViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.chat_layout, parent, false); return new ChatViewHolder(view); } @Override public void onBindViewHolder(@NonNull @NotNull ChatViewHolder holder, int position) { if (chatDataset.get(position).getSender().compareTo(uid) == 0) holder.setTv_sender("You:"); else holder.setTv_sender(kachatName + ":"); holder.setTv_message(chatDataset.get(position).getMessage()); } @Override public int getItemCount() { return this.chatDataset.size(); } }
package com.cmm.pay.refund.dto; import lombok.Data; import java.io.Serializable; @Data public class RefundNoticeResultDTO implements Serializable { private Integer code; //1:成功,-1:失败 private String msg; private String tradeNo; private Long refundSerialNo; }
package org.e7.s2nd.codec; /** * @author e7 */ public class BaseSerializer { public static byte[] shortToByteArray(int a) { return new byte[] { (byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF) }; } public static short byteArrayToShort(byte[] b) { return (short)((b[1] & 0xFF) | (b[0] & 0xFF) << 8); } public static byte[] intToByteArray(int a) { return new byte[] { (byte) ((a >> 24) & 0xFF), (byte) ((a >> 16) & 0xFF), (byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF) }; } public static int byteArrayToInt(byte[] b) { return (b[3] & 0xFF) | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24; } public static byte[] sliceByteArray(byte[] b, int from, int count) { byte[] bs = new byte[count]; System.arraycopy(b, from, bs, 0, count); return bs; } }
/* WebApp.java Purpose: Description: History: Fri Dec 9 16:23:08 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.net.URL; import java.io.InputStream; import org.zkoss.util.resource.Locator; import org.zkoss.zk.ui.util.Configuration; import org.zkoss.zk.ui.ext.Scope; /** * Represents a Web application. * A web application is usually in form of a war file. * An application might have multiple Web applications. * * <p>In HTTP, Web application represents a servlet context that supports ZK. * In other word, a Web application is created if * {@link org.zkoss.zk.ui.http.DHtmlLayoutServlet} is declared in web.xml. * * <p>To get the current Web application, use {@link Desktop#getWebApp}. * * @author tomyeh */ public interface WebApp extends Scope, Locator { /** Returns the application name, never null. * Developer can set it to any name that describes his application. * <p>Default: ZK */ public String getAppName(); /** Sets the applicationname. * Developer can set it to any name that describes his application. */ public void setAppName(String name); /** Returns the ZK version, such as "1.1.0" and "2.0.0". * @see #getSubversion * @see org.zkoss.util.Utils#parseVersion * @see org.zkoss.util.Utils#compareVersion */ public String getVersion(); /** Returns the build identifier, such as 2007121316. * * <p>Each time ZK is built, a different build identifier is assigned. * @since 3.0.1 */ public String getBuild(); /** Returns a portion of the version in an integer by specifying its index. * For example, getSubversion(0) returns the so-called major version * (2 in "2.4.0"), getSubversion(1) returns the so-called * minor version (4 in "2.4.0"), and both getSubversion(2) and getSubversion(3) * return 0. * * @param portion which portion of the version; starting from 0. * If you want to retrieve the major verion, specify 0. * @since 3.0.0 * @see #getVersion */ public int getSubversion(int portion); /** Returns the value of the specified custom attribute. */ public Object getAttribute(String name); /** Sets the value of the specified custom attribute. * @return the previous value if any (since ZK 5) */ public Object setAttribute(String name, Object value); /** Removes the specified custom attribute. * @return the previous value if any (since ZK 5) */ public Object removeAttribute(String name); /** Returns a map of custom attributes associated with this object. */ public Map getAttributes(); /** Returns the WebApp that corresponds to a specified URL on the server, * or null if either none exists or the container wishes to restrict * this access.. */ public WebApp getWebApp(String uripath); /** Returns a URL to the resource that is mapped to a specified path. * * <p>Notice that, since 3.6.3, this method can retreive the resource * starting with "~./". If the path contains the wildcard ('*'), * you can use {@link Execution#locate} to convert it to a proper * string first. */ public URL getResource(String path); /** Returns the resource located at the named path as * an InputStream object. * * <p>Notice that, since 3.6.3, this method can retreive the resource * starting with "~./". If the path contains the wildcard ('*'), * you can use {@link Execution#locate} to convert it to a proper * string first. */ public InputStream getResourceAsStream(String path); /** Returns a String containing the real path for a given virtual path. * For example, the path "/index.html" returns the absolute file path * on the server's filesystem would be served by a request for * "http://host/contextPath/index.html", where contextPath is * the context path of this {@link WebApp}. * * <p>Notice that ZK don't count on this method to retrieve resources. * If you want to change the mapping of URI to different resources, * override {@link org.zkoss.zk.ui.sys.UiFactory#getPageDefinition} * instead. */ public String getRealPath(String path); /** Returns the MIME type of the specified file, or null if the MIME type * is not known. The MIME type is determined by the configuration of * the Web container. * <p>Common MIME types are "text/html" and "image/gif". */ public String getMimeType(String file); /** Returns a directory-like listing of all the paths to resources * within the web application whose longest sub-path matches the * supplied path argument. Paths indicating subdirectory paths * end with a '/'. The returned paths are all relative to * the root of the web application and have a leading '/'. * For example, for a web application containing <pre><code> /welcome.html /catalog/index.html /catalog/products.html /catalog/offers/books.html /catalog/offers/music.html /customer/login.jsp /WEB-INF/web.xml /WEB-INF/classes/com.acme.OrderServlet.class, getResourcePaths("/") returns {"/welcome.html", "/catalog/", "/customer/", "/WEB-INF/"} getResourcePaths("/catalog/") returns {"/catalog/index.html", "/catalog/products.html", "/catalog/offers/"}. </code> </pre> */ public Set getResourcePaths(String path); /** Returns the value of the named context-wide initialization parameter, * or null if the parameter does not exist. */ public String getInitParameter(String name); /** Returns the names of the context's initialization parameters as * an Iterator of String objects, or an empty Iterator if the context * has no initialization parameters. */ public Iterator getInitParameterNames(); /** Returns the URI for asynchronous update. * <p>Both {@link #getUpdateURI} and {@link Desktop#getUpdateURI} * are encoded with {@link Execution#encodeURL} * @see Desktop#getUpdateURI * @exception NullPointerException if the current execution is not available * @since 3.6.2 */ public String getUpdateURI(); /** Returns the URI for asynchronous update that can be encoded or * not. * * @param encode whether to encode with {@link Execution#encodeURL}. * It is the same as {@link #getUpdateURI()} if <code>encode</code> is true. * @since 5.0.0 * @exception NullPointerException if the current execution is not available * and encode is true. */ public String getUpdateURI(boolean encode); /** Returns the configuration. */ public Configuration getConfiguration(); /** Returns the native application context, or null if not available. * * <p>The returned object depends on the Web container. * If it is based Java servlet container, an instance of * javax.servlet.Servletcontext is returned. */ public Object getNativeContext(); }
package com.example.macintosh.moviesprojectstage1; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; public class ViewPagerAdapter extends FragmentStatePagerAdapter { private int mCurrentPosition = -1; private final List<Fragment> fragmentList = new ArrayList<>(); private final List<String> fragmentTitles = new ArrayList<>(); public ViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return fragmentList.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return fragmentTitles.get(position); } public void addFragment(Fragment fragment,String title){ fragmentList.add(fragment); fragmentTitles.add(title); } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { super.setPrimaryItem(container, position, object); if (position != mCurrentPosition && container instanceof CustomViewPager) { Fragment fragment = (Fragment) object; CustomViewPager pager = (CustomViewPager) container; if (fragment != null && fragment.getView() != null) { mCurrentPosition = position; pager.measureCurrentView(fragment.getView()); } } } }
package com.wjfit.introspector; public class User { private String name; private int age; private boolean man; //属性名:name public void setName(String name) { this.name = name; } //属性名:age public int getAge() { return age; } //属性名:man public boolean isMan() { return man; } //属性名:man public void setMan(boolean man) { this.man = man; } @Override public String toString() { return "User [name=" + name + "]"; } }
package io.github.cottonmc.libcd.api.tweaker; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import net.minecraft.class_2960; public class TweakerManager { public static final TweakerManager INSTANCE = new TweakerManager(); private TweakerManager() {} private List<Tweaker> tweakers = new ArrayList<>(); private Map<Tweaker, String> tweakerNames = new HashMap<>(); private Map<String, Function<ScriptBridge, Object>> assistants = new HashMap<>(); private Map<class_2960, TweakerStackFactory> factories = new HashMap<>(); /** * Add a new tweaker to store data in. * @param name A name to pass to `libcd.require`. Names shared with addAssistant(Factory). Namespace with package notation, ex. `libcd.util.TweakerUtils` * @param tweaker An instanceof Tweaker to call whenever reloading. * For deprecation purposes, the final part of the package-notated name will be passed directly to the script on its own. */ public void addTweaker(String name, Tweaker tweaker) { tweakers.add(tweaker); tweakerNames.put(tweaker, name); assistants.put(name, (id) -> { tweaker.prepareFor(id); return tweaker; }); } /** * Add a new assistant class for tweakers to access through `libcd.require`. * DO NOT PASS TWEAKER INSTANCES HERE. They are automatically added in addTweaker. * @param name A name to pass to `libcd.require`. Names shared with addTweaker and addAssistantFactory. Namespace with package notation, ex. `libcd.util.TweakerUtils` * @param assistant An object of a class to use in scripts. */ public void addAssistant(String name, Object assistant) { assistants.put(name, id -> assistant); } /** * Add a factory for assistants which have methods affected by script ID. * @param name A name to pass to `require`. Names shared with addTweaker and addAssistant. Namespace with package notation, x. `libcd.util.TweakerUtils` * @param factory A function that takes an identifier and returns an object of a class to use in scripts. * For deprecation purposes, the final part of the package-notated name will be passed directly to the script on its own. */ public void addAssistantFactory(String name, Function<ScriptBridge, Object> factory) { assistants.put(name, factory); } public void addStackFactory(class_2960 id, TweakerStackFactory getter) { factories.put(id, getter); } public List<Tweaker> getTweakers() { return tweakers; } public Object getAssistant(String name, ScriptBridge scriptFrom) { return assistants.get(name).apply(scriptFrom); } public Map<class_2960, TweakerStackFactory> getStackFactories() { return factories; } public String getTweakerName(Tweaker tweaker) { return tweakerNames.get(tweaker); } }
package net.mv.dao; import org.hibernate.Session; public class AnimalWebDAO { public static Animal lookup(String id) { Session session = null; session = HibernateUtility.getSessionFactory().openSession(); //transaction? long l_id = Long.parseLong(id); System.out.println(l_id); Animal a1 = (Animal)session.get(Animal.class, l_id); session.close(); return a1; } }
package com.koreait.board2.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.koreait.board2.model.BoardCmtVO; import com.koreait.board2.model.BoardVO; public class BoardDAO { // 페이징 public static int selPageCount(final BoardVO param) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = " SELECT ceil(COUNT(i_board) / ?) " + " FROM t_board_? "; // 데이터의 총 개수 / 리스트에 보여질 게시물의 최대 개수 try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, param.getRowCntPerPage()); pstmt.setInt(2, param.getTyp()); rs = pstmt.executeQuery(); if(rs.next()) { return rs.getInt(1); // 가장 첫번째 결과값을 가지고 온다 } } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt, rs); } return 0; } // 서브 페이지의 글 목록 확인 public static List<BoardVO> selBoard(final BoardVO param){ List<BoardVO> list = new ArrayList<>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = " SELECT i_board, title, hits, r_dt " + " FROM t_board_? ORDER BY i_board DESC " + " LIMIT ?, ? "; try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, param.getTyp()); pstmt.setInt(2, param.getS_Index()); // 0 pstmt.setInt(3, param.getRowCntPerPage()); // 가져올 데이터 개수 rs = pstmt.executeQuery(); while(rs.next()) { BoardVO vo = new BoardVO(); vo.setI_board(rs.getInt("i_board")); vo.setTitle(rs.getString("title")); vo.setR_dt(rs.getString("r_dt")); vo.setHits(rs.getInt("hits")); list.add(vo); } } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt, rs); } return list; } // 글 읽기 public static void readBoard(final BoardVO param) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = " SELECT i_board, title, ctnt, r_dt, hits " + " FROM t_board_? WHERE i_board = ? "; try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, param.getTyp()); pstmt.setInt(2, param.getI_board()); rs = pstmt.executeQuery(); if(rs.next()) { param.setI_board(rs.getInt("i_board")); param.setTitle(rs.getString("title")); param.setCtnt(rs.getString("ctnt")); param.setR_dt(rs.getString("r_dt")); param.setHits(rs.getInt("hits")); } } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt, rs); } } // 댓글 읽기 public static List<BoardCmtVO> readCmtList(final BoardVO param){ List<BoardCmtVO> list = new ArrayList<>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = " SELECT i_cmt, ctnt FROM t_board_cmt_? " + " WHERE i_board = ? " + " ORDER BY i_board DESC "; try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, param.getTyp()); pstmt.setInt(2, param.getI_board()); rs = pstmt.executeQuery(); while(rs.next()) { BoardCmtVO cmtVo = new BoardCmtVO(); cmtVo.setI_cmt(rs.getInt("i_cmt")); cmtVo.setCtnt(rs.getString("ctnt")); list.add(cmtVo); } } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt, rs); } return list; } // 글 쓰기 public static int insBoard(BoardVO param) { int result = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = " INSERT INTO t_board_? (title, ctnt) " + " VALUES (?, ?) "; try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setInt(1, param.getTyp()); pstmt.setString(2, param.getTitle()); pstmt.setString(3, param.getCtnt()); result = pstmt.executeUpdate(); // PK값을 가져온다 rs = pstmt.getGeneratedKeys(); if(rs.next()) { int i_board = rs.getInt(1); // 1번쩨 컬럼을 얻어와서 System.out.println("ins i_board = " + i_board); param.setI_board(i_board); // i_board의 값을 1번으로 바꾼다(원래 0번) } } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt, rs); } return result; } // 글 수정 public static int upBoard(BoardVO param) { int result = 0; Connection conn = null; PreparedStatement pstmt = null; String sql = " UPDATE t_board_? SET title = ?, ctnt = ? WHERE i_board = ? "; try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, param.getTyp()); pstmt.setString(2, param.getTitle()); pstmt.setString(3, param.getCtnt()); pstmt.setInt(4, param.getI_board()); result = pstmt.executeUpdate(); } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt); } return result; } // 조회수 증가 public static void addHits(BoardVO param) { Connection conn = null; PreparedStatement pstmt = null; String sql = " UPDATE t_board_? SET hits = hits + 1 " + " WHERE i_board = ? "; try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, param.getTyp()); pstmt.setInt(2, param.getI_board()); pstmt.executeUpdate(); } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt); } } // 글 삭제 public static int delBoard(final BoardVO param) { int result = 0; Connection conn = null; PreparedStatement pstmt = null; String sql = " DELETE FROM t_board_? WHERE i_board = ? "; try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, param.getTyp()); pstmt.setInt(2, param.getI_board()); result = pstmt.executeUpdate(); } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt); } return result; } // AOP public static int myExecuteUpdate(String sql, SQLInterUpdate sqlInter) { Connection conn = null; PreparedStatement pstmt = null; try { conn = DBUtils.getConn(); pstmt = conn.prepareStatement(sql); sqlInter.proc(pstmt); return pstmt.executeUpdate(); } catch (Exception e) { e.getMessage(); } finally { DBUtils.close(conn, pstmt); } return 0; } }
package com.daexsys.automata.event.tile; import com.daexsys.automata.Tile; import com.daexsys.automata.event.Event; public class TileAlterEvent implements Event { private Tile tile; private TilePlacementReason tileAlterCause; public TileAlterEvent(Tile tile, TilePlacementReason tileAlterCause) { this.tile = tile; this.tileAlterCause = tileAlterCause; } public Tile getTile() { return tile; } public TilePlacementReason getTileAlterCause() { return tileAlterCause; } }
package br.cefetrj.sca.dominio.repositories; import java.io.Serializable; import org.springframework.data.jpa.repository.JpaRepository; import br.cefetrj.sca.dominio.Departamento; public interface DepartamentoRepositorio extends JpaRepository<Departamento, Serializable> { public Departamento findDepartamentoById(Long id); }
package dk.webbies.tscreate.paser.AST; import com.google.javascript.jscomp.parsing.parser.util.SourceRange; import dk.webbies.tscreate.paser.ExpressionVisitor; import java.util.Collections; /** * This can only occur as expressions in properties of objects. */ public class GetterExpression extends Expression { private final BlockStatement body; GetterExpression(SourceRange location, BlockStatement body) { super(location); this.body = body; } public BlockStatement getBody() { return body; } @Override public <T> T accept(ExpressionVisitor<T> visitor) { return visitor.visit(this); } FunctionExpression function = null; private static int getterCounter = 0; public FunctionExpression asFunction() { if (function == null) { Identifier identifier = new Identifier(this.location, ":getter" + getterCounter++); function = new FunctionExpression(this.location, identifier, body, Collections.EMPTY_LIST); } return function; } }
package entities; import javax.persistence.CascadeType; import javax.persistence.OneToMany; import javax.persistence.Transient; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; @javax.persistence.Entity public class University extends Entity implements Serializable { private static final long serialVersionUID = 6529685098267757690L; @OneToMany(cascade= CascadeType.ALL) private List<Teacher> teacherList = new ArrayList(); @OneToMany(cascade= CascadeType.ALL) private List<StudentsGroupImpl> studentsGroupImplList = new ArrayList(); @OneToMany(cascade= CascadeType.ALL) private List<Course> courseList = new ArrayList(); @Transient private StudentsGroupImpl selectedStudentsGroupImpl; public void setSelectedCourse(Object selectedCourse) { this.selectedCourse = (Course) selectedCourse; } @Transient private Course selectedCourse; public Course getSelectedCourse() { return selectedCourse; } public University(String name) { super(name); } public University() { } public void setSelectedStudentsGroupImpl(Object selectedStudentsGroupImpl) { this.selectedStudentsGroupImpl = (StudentsGroupImpl) selectedStudentsGroupImpl; } public StudentsGroupImpl getSelectedStudentsGroupImpl() { return selectedStudentsGroupImpl; } //Groups //region public List<StudentsGroupImpl> getStudentsGroupImplList() { return studentsGroupImplList; } public void addGroup(StudentsGroupImpl studentsGroupImpl) { studentsGroupImplList.add(studentsGroupImpl); } public void addGroup(String name) { StudentsGroupImpl studentsGroupImpl = new StudentsGroupImpl(name); studentsGroupImplList.add(studentsGroupImpl); } public StudentsGroupImpl getGroupByID(int id) { for (StudentsGroupImpl studentsGroupImpl : this.getStudentsGroupImplList()) { if (studentsGroupImpl.getId() == id) { return studentsGroupImpl; } } return null; } public void removeGroup(Object groupToRemove) { studentsGroupImplList.remove(groupToRemove); } //endregion //Courses //region public List<Course> getCourseList() { return courseList; } public void removeCourse(Object courseToRemove) { courseList.remove(courseToRemove); for (StudentsGroupImpl studentsGroupImpl : studentsGroupImplList) { studentsGroupImpl.getGroupCourses().remove(courseToRemove); } for (Teacher teacher : teacherList) { teacher.getTeacherCourses().remove(courseToRemove); } } public void addCourse(Course course) { courseList.add(course); } public Course getCourseByID(int id) { Course courseMatch = null; for (Course course : this.getCourseList()) { if (course.getId() == id) { courseMatch = course; break; } } return courseMatch; } //endregion //Teachers // region public List<Teacher> getTeacherList() { return teacherList; } public void addTeacher(Teacher teacher) { this.teacherList.add(teacher); } public void removeTeacher(Object teacherToRemove) { System.out.println("remooving"); teacherList.remove(teacherToRemove); } public Teacher getTeacherByID(int id) { Teacher teacherMatch = null; for (Teacher teacher : this.getTeacherList()) { if (teacher.getId() == id) { teacherMatch = teacher; return teacherMatch; } } //if (teacherMatch==null) throw new IllegalArgumentException(" !entities.Teacher with this ID does not exist!"); return null; } public void addTeacher(String name, String surname) { Teacher teacher = new Teacher(name, surname); teacherList.add(teacher); } public void removeTeacher(Teacher teacherToRemove) { try { teacherList.remove(teacherToRemove); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(" !entities.Teacher does not exist!"); } } //endregion //General public List<Student> getAllStudents() { List<Student> allStudents = new ArrayList<>(); for (StudentsGroupImpl studentsGroupImpl : studentsGroupImplList) { allStudents.addAll(studentsGroupImpl.getGroupStudents()); } return allStudents; } public Student getStudentById(int studentId) { List<Student> studentList = getAllStudents(); for (Student student : studentList) { if (student.getId() == studentId) { return student; } } throw new NoSuchElementException("Student not found"); } }
package com.donkeymonkey.recyq.defines; public class Defines { // Waster locations public class NearestWasteLocation { public final static String kAmsterdamsePoort = "A'damse Poort"; public final static String kHBuurt = "H-Buurt"; public final static String kHolenDrecht = "Holendrecht"; public final static String kVenserPoler = "Venserpolder"; public final String wasteLocation; public NearestWasteLocation(String wasteLocation) { this.wasteLocation = wasteLocation; } } public enum WasteLocationColors { } }
/* CAFileFilter -- a class within the Cellular Automaton Explorer. Copyright (C) 2007 David B. Bahr (http://academic.regis.edu/dbahr/) 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 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package cellularAutomata.util.files; import java.io.File; import javax.swing.filechooser.FileFilter; import cellularAutomata.CAConstants; /** * A filter (for JFileChoosers) that only allows ".ca" file types. */ public class CAFileFilter extends FileFilter { /** * This filter's supported file types. */ public final static String CA = CAConstants.CA_FILE_EXTENSION; /** * File types accepted by this filter. */ private final static String[] PERMITTED_FILE_TYPES = {CA}; /** * Get the extension of a file in lower case. * * @param f * The file whose extension will be determined. * * @return The extension, or null if there is no extension. */ public static String getExtension(File f) { String extension = null; if(f != null) { String fileName = f.getName(); int i = fileName.lastIndexOf('.'); if(i > 0 && i < fileName.length() - 1) { extension = fileName.substring(i + 1).toLowerCase(); } } return extension; } /** * A list of accepted file types. * * @return the accepted file types. */ public static String[] getPermittedFileTypes() { return PERMITTED_FILE_TYPES; } /** * Accept only CA files. * * @param f * The file. * * @return true if the file is one of the supported types. */ public boolean accept(File f) { if(f.isDirectory()) { return true; } String extension = getExtension(f); if(extension != null) { for(String permittedExtension : PERMITTED_FILE_TYPES) { if(extension.equals(permittedExtension)) { return true; } } } return false; } /** * Gets the extension of the path for the given file. * * @param filePath * The file whose extension will be determined. * * @return The extension, or an empty string if there is no extension. */ public static String getExtension(String filePath) { String extension = ""; int i = filePath.lastIndexOf('.'); if(i > 0 && i < filePath.length() - 1) { extension = filePath.substring(i + 1).toLowerCase(); } return extension; } /** * The description used for display in the JChooser. */ public String getDescription() { return CAConstants.PROGRAM_TITLE + " (" + getListOfPermittedFileTypes() + ")"; } /** * A descriptive list of permitted file types. */ public static String getListOfPermittedFileTypes() { String allTypes = ""; for(String type : PERMITTED_FILE_TYPES) { allTypes += "." + type + ", "; } // get rid of the last extraneous "," allTypes = allTypes.substring(0, allTypes.lastIndexOf(",")); return allTypes; } /** * Decides if the file extension is one of the supported file formats for * this filter. * * @param extension * The extension being tested, which should not include a "." * @return true if the extension matches one of the supported image formats. */ public static boolean isPermittedFileType(String extension) { boolean supported = false; if(extension != null) { for(int i = 0; i < PERMITTED_FILE_TYPES.length; i++) { if(extension.equalsIgnoreCase(PERMITTED_FILE_TYPES[i])) { supported = true; } } } return supported; } }
package vehicles.interf; public interface Travel { double countSpeed(); }
package org.apache.bookkeeper.proto; import com.google.protobuf.ByteString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.proto.PacketProcessorBaseV3; import org.apache.bookkeeper.proto.NIOServerFactory.Cnxn; import org.apache.bookkeeper.stats.BookkeeperServerStatsLogger.BookkeeperServerOp; import org.apache.bookkeeper.stats.ServerStatsProvider; import org.apache.bookkeeper.util.MathUtils; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class ReadEntryProcessorV3 extends PacketProcessorBaseV3 implements Runnable { private final static Logger logger = LoggerFactory.getLogger(ReadEntryProcessorV3.class); public ReadEntryProcessorV3(Request request, Cnxn srcConn, Bookie bookie) { super(request, srcConn, bookie); } private ReadResponse getReadResponse() { final long startTimeMillis = MathUtils.now(); ReadRequest readRequest = request.getReadRequest(); long ledgerId = readRequest.getLedgerId(); long entryId = readRequest.getEntryId(); ReadResponse.Builder readResponse = ReadResponse.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId); if (!isVersionCompatible()) { readResponse.setStatus(StatusCode.EBADVERSION); return readResponse.build(); } StatusCode status; ByteBuffer entryBody = null; try { Future<Boolean> fenceResult = null; if (readRequest.hasFlag() && readRequest.getFlag().equals(ReadRequest.Flag.FENCE_LEDGER)) { logger.warn("Ledger fence request received for ledger:" + ledgerId + " from address:" + srcConn.getPeerName()); // TODO: Move this to a different request which definitely has the master key. if (!readRequest.hasMasterKey()) { logger.error("Fence ledger request received without master key for ledger:" + ledgerId + " from address:" + srcConn.getRemoteAddress()); throw BookieException.create(BookieException.Code.UnauthorizedAccessException); } else { byte[] masterKey = readRequest.getMasterKey().toByteArray(); fenceResult = bookie.fenceLedger(ledgerId, masterKey); } } entryBody = bookie.readEntry(ledgerId, entryId); if (null != fenceResult) { // TODO: // currently we don't have readCallback to run in separated read // threads. after BOOKKEEPER-429 is complete, we could improve // following code to make it not wait here // // For now, since we only try to wait after read entry. so writing // to journal and read entry are executed in different thread // it would be fine. try { Boolean fenced = fenceResult.get(1000, TimeUnit.MILLISECONDS); if (null == fenced || !fenced) { // if failed to fence, fail the read request to make it retry. status = StatusCode.EIO; } else { status = StatusCode.EOK; readResponse.setBody(ByteString.copyFrom(entryBody)); } } catch (InterruptedException ie) { logger.error("Interrupting fence read entry (lid:" + ledgerId + ", eid:" + entryId + ") :", ie); status = StatusCode.EIO; } catch (ExecutionException ee) { logger.error("Failed to fence read entry (lid:" + ledgerId + ", eid:" + entryId + ") :", ee); status = StatusCode.EIO; } catch (TimeoutException te) { logger.error("Timeout to fence read entry (lid:" + ledgerId + ", eid:" + entryId + ") :", te); status = StatusCode.EIO; } } else { readResponse.setBody(ByteString.copyFrom(entryBody)); status = StatusCode.EOK; } } catch (Bookie.NoLedgerException e) { status = StatusCode.ENOLEDGER; logger.error("No ledger found while reading entry:" + entryId + " from ledger:" + ledgerId); } catch (Bookie.NoEntryException e) { status = StatusCode.ENOENTRY; if (logger.isDebugEnabled()) { logger.debug("No entry found while reading entry:" + entryId + " from ledger:" + ledgerId); } } catch (IOException e) { status = StatusCode.EIO; logger.error("IOException while reading entry:" + entryId + " from ledger:" + ledgerId); } catch (BookieException e) { logger.error("Unauthorized access to ledger:" + ledgerId + " while reading entry:" + entryId + " in request " + "from address:" + srcConn.getPeerName()); status = StatusCode.EUA; } long latencyMillis = MathUtils.now() - startTimeMillis; if (status.equals(StatusCode.EOK)) { ServerStatsProvider.getStatsLoggerInstance().getOpStatsLogger(BookkeeperServerOp .READ_ENTRY).registerSuccessfulEvent(latencyMillis); } else { ServerStatsProvider.getStatsLoggerInstance().getOpStatsLogger(BookkeeperServerOp .READ_ENTRY).registerFailedEvent(latencyMillis); } // Finally set status and return. The body would have been updated if // a read went through. readResponse.setStatus(status); return readResponse.build(); } @Override public void run() { ReadResponse readResponse = getReadResponse(); Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(readResponse.getStatus()) .setReadResponse(readResponse); srcConn.sendResponse(encodeResponse(response.build())); } }
package com.infohold.bdrp.org.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.lang3.builder.HashCodeBuilder; import com.infohold.core.model.BaseIdModel; import com.infohold.core.utils.StringUtils; /** * Created by IBUP model engine. Model code : Org Edited by : iBSDS Edited on * 2012-05-30 11:24:19 */ @Entity @Table(name = "IH_ORG") public class Org extends BaseIdModel { private static final long serialVersionUID = 8252802287306624802L; // private String id; private String name; private String status; private String parentId; private Org parent; private String brcCode; private String province; private String effectDate; private String licnum; private String mobile; private String idNo; private String cascade; private String type; private String type2; private String shortName; private String phone; private String mobile1; private String enName; private String visaAddress; private String address; private String tags; private String phone1; private String idType; private String custCode; private String isLeaf; private String memo; private String zip; private String expirDate; private String upDate; private String visaDate; private String categry; private String city; private Integer lvl; private String siId; private int numberOfemployees; // @Id // @Column(name = "ID", nullable = false,length=32) // @GeneratedValue(generator="customer-assigned") // @GenericGenerator(name="customer-assigned",strategy="assigned") // public String getId(){ // return this.id; // } // // public void setId(String id){ // this.id = id; // } @Column(name = "BRCCODE", length = 6, updatable = false) public String getBrcCode() { return brcCode; } public void setBrcCode(String brcCode) { this.brcCode = brcCode; } public void setProvince(String province) { this.province = province; } @Column(name = "PROVINCE", length = 6) public String getProvince() { return this.province; } public void setEffectDate(String effectDate) { this.effectDate = effectDate; } @Column(name = "EFFECTIVEDATE", length = 10) public String getEffectDate() { return this.effectDate; } public void setLicnum(String licnum) { this.licnum = licnum; } @Column(name = "LICNUM", length = 50) public String getLicnum() { return this.licnum; } public void setMobile(String mobile) { this.mobile = mobile; } @Column(name = "MOBILE", length = 50) public String getMobile() { return this.mobile; } public void setIdNo(String idNo) { this.idNo = idNo; } @Column(name = "IDNO", length = 18) public String getIdNo() { return this.idNo; } public void setCascade(String cascade) { this.cascade = cascade; } @Column(name = "CASCAD", length = 50) public String getCascade() { return this.cascade; } public void setType(String type) { this.type = type; } @Column(name = "TYPE", length = 50) public String getType() { return this.type; } @Column(name = "TYPE2", length = 10) public String getType2() { return type2; } public void setType2(String type2) { this.type2 = type2; } public void setAddress(String address) { this.address = address; } @Column(name = "ADDRESS", length = 10) public String getAddress() { return this.address; } public void setMobile1(String mobile1) { this.mobile1 = mobile1; } @Column(name = "MOBILE1", length = 50) public String getMobile1() { return this.mobile1; } public void setPhone(String phone) { this.phone = phone; } @Column(name = "PHONE", length = 50) public String getPhone() { return this.phone; } public void setShortName(String shortName) { this.shortName = shortName; } @Column(name = "SHORTNAME", length = 20) public String getShortName() { return this.shortName; } // @ManyToOne(cascade = CascadeType.REFRESH, optional = true) // @JoinColumn(name = "PARENT") // @NotFound(action=NotFoundAction.IGNORE) @Transient public Org getParent() { return parent; } public void setParent(Org parent) { this.parent = parent; } public void setEnName(String enName) { this.enName = enName; } @Column(name = "ENNAME", length = 50) public String getEnName() { return this.enName; } public void setTags(String tags) { this.tags = tags; } @Column(name = "TAGS", length = 100) public String getTags() { return this.tags; } public void setVisaAddress(String visaAddress) { this.visaAddress = visaAddress; } @Column(name = "VISAADDR", length = 100) public String getVisaAddress() { return this.visaAddress; } public void setExpirDate(String expirDate) { this.expirDate = expirDate; } @Column(name = "EXPIREDDATE", length = 10) public String getExpirDate() { return this.expirDate; } public void setUpDate(String upDate) { this.upDate = upDate; } @Column(name = "UPDATEDON", length = 19) public String getUpDate() { return this.upDate; } public void setLvl(Integer lvl) { this.lvl = lvl; } @Column(name = "LVL") public Integer getLvl() { return this.lvl; } public void setPhone1(String phone1) { this.phone1 = phone1; } @Column(name = "PHONE1", length = 50) public String getPhone1() { return this.phone1; } public void setStatus(String status) { this.status = status; } @Column(name = "STATUS", length = 1) public String getStatus() { return this.status; } public void setCity(String city) { this.city = city; } @Column(name = "CITY", length = 6) public String getCity() { return this.city; } public void setCategry(String categry) { this.categry = categry; } @Column(name = "CATEGRY", length = 50) public String getCategry() { return this.categry; } public void setVisaDate(String visaDate) { this.visaDate = visaDate; } @Column(name = "VISADATE", length = 19) public String getVisaDate() { return this.visaDate; } public void setZip(String zip) { this.zip = zip; } @Column(name = "ZIP", length = 6) public String getZip() { return this.zip; } public void setIsLeaf(String isLeaf) { this.isLeaf = isLeaf; } @Column(name = "ISLEAF", length = 1) public String getIsLeaf() { return this.isLeaf; } public void setMemo(String memo) { this.memo = memo; } @Column(name = "MEMO", length = 500) public String getMemo() { return this.memo; } public void setCustCode(String custCode) { this.custCode = custCode; } @Column(name = "CUSTCODE", length = 30, updatable = false) public String getCustCode() { return this.custCode; } public void setIdType(String idType) { this.idType = idType; } @Column(name = "IDTYPE", length = 2) public String getIdType() { return this.idType; } public void setName(String name) { this.name = name; } @Column(name = "NAME", nullable = false, length = 100) public String getName() { return this.name; } @Column(name = "SI_ID") public String getSiId() { return siId; } public void setSiId(String siId) { this.siId = siId; } @Column(name = "EMPLOYEES") public int getNumberOfemployees() { return numberOfemployees; } public void setNumberOfemployees(int numberOfemployees) { this.numberOfemployees = numberOfemployees; } @Column(name = "PARENT") public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } @Override public boolean _newObejct() { return StringUtils.isEmpty(this.id); } /** * 重载hashCode; */ public int hashCode() { return new HashCodeBuilder().append(this).toHashCode(); } }
package com.jrz.bettingsite.event; import com.jrz.bettingsite.team.Team; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.Optional; @Controller public class EventController { @Autowired private EventService eventService; @RequestMapping(path = "/events") public @ResponseBody Iterable<Event> getAllEvents() { return eventService.findAll(); } @RequestMapping(path = "/events/{id}") public @ResponseBody Optional<Event> getEventById(@PathVariable Long id){ return eventService.findById(id); } @RequestMapping(method = RequestMethod.POST, path = "/events") public void saveEvent(@RequestBody Event event){ eventService.saveEvent(event); } @RequestMapping(method = RequestMethod.PUT, path = "/events/{id}") public @ResponseBody void updateEvent(@RequestBody Event event, @PathVariable Long id){ eventService.updateEvent(event, id); } @RequestMapping(method = RequestMethod.DELETE, path = "/events/{id}") public @ResponseBody void deleteEvent(@RequestBody Event event, @PathVariable Long id){ eventService.deleteEvent(event); } }
//Created by MyEclipse Struts // XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.8.2/xslt/JavaClass.xsl package com.aof.webapp.action.helpdesk; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.aof.component.helpdesk.servicelevel.SLACategoryService; import com.aof.component.helpdesk.servicelevel.SLAMaster; import com.aof.component.helpdesk.servicelevel.SLAMasterService; import com.aof.webapp.action.ActionUtils; import com.aof.webapp.action.BaseAction; /** * MyEclipse Struts * Creation date: 11-16-2004 * * XDoclet definition: * @struts:action validate="true" */ public class SLACategoryTreeDialogAction extends com.shcnc.struts.action.BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Integer masterid = ActionUtils.parseInt(request.getParameter("masterid")); if (masterid == null) { String partyid = request.getParameter("partyid"); SLAMaster master = new SLAMasterService().findActiveByPartyId(partyid); masterid = master.getId(); } request.setAttribute("X_xml", new SLACategoryService().getAllForMasterAsXml(masterid, getLocale(request))); return mapping.findForward("jsp"); } }
package TreeMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class Treemap { public static void main(String[] args) { Student2 s1 = new Student2("Bindu","1"); Student2 s2 = new Student2("Priya","2"); Student2 s3 = new Student2("Deepu","3"); Student2 s4 = new Student2("Anu"," 4"); Student2 s5 = new Student2("Kiran","5"); Library l1 = new Library(101,20); Library l2 = new Library(102,30); Library l3 = new Library(105,40); Library l4 = new Library(103,25); Library l5 = new Library(104,35); TreeMap<Library,Student2>hm = new TreeMap<>(); hm.put(l1,s1); hm.put(l2,s2); hm.put(l3,s3); hm.put(l4,s4); hm.put(l5,s5); System.out.println("LibraryNum TotalBooks StudentName Semester "); for(Map.Entry<Library, Student2>entry:hm.entrySet()) { Library lb1 = entry.getKey(); Student2 st1 = entry.getValue(); System.out.println(lb1.libNum+" "+lb1.totalBooks+" "+st1.name+" "+st1.semester); } } }
package com.vmware.onlinetest; import java.util.Arrays; import java.util.List; /* * Given list of song durations, find the pairs of songs which sum up to 60 or multiples of 60 * * songs = [10, 50, 90, 30] * combinations are (10, 50) and (90, 30) so output is 2. */ public class SongCombinations { /* * Time: O(n^2) */ public static Long playList(List<Integer> songs) { long songCount = 0; for (int i = 0; i < songs.size() - 1; i++) { for (int j = i + 1; j < songs.size(); j++) { if ((songs.get(i) + songs.get(j)) % 60 == 0) { songCount++; } } } return songCount; } /* * Time complexity: O(N) * Auxiliary space: O(K) */ public static Long playListCombinations(List<Integer> songs, int songDuration) { int freq[] = new int[songDuration]; long songCount = 0; for (int i = 0; i < songs.size(); i++) { ++freq[songs.get(i) % songDuration]; } // if the song itself is of songDuration or its multiples songCount += freq[0] * (freq[0] - 1) / 2; // nCr => n (n - 1) /2 for (int i = 1; i <= songDuration/2 && i != songDuration - i; i++) { songCount += freq[i] * freq[songDuration - i]; } // if the songDuration asked is even, then find the pairs of middle ones songCount += freq[songDuration / 2] * (freq[songDuration / 2] - 1) / 2; return songCount; } public static void main(String[] args) { List<Integer> songs = Arrays.asList(new Integer[] {10, 50, 90, 30}); System.out.println(playList(songs)); System.out.println(playListCombinations(songs, 60)); } }
package com.example.android.worldheadlines.utilitaries; import android.content.ContentValues; import android.content.Context; import com.example.android.worldheadlines.database.Contract; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.List; public class GetJsonResponse { public List<ArticleList> jsonReponse(Context context, String response, List<ArticleList> articleLists) throws JSONException { List<ArticleList> mArticleList = articleLists; Context mContext = context; JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("articles"); for(int c = 0; c < jsonArray.length(); c++){ JSONObject json = jsonArray.getJSONObject(c); JSONObject source = json.getJSONObject("source"); ArticleList articles = new ArticleList(json.getString("title"), json.getString("description"), json.getString("url"), json.getString("urlToImage"), source.getString("name"), json.getString("publishedAt")); mArticleList.add(articles); ContentValues contentValues = new ContentValues(); contentValues.put(Contract.HeadlinesEntry.COLUMN_TITLE, articles.getTitle()); contentValues.put(Contract.HeadlinesEntry.COLUMN_DESCRIPTION, articles.getDescription()); contentValues.put(Contract.HeadlinesEntry.COLUMN_URL, articles.getUrl()); contentValues.put(Contract.HeadlinesEntry.COLUMN_IMAGE, articles.getImage()); contentValues.put(Contract.HeadlinesEntry.COLUMN_SOURCE, articles.getSource()); contentValues.put(Contract.HeadlinesEntry.COLUMN_DATE, articles.getDate()); mContext.getContentResolver().insert(Contract.HeadlinesEntry.CONTENT_URI, contentValues); } return mArticleList; } }
/// Roee Ebenstein /// 2013.09.23 //////////////////////////// // This is the main file - creates the vectors, and writes the files. // Over here there's also an xml readers that extract the interesting sections of the xmls. import java.io.File; import java.io.FilenameFilter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class AppLoader { static public void main(String[] params) { // Load the xmls and the dictionary String XmlsPath; WordCountVector.LoadDictionary(); if (params.length == 0) XmlsPath = "../5243hw2Py/hw1/xmls/"; else XmlsPath = params[0]; // Build the vector ReadXmlAndBuildVector(XmlsPath); WordCountVector.DecreaseVectorSize(); System.out.println("Finished building WordCountVector."); ReadXmlAndBuildWordListVector(XmlsPath); System.out.println("Finished building WordListVector."); // Write the vector to disk System.out.println("Finished building vector, starting to write WordCountVector file and TopicsVector file."); WordCountVector.WriteToFile("output/WordCount.csv", "output/TopicsVector.csv"); System.out.println("Finished building vector, starting to write WordListVector file."); //WordListVector.WriteToFile("../output/WordList.csv"); System.out.println("Finished writing files."); // Start KNN Classification double split = 0.6; KNNPrediction.GetPredictions("output/WordCount.csv",9342,"output/predictKNN6040.txt",split); split = 0.8; KNNPrediction.GetPredictions("output/WordCount.csv",9342,"output/predictKNN8020.txt",split); // Start Naive Bayes Classification NaiveBayesPrediction.GetPredictions("output/WordCount.csv", 0.8); NaiveBayesPrediction.GetPredictions("output/WordCount.csv", 0.6); } // Read all the xmls in a directory - and build the vectors static public void ReadXmlAndBuildVector(String XmlsPath) { // Get all XML files File dir = new File(XmlsPath); File [] files = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); // For each file, parse the xml if (files != null) { for (File xmlfile : files) { // Get each article (within the large XML Document doc = XmlReader.ReturnXml(xmlfile.getPath()); Node[] articles = XmlReader.getElements(doc, "REUTERS"); if (articles != null) { // Get the properties of each XML - and add it to the vector for (Node article : articles) { if (article.getNodeType() == Node.ELEMENT_NODE) { Element eArticle = (Element) article; // For each article - extract the topics, locations, and text int id = Integer.parseInt(eArticle.getAttribute("NEWID")); NodeList nTopics = null; if (eArticle.getElementsByTagName("TOPICS").getLength()> 0) nTopics = ((Element)eArticle.getElementsByTagName("TOPICS").item(0)).getElementsByTagName("D"); NodeList nLocations = null; if (eArticle.getElementsByTagName("PLACES").getLength()> 0) nLocations = ((Element)eArticle.getElementsByTagName("PLACES").item(0)).getElementsByTagName("D"); // Get Text and subjects Node nText = eArticle.getElementsByTagName("TEXT").item(0); NodeList nTitle = ((Element)nText).getElementsByTagName("TITLE"); NodeList nDateLine = ((Element)nText).getElementsByTagName("DATELINE"); NodeList nBody = ((Element)nText).getElementsByTagName("BODY"); // Extract Texts String[] Topics = XmlReader.getElementContent(nTopics); String[] Locations = XmlReader.getElementContent(nLocations); String[] Title = XmlReader.getElementContent(nTitle); String[] DateLine = XmlReader.getElementContent(nDateLine); String[] Body = XmlReader.getElementContent(nBody); WordCountVector.AddDocumentToTopicVector(id,Topics, Title, Body); System.out.println("Processed Document " + id); } } } } } // Outputs the results System.out.println("finished creating WordCount vector.\nThere are " + WordCountVector.Words.size() + " Words, and " + WordCountVector.Topics.size() + " Topics.\n"+ "There are " + WordCountVector.Document.size() + " Documents."); } static public void ReadXmlAndBuildWordListVector(String XmlsPath) { // Get all XML files File dir = new File(XmlsPath); File [] files = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); // For each file, parse the xml if (files != null) { for (File xmlfile : files) { // Get each article (within the large XML Document doc = XmlReader.ReturnXml(xmlfile.getPath()); Node[] articles = XmlReader.getElements(doc, "REUTERS"); if (articles != null) { // Get the properties of each XML - and add it to the vector for (Node article : articles) { if (article.getNodeType() == Node.ELEMENT_NODE) { Element eArticle = (Element) article; // For each article - extract the topics, locations, and text int id = Integer.parseInt(eArticle.getAttribute("NEWID")); NodeList nTopics = null; if (eArticle.getElementsByTagName("TOPICS").getLength()> 0) nTopics = ((Element)eArticle.getElementsByTagName("TOPICS").item(0)).getElementsByTagName("D"); NodeList nLocations = null; if (eArticle.getElementsByTagName("PLACES").getLength()> 0) nLocations = ((Element)eArticle.getElementsByTagName("PLACES").item(0)).getElementsByTagName("D"); // Get Text and subjects Node nText = eArticle.getElementsByTagName("TEXT").item(0); NodeList nTitle = ((Element)nText).getElementsByTagName("TITLE"); NodeList nDateLine = ((Element)nText).getElementsByTagName("DATELINE"); NodeList nBody = ((Element)nText).getElementsByTagName("BODY"); // Extract Texts String[] Topics = XmlReader.getElementContent(nTopics); String[] Locations = XmlReader.getElementContent(nLocations); String[] Title = XmlReader.getElementContent(nTitle); String[] DateLine = XmlReader.getElementContent(nDateLine); String[] Body = XmlReader.getElementContent(nBody); WordListVector.AddDocumentToTopicVector(id,Topics, Title, Body); System.out.println("Processed Document " + id); } } } } } // Outputs the results System.out.println("finished creating WordList vector.\nThere are " + WordCountVector.Words.size() + " Words, and " + WordCountVector.Topics.size() + " Topics.\n"+ "There are " + WordCountVector.Document.size() + " Documents."); } }
package com.ibisek.outlanded.smsReceiver; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.telephony.SmsMessage; import android.util.Log; import com.ibisek.outlanded.MainActivity; import com.ibisek.outlanded.R; import com.ibisek.outlanded.SmsListActivity; import com.ibisek.outlanded.navigation.POI; import com.ibisek.outlanded.navigation.gps.GpsUtils; import com.ibisek.outlanded.navigation.proximity.ProximityListener; import com.ibisek.outlanded.navigation.proximity.ProximitySource; import com.ibisek.outlanded.phonebook.PhonebookUtils; import com.ibisek.outlanded.utils.CompetitionModeLocationSender; import com.ibisek.outlanded.utils.Configuration; /** * Filters all incoming SMS messages and searches for GPS coordinates in RAW, Geocaching and WGS-84 formats. * * If such coordinate is found, a notification is created, which later on opens list with received messages and lets the user select one and click 'Navigate' * button to open external navigation application. * * Additionally, if location sharing is enabled, it posts the incoming location to server. * * * @see http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87 * * @author ibisek * @version 2014-05-20 */ public class SmsReceiver extends BroadcastReceiver { private static final String TAG = SmsReceiver.class.getSimpleName(); public static final int SMS_NOTIFICATION_ID = 666; private static Pattern PATTERN_COMPETITION_NO = Pattern.compile("([A-Z]{1,3})[ ]"); private static Pattern PATTERN_REGISTRATION_NO = Pattern.compile("([A-Z]+[-][0-9]+)"); @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "SMS RECIVER ACTION: " + intent.getAction()); // check if SMS reception is enabled: if (!Configuration.getInstance(context).isSmsFilteringEnabled()) { Log.d(TAG, "SMS reception not allowed."); return; } try { final Bundle bundle = intent.getExtras(); if (bundle != null) { String senderNumber, senderName = null; // aggregate all the message parts to one string: StringBuilder message = new StringBuilder(); final Object[] pdusObj = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdusObj.length; i++) { SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); String messagePart = currentMessage.getDisplayMessageBody(); message.append(messagePart); // lookup the sender's name in the phonebook: senderNumber = currentMessage.getDisplayOriginatingAddress(); senderName = PhonebookUtils.findDisplayName(context, senderNumber); if (senderName == null) senderName = senderNumber; Log.d(TAG, String.format("PDU info: senderName: %s; senderNumber:%s; messagePart:%s", senderName, senderNumber, messagePart)); } if(message.toString().length() > 0) { Log.d(TAG, "Incoming SMS: " + message); // N49.390856 E16.099912 na hristi u krizanova // message = "aaa N49.390856 E16.099912 bbb"; Float[] coords = GpsUtils.extractGpsCoordinates(message.toString()); // if there are coordinates in the SMS message: if (coords[0] != null && coords[1] != null) { Log.d(TAG, String.format("GPS coords: %.4f %.4f", coords[0], coords[1])); // create BASIC notification in the upper area: setNotification(context, context.getString(R.string.app_name), senderName, R.drawable.outlanded); // .. and if the sender is within recipient's polygon area a better notification will be created by the proximity listener.. Float latitude = (float) Math.toRadians(coords[0]); Float longitude = (float) Math.toRadians(coords[1]); // try to find competition and registration numbers: String competitionNo = null, registrationNo = null; Matcher m = PATTERN_COMPETITION_NO.matcher(message); if (m.find()) competitionNo = m.group(1); m = PATTERN_REGISTRATION_NO.matcher(message); if (m.find()) registrationNo = m.group(); // find the location in on proximity display: // new Thread(new ProximityQueryStarter(context, senderName, latitude, longitude, competitionNo, registrationNo)).start(); new ProximityQueryAsyncTask(context, senderName, latitude, longitude, competitionNo, registrationNo).execute(); // start beeping service: Intent beepingServiceIntent = new Intent(context, BeepingService.class); context.startService(beepingServiceIntent); } // else ignore the message } } } catch (Exception ex) { if (ex != null) { // uz se stalo ze ex.getMessage() udelalo NPE(!!) StringBuilder sb = new StringBuilder(ex.getMessage()); StackTraceElement[] items = ex.getStackTrace(); for (StackTraceElement item : items) { sb.append("\n").append(item); } Log.e(TAG, sb.toString()); } } } /** * Adds a notification icon & message to the notification area. * * @param title * @param text * @param icon R.drawable.. * * @see https ://developer.android.com/guide/topics/ui/notifiers/notifications .html #CreateNotification */ private void setNotification(Context context, String title, String text, int icon) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(icon).setContentTitle(title).setContentText(text); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(context, SmsListActivity.class); // The stack builder object will contain an artificial back stack for // the started Activity. This ensures that navigating backward from the // Activity leads out of your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(MainActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mNotificationManager.notify(SMS_NOTIFICATION_ID, mBuilder.build()); } /** * Cancels our notification in the upper screen area. * * @param context */ public static void cancelNotification(Context context) { if (Context.NOTIFICATION_SERVICE != null) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager notificationManager = (NotificationManager) context.getSystemService(ns); notificationManager.cancel(SMS_NOTIFICATION_ID); } } private class ProximityQueryAsyncTask extends AsyncTask<Void, Void, String> { private Context context; private String senderName; private Float latitude, longitude; private String competitionNo, registrationNo; /** * @param context * @param senderName * @param latitude * @param longitude * @param competitionNo * @param registrationNo */ public ProximityQueryAsyncTask(Context context, String senderName, Float latitude, Float longitude, String competitionNo, String registrationNo) { this.context = context; this.senderName = senderName; this.latitude = latitude; this.longitude = longitude; this.competitionNo = competitionNo; this.registrationNo = registrationNo; } @Override protected String doInBackground(Void... params) { ProximitySource proximitySource = ProximitySource.getInstance(); if (!proximitySource.isInitialised()) proximitySource.init(context, 4, 1); // 4m, 1point //proximitySource.addListener(new MyProximityListener(context, senderName, latitude, longitude, competitionNo, registrationNo)); while (!proximitySource.isInitialised()) { // give it some time try { Thread.sleep(1000); } catch (InterruptedException e) { // don't care } } proximitySource.resolveLocation(latitude, longitude, new MyProximityListener(context, senderName, latitude, longitude, competitionNo, registrationNo)); return null; } } // /** // * Needs to be done in such complicated way as we need to wait until the ProximitySource is initialised and that takes time.. while we cannot do // * Thread.sleep() on the main app thread. // */ // private class ProximityQueryStarter implements Runnable { // // private Context context; // private String senderName; // private Float latitude, longitude; // private String competitionNo, registrationNo; // // /** // * @param context // * @param senderName // * @param latitude in radians // * @param longitude in radians // * @param registrationNo // * @param competitionNo // */ // public ProximityQueryStarter(Context context, String senderName, Float latitude, Float longitude, String competitionNo, String registrationNo) { // this.context = context; // this.senderName = senderName; // this.latitude = latitude; // this.longitude = longitude; // this.competitionNo = competitionNo; // this.registrationNo = registrationNo; // } // // @Override // public void run() { // ProximitySource proximitySource = ProximitySource.getInstance(); // proximitySource.init(context, 4, 1); // 4m, 1point // proximitySource.addListener(new MyProximityListener(context, senderName, latitude, longitude, competitionNo, registrationNo)); // while (!proximitySource.isInitialised()) { // give it some time // try { // Thread.sleep(500); // } catch (InterruptedException e) { // // don't care // } // } // proximitySource.updateLocation(latitude, longitude); // } // } private class MyProximityListener implements ProximityListener { private Context context; private String senderName; private float latitude, longitude; private String competitionNo, registrationNo; public MyProximityListener(Context context, String senderName, float latitude, float longitude, String competitionNo, String registrationNo) { this.context = context; this.senderName = senderName; this.latitude = latitude; this.longitude = longitude; this.competitionNo = competitionNo; this.registrationNo = registrationNo; } @Override public void notify(List<POI> nearestPoints) { POI nearestPoi = nearestPoints.get(0); // get direction to nearest point: String name = nearestPoi.getName(); float bearing = nearestPoi.getBearingToOrigin(); String direction = new GpsUtils(context).bearingToDirection(bearing); // format the "2km SW from XX" direction string: String format = context.getResources().getString(R.string.locationFormatSMS); String directionString = String.format(format, nearestPoi.getDistanceToOrigin(), direction, name); // create the notification in the upper area: String title = String.format("%s: %s", context.getString(R.string.app_name), senderName); String notificationMessage = String.format("%s", directionString); setNotification(context, title, notificationMessage, R.drawable.outlanded); // share incoming location: if (Configuration.getInstance(context).isLocationSharingEnabled()) { new CompetitionModeLocationSender().sendToServer(competitionNo, registrationNo, Math.toDegrees(latitude), Math.toDegrees(longitude), nearestPoi.getName()); } } } }
package mathPhysicsEngine; public class WorldPoint { private double x; private double y; private double z; private double t; public WorldPoint(double x, double y, double z, double t) { super(); this.x = x; this.y = y; this.z = z; this.t = t; } public WorldPoint(double x, double y, double z) { super(); this.x = x; this.y = y; this.z = z; this.t = 1D; } public WorldPoint() { super(); this.x = 0D; this.y = 0D; this.z = 0D; this.t = 1D; } public WorldPoint(WorldPoint startVec) { this.x = startVec.getX(); this.y = startVec.getY(); this.z = startVec.getZ(); this.t = startVec.getT(); } public void scaleVector(double scaleFactor) { this.x = this.x * scaleFactor; this.y = this.y * scaleFactor; this.z = this.z * scaleFactor; this.t = this.t * scaleFactor; } public void translateVector(WorldPoint translation) { this.x = this.x + translation.getX(); this.y = this.y + translation.getY(); this.z = this.z + translation.getZ(); this.t = this.t + translation.getT(); } @SuppressWarnings("static-access") public ScreenPoint perspective(WorldPoint vector) { Camera camera = new Camera(); WorldPoint wp = new WorldPoint(); //wp = multiplyWorldPointwithFourPointMatrix(camera.getPerspectiveMatrix()); double screenY = 360 * (wp.getY() / wp.getZ()); double screenX = 360 * (wp.getX() / wp.getZ()); ScreenPoint screenCoordinate = new ScreenPoint(screenX, screenY); screenCoordinate.setX(screenX); screenCoordinate.setY(screenY); return screenCoordinate; } public WorldPoint multiplyWorldPointwithFourPointMatrix(FourPointMatrix fpm) { WorldPoint result = new WorldPoint(); result.setX((this.x * fpm.getA1()) + (this.y * fpm.getB1()) + (this.z * fpm.getC1()) + (this.t * fpm.getD1())); result.setY((this.x * fpm.getA2()) + (this.y * fpm.getB2()) + (this.z * fpm.getC2()) + (this.t * fpm.getD2())); result.setZ((this.x * fpm.getA3()) + (this.y * fpm.getB3()) + (this.z * fpm.getC3()) + (this.t * fpm.getD3())); result.setT((this.x * fpm.getA4()) + (this.y * fpm.getB4()) + (this.z * fpm.getC4()) + (this.t * fpm.getD4())); return result; } public void transform(FourPointMatrix transformationMatrix) { WorldPoint result = new WorldPoint(); result = multiplyWorldPointwithFourPointMatrix(transformationMatrix); this.x = result.getX(); this.y = result.getY(); this.z = result.getZ(); this.t = result.getT(); } public String getStringVector() { return ("x:" + Double.toString(x) + " y:" + Double.toString(y) + " z:" + Double.toString(z) + " t:" + Double.toString(t)); } public WorldPoint getWorldPoint() { return new WorldPoint(x, y, z, t); } public double getT() { return t; } public void setT(double t) { this.t = t; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getZ() { return z; } public void setZ(double z) { this.z = z; } }
package com.parse; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LogRegExp { public static void main(String[] args) { // Input for matching the regexe pattern String input = "11-09-2017 03:40:53 - :: | Error: 3303 | P_36628_6270 | 6275000150 Error: 3303 36628 USGAAP_Input_Adj Non-Controllable (local overhead) Working MNCL_6270 No_Channel No_Product P_36628_6270 USD_Constant_FCY F_36628_6270 C_36628_6270 MTD Projection_Oct FY20 Sep 934.13678543893"; // Regexe to be matched String regexe = "Error: 3303"; // Step 1: Allocate a Pattern object to compile a regexe Pattern pattern = Pattern.compile(regexe); // Pattern pattern = Pattern.compile(regexe, Pattern.CASE_INSENSITIVE); // // // case-insensitive matching // Step 2: Allocate a Matcher object from the compiled regexe pattern, // and provide the input to the Matcher Matcher matcher = pattern.matcher(input); // Step 3: Perform the matching and process the matching result // Use method find() while (matcher.find()) { // find the next match System.out.println("find() found the pattern \"" + matcher.group() + "\" starting at index " + matcher.start() + " and ending at index " + matcher.end()); } // Use method matches() if (matcher.matches()) { System.out.println("matches() found the pattern \"" + matcher.group() + "\" starting at index " + matcher.start() + " and ending at index " + matcher.end()); } else { System.out.println("matches() found nothing"); } // Use method lookingAt() if (matcher.lookingAt()) { System.out.println("lookingAt() found the pattern \"" + matcher.group() + "\" starting at index " + matcher.start() + " and ending at index " + matcher.end()); } else { System.out.println("lookingAt() found nothing"); } } }
package main.java.Pipelines; import main.java.Pipelines.Advanced.BetterTowergoalPipeline; import main.java.Pipelines.Basic.PipelineTester; import main.java.Pipelines.Basic.PnPPipelineTester; import main.java.Utils.BetterTowerGoalUtils; import main.java.Utils.CvUtils; import main.java.Utils.VideoPlayback; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Rect; import org.opencv.core.Size; import org.opencv.highgui.HighGui; import org.opencv.imgproc.Imgproc; import javax.imageio.ImageIO; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Objects; public class MultiPipelineRunner { static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } public static void main(String[] args) throws IOException, InterruptedException { PnPPipelineTester pipeline = new PnPPipelineTester(); Mat matchMat = CvUtils.bufferedImageToMat(ImageIO.read(new File("src/assets/annotations/out631.png")));//432, 631 String annoFolder = "src/assets/input2"; System.out.print("Serializing Images... "); long tmS = System.currentTimeMillis(); ArrayList<Mat> inMats = new ArrayList<>(); int fileLength = Objects.requireNonNull(new File(annoFolder).listFiles()).length-2; //fileLength = 400; for(int i = 1; i < fileLength; i ++) { Mat tmp = CvUtils.bufferedImageToMat(ImageIO.read(new File(annoFolder + "/out" + i + ".png"))); inMats.add(tmp); CvUtils.printLoadingBar("Loading Images", i, fileLength-1.0); //System.out.println(i + "/" + 681); } ArrayList<Long> times = new ArrayList<>(); ArrayList<Rect> rects = new ArrayList(); System.out.println("Loading Images Complete! Elapsed Time " + (System.currentTimeMillis() - tmS) + " ms"); System.out.print("Processing Images... "); tmS = System.currentTimeMillis(); ArrayList<Mat> mts = new ArrayList<>(); ArrayList<Mat> pos = new ArrayList<>(); for(Mat m : inMats) { long start = System.currentTimeMillis(); Mat out = pipeline.processFrame(m); rects.add(pipeline.getBoundingRect()); //pos.add(pipeline.getPos().clone()); long end = System.currentTimeMillis(); Imgproc.resize(out, out, new Size(1280, 720)); ImageIO.write(CvUtils.toBufferedImage(HighGui.toBufferedImage(out)), "JPG", new File("src/assets/out/out" + inMats.indexOf(m) + ".jpg")); //mts.add(out.clone()); out.release(); m.release(); times.add(end-start); CvUtils.printLoadingBar("Processing Images", inMats.indexOf(m), inMats.size()-1); } System.out.println("Processing Images Complete! Elapsed Time " + (System.currentTimeMillis() - tmS) + " ms"); double avgTime = 0; double avgx = 0, avgy = 0, avgw = 0, avgh = 0; for(long l : times){ avgTime += ((double)l/times.size()); } for(Rect r : rects){ avgx += (double)r.x/rects.size(); avgy += (double)r.y/rects.size(); avgw += (double)r.width/rects.size(); avgh += (double)r.height/rects.size(); } double lastX = 0; double lastY = 0; double lastZ = 0; StringBuilder str = new StringBuilder(); for(Mat m : pos){ double[] arr = new double[(int) m.total()]; m.get(0, 0, arr); if(arr.length == 3){ double x = arr[0]; if(x > 0){ x = -x; } double y = arr[1]; double z = arr[2]; str.append("[").append(x).append(',').append(y).append(",").append(z).append("]\n"); lastX = x; lastY = y; lastZ = z; }else{ str.append("[").append(lastX).append(',').append(lastY).append(",").append(lastZ).append("]\n"); } } File f = new File("src/assets/out.txt"); f.createNewFile(); FileWriter writer = new FileWriter(f); writer.write(str.toString()); writer.flush(); writer.close(); System.out.println("Average Time Taken: " + avgTime + " ms. Full Capacity: " + (1/(avgTime/1000.0)) + " Frames Per Second"); System.out.println("Average Position | X: " + avgx + " Y: " + avgy + " | W: " + avgw + " H: " + avgh); System.out.println(); /** System.out.print("Starting Visualizer... " ); for(int i = 0; i < mts.size(); i ++){ Mat combined = mts.get(i); Imgproc.resize(combined, combined, new Size(1280, 720)); ImageIO.write(CvUtils.toBufferedImage(HighGui.toBufferedImage(combined)), "JPG", new File("src/assets/out/out" + i + ".jpg")); //System.out.println("Wrote " + i + " of " + mts.size()); CvUtils.printLoadingBar("Writing Images", i, mts.size()-1); } System.out.println("Complete"); //VideoPlayback playback = new VideoPlayback(mts, 24); //playback.run(); ffmpeg -i out%d.jpg -c:v libx264 -vf fps=24 -pix_fmt yuv420p out.mp4 */ } }
package baek2675; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main {//완료 public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //문자열 상태인 버퍼 리더를 사용할것이다 int T = Integer.parseInt(br.readLine()); //먼저 몇개의 문장을 입력할것인지 선택한다 for (int i = 0; i < T; i++) { String str = br.readLine(); String[] st = str.split(" "); //스트링 형식으로 받을것이며 readLine() 은 공백 포함 문자를 받아 문자열을 받는다 //즉, 공백을 나눌수 있는 함수 split을 사용해 배열에 담는다 String S = st[1]; int X = Integer.parseInt(st[0]); //배열 0번째는 반복할 횟수가 들어오니 인트형으로 변환해서 받고 //배열 1번은 문자열이 들어가있으니 다시 스트링 변수에 담아서 처리한다 for (int p = 0; p < S.length(); p++) { for (int j = 0; j < X; j++) { System.out.print(S.charAt(p)); //알파벳 잘 좀 보자 헷갈려죽는줄 알았다 한결아 ㅋ } } System.out.println(); } } }
package Lec_05_Whill_Loop_1; import java.util.Scanner; public class Pro_05_02_ExamPreparation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Въведете броя незадоволителни оценки, които може да получи: "); int inputNumPoorGrade = Integer.parseInt(scanner.nextLine()); String currentText = ""; String lastProblem = ""; int counterPoorGrade = 0; int countGoodGrade = 0; int goodGrade = 0; boolean isEnough = false; while (counterPoorGrade < inputNumPoorGrade) { System.out.print("Въведете име на задачата или команда Enough: "); currentText = scanner.nextLine(); if ("Enough".equals(currentText)) { isEnough = true; break; } System.out.print("Въведете получена оценка за задачата: "); int problemGrade = Integer.parseInt(scanner.nextLine()); goodGrade += problemGrade; lastProblem = currentText; countGoodGrade++; if (problemGrade <= 4) { counterPoorGrade++; } } if (isEnough) { double averageGrade = goodGrade * 1.0 / countGoodGrade; System.out.printf("Average score: %.2f%nNumber of problems: %d%nLast problem: %s", averageGrade, countGoodGrade, lastProblem); } else { System.out.printf("You need a break, %d poor grades.", counterPoorGrade); } } }
/*********************************************************** * @Description : * @author : 梁山广(Liang Shan Guang) * @date : 2020/5/4 12:42 * @email : liangshanguang2@gmail.com ***********************************************************/ package 第4到27章_23大设计模式.第21章_观察者模式.订阅课程的例子; public class Question { private String userName; private String questionContent; public Question(String userName, String questionContent) { this.userName = userName; this.questionContent = questionContent; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getQuestionContent() { return questionContent; } public void setQuestionContent(String questionContent) { this.questionContent = questionContent; } }
package com.bofsoft.laio.customerservice.DataClass.Order; import com.bofsoft.laio.data.BaseData; /** * 设置默认的Erp账号 * * @author yedong */ public class SettingDefaultErpAccountData extends BaseData { // 请求参数 // ERPId Integer ERP记录Id public String UserPhone; // 用户手机号(如果没有就填写“”) public String UserERPName; // 用户ERP名称(如果没有就填写“”) public String UserERPDanwei; // 用户ERP单位(如果没有就填写“”) }
package br.com.belezanaweb.domain; public enum WarehouseType { ECOMMERCE(1), PHYSICAL_STORE(2); private int codigo; WarehouseType(int codigo) { this.codigo = codigo; } public int getCodigo() { return codigo; } }
package com.bag.utils.crawler.htmlParser; import com.bag.pin.model.Pin; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.jsoup.nodes.Document; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.Date; /** * Created by johnny on 25/11/15. */ @Service public class PinParser { public Pin parseToPin(String id, Document document) { Pin pin = new Pin(); pin.setId(id); pin.setTitle(getTitle(document)); pin.setDate(getDate(document)); pin.setFavoriteTotal(getFavoriteTotal(document)); pin.setLike_total(getLikeTotal(document)); pin.setPentoUserId(getPentoUserId(document)); pin.setSourceUrl(getSourceUrl(document)); pin.setSourceName(getSourceName(document)); return pin; } private String getSourceName(Document document) { return document.select("div.left_source_type_1 a").html(); } private String getSourceUrl(Document document) { return document.select("div.left_source_type_1 a").attr("href"); } //Elements newsHeadlines = doc.select("#mp-itn b a"); private String getTitle(Document document) { return document.select(".left_title h1").html(); } private String getPentoUserId(Document document) { return document.select(".author_avatar_type_5").attr("href").replace("/user/", ""); } private long getLikeTotal(Document document) { String likes = document.select(".left_function_good").html().replace("赞", ""); return StringUtils.isEmpty(likes)? 0:Long.parseLong(likes.trim()); } private long getFavoriteTotal(Document document) { String favorate = document.select(".left_function_collection").html().replace("收集", ""); return StringUtils.isEmpty(favorate)? 0: Long.parseLong(favorate.trim()); } private Date getDate(Document document) { String time = document.select(".left_time").html().replace("时间:", ""); DateTime date = DateTime.parse(time, DateTimeFormat.forPattern("yyyy-MM-dd")); return date.toDate(); } }
package com.pricer.test.menuparser.parser; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.pricer.test.menuparser.model.BreakfastMenu; import com.pricer.test.menuparser.model.Food; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.nio.file.Path; import java.util.Arrays; import java.util.List; @Slf4j public class MenuXmlParser implements MenuParser { @Override public List<Food> parse(Path menuPath) { XmlMapper mapper = XmlMapper.builder().defaultUseWrapper(false).build(); try { var menu = mapper.readValue(menuPath.toFile(), BreakfastMenu.class); return Arrays.asList(menu.getFoods()); } catch (IOException e) { log.error("Failed to parse XML menu file", e); throw new IllegalStateException(); } } }
public class TestStdArrayAppend{ public static void main(String[] args){ int[] a = [10,20,50]; int[] b = [12,22,55]; int i = 2; //Test 1 System.out.println(StdArray.append(a,b).length == a.length + b.length); //Test 2 System.out.println(append(a,b)[i] == a[i]); //Test 3 System.out.println(append(a,b)[i+a.length] == b[i]); } }
package com.kingnode.gou.dto; import java.math.BigDecimal; import com.kingnode.gou.entity.OrderHead; import com.kingnode.gou.entity.OrderReturnDetail; /** * @author 58120775@qq.com (chenchao) * 订单返回列表 */ public class OrderReturnListDTO{ private long productId;//产品id private String orderNo;//订单编号 private BigDecimal price;//价格 private BigDecimal orgPrice;//原始价格 private Integer quatity;//数量 private OrderHead.OrderStatus status;//订单状态,未付款,代发货,已发货,退货 private OrderReturnDetail.ReturnStatus returnStatus;//退回状态 private String imgPath;//商品图片 private String productName;//商品名称 private String guige;//规格 public long getProductId(){ return productId; } public void setProductId(long productId){ this.productId=productId; } public String getGuige(){ return guige; } public void setGuige(String guige){ this.guige=guige; } public String getProductName(){ return productName; } public void setProductName(String productName){ this.productName=productName; } public String getImgPath(){ return imgPath; } public void setImgPath(String imgPath){ this.imgPath=imgPath; } public OrderHead.OrderStatus getStatus(){ return status; } public void setStatus(OrderHead.OrderStatus status){ this.status=status; } public String getOrderNo(){ return orderNo; } public void setOrderNo(String orderNo){ this.orderNo=orderNo; } public BigDecimal getPrice(){ return price; } public void setPrice(BigDecimal price){ this.price=price; } public BigDecimal getOrgPrice(){ return orgPrice; } public void setOrgPrice(BigDecimal orgPrice){ this.orgPrice=orgPrice; } public Integer getQuatity(){ return quatity; } public void setQuatity(Integer quatity){ this.quatity=quatity; } public OrderReturnDetail.ReturnStatus getReturnStatus(){ return returnStatus; } public void setReturnStatus(OrderReturnDetail.ReturnStatus returnStatus){ this.returnStatus=returnStatus; } }
/** * All rights Reserved, Designed By www.tydic.com * @Title: ItemParamItemController.java * @Package com.taotao.controller * @Description: TODO(用一句话描述该文件做什么) * @author: axin * @date: 2018年12月15日 上午12:02:03 * @version V1.0 * @Copyright: 2018 www.hao456.top Inc. All rights reserved. */ package com.taotao.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import com.taotao.service.ItemParamItemService; /** * @Description: TODO * @ClassName: ItemParamItemController * @author: Axin * @date: 2018年12月15日 上午12:02:03 * @Copyright: 2018 www.hao456.top Inc. All rights reserved. */ @Controller public class ItemParamItemController { @Autowired private ItemParamItemService itemParamItemService; @RequestMapping("/showItem/{itemId}") public String getItemParamItemById(@PathVariable Long itemId, Model model){ String itemParam = this.itemParamItemService.getItemParamByItemId(itemId); model.addAttribute("itemParam", itemParam); return "item"; } }
package com.apssouza.mytrade.trading.forex.portfolio; public enum ExitReason { STOP_ORDER_FILLED, COUNTER_SIGNAL, RECONCILIATION_FAILED, END_OF_DAY }
/* * Copyright 2016 Virtual Rainbow, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.virtualrainbowllc.demotracker.ui.log; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.virtualrainbowllc.demotracker.data.DemoRepository; import com.virtualrainbowllc.demotracker.data.ServiceCallback; import com.virtualrainbowllc.demotracker.data.model.Demo; import com.virtualrainbowllc.demotracker.ui.common.BasePresenterImpl; import timber.log.Timber; class LogPresenterImpl extends BasePresenterImpl implements LogContract.LogPresenter, ServiceCallback { @NonNull private final DemoRepository demoRepository; @Nullable private LogContract.LogView logView; LogPresenterImpl(@Nullable LogContract.LogView logView, @NonNull DemoRepository demoRepository) { this.logView = logView; this.demoRepository = demoRepository; } @Override public void onViewAttached() { super.onViewAttached(); if (logView != null) { logView.setupBaseViews(); } } @Override public void onViewDetached() { super.onViewDetached(); if (logView == null) { throw new IllegalStateException("View is already detached"); } logView = null; } @Override public void closeRealm() { demoRepository.closeRealm(); } @Override public void firstRun() { if (logView != null) { logView.showFirstRun(); } } @Override public void loadData() { if (logView != null) { addToAutoUnsubscribe(demoRepository.getAll() .doOnNext(items -> logView.setItems(items)) .doOnError(throwable -> Timber.e(throwable.getMessage())) .subscribe()); } } @Override public void fabClicked() { if (logView != null) { logView.startCheckOutDialog(); } } @Override public void itemClicked(String id) { if (logView != null) { logView.startViewDemoActivity(id); } } @Override public void checkOutDemo(Demo demo) { if (logView != null) { demoRepository.add(demo, this); } } @Override public void onSuccess() { if (logView != null) { logView.checkOutDemoSuccess(); loadData(); } } @Override public void onError(Throwable e) { if (logView != null) { logView.checkOutDemoError(); Timber.e(e.getMessage()); } } }
public class ElectronicPetEasy { public String isDifficult(int st1, int p1, int t1, int st2, int p2, int t2) { for(int i = 0; i < t1; ++i) { if(st2 <= st1) { int test = st1 - st2; if(test%p2 == 0) { if(test/p2 < t2) { return "Difficult"; } } } st1 += p1; } return "Easy"; } }
package exer2; import java.util.Random; public class Main { static Random random = new Random(); public static int sumMachine =1 + random.nextInt(20); static int candidate = 1+random.nextInt(10); public static void main(String[] args) { Runnable server = new Server(); Thread thread = new Thread(server); thread.start(); for (int i = 0; i < sumMachine; i++) { Runnable machine = new Machine(candidate); Thread thread1 = new Thread(machine); thread1.start(); } } }
package br.com.abc.javacore.metodo.test; import br.com.abc.javacore.metodo.classes.Calculadora; public class ParametrosTest { public static void main(String[] args) { Calculadora calc = new Calculadora(); int num1 = 5; int num2 = 10; calc.alteraDoisNumeros(num1, num2); System.out.println("Dentro do teste"); System.out.println("Num 1: " + num1); System.out.println("Num 2: " + num2); //Quando o valor de uma variável de tipo primitivo for passado com argumento //para um método, o valor da variável nunca é alterado } }
/* * 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 Controller; import gui.InfoEvent; import java.io.File; import java.io.IOException; import java.util.List; import model.Animal; import model.AnimalData; /** * * @author Ilham */ public class Controller { AnimalData animalData = new AnimalData(); public void addAnimal(InfoEvent infoEvent) { String name = infoEvent.getName(); String kindsOfAnimal = infoEvent.getKindsAnimal(); String eat = infoEvent.getEat(); String move = infoEvent.getMove(); String breath = infoEvent.getBreath(); Animal animal = new Animal(name, kindsOfAnimal, eat, move, breath); animalData.addAnimal(animal); } public void deleteAnimal(int index) { animalData.deleteAnimal(index); } public void editAnimal(InfoEvent infoEvent) { int index = infoEvent.getIndex(); String name = infoEvent.getName(); String kindsOfAnimal = infoEvent.getKindsAnimal(); String eat = infoEvent.getEat(); String move = infoEvent.getMove(); String breath = infoEvent.getBreath(); animalData.editAnimal(index, name, kindsOfAnimal, eat, move, breath); } public List<Animal> getAnimals() { return animalData.getAnimals(); } public void saveToFile(File file) throws IOException { animalData.saveToFile(file); } public void loadFromFile(File file) throws IOException { animalData.loadFromFile(file); } }
/* * 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 mx.appsw.persistencia.integration; import java.util.HashMap; import java.util.Map; /** * * @author kitto */ public class ServiceLocatorSingletonFactory { private static final ServiceLocatorSingletonFactory instance = new ServiceLocatorSingletonFactory(); @SuppressWarnings("rawtypes") private Map<Class, Object> mapHolder = new HashMap<>(); private ServiceLocatorSingletonFactory() { } @SuppressWarnings("unchecked") public static <T> T getInstance(Class<T> classOf) { synchronized (instance) { if (!instance.mapHolder.containsKey(classOf)) { T obj = null; try { obj = classOf.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } instance.mapHolder.put(classOf, obj); } } return (T) instance.mapHolder.get(classOf); } }
package com.beike.common.enums.trx; /** * @Title: BizActHistoryType.java * @Package com.beike.common.enums.trx * @Description: 帐务相关的外在产品业务类型 * @author wh.cheng@sinobogroup.com * @date May 5, 2011 2:35:06 PM * @version V1.0 */ public enum BizType { /** * 帐务相关的外在产品业务类型。可频繁更改 */ CARDLOAD,// 千品卡充值 COUPON, //优惠券 COUPON_3 //优惠券3期 }
package entity; import entity.Item; import java.util.ArrayList; public class Minibar { ArrayList<Item> itemlist = new ArrayList(); ArrayList<String> consumedItems = new ArrayList(); private int barrevenue = 0; public Minibar(ArrayList<Item> itemlist) { this.itemlist = itemlist; } public void takeItem(Item choice){ barrevenue+=choice.getCost(); System.out.println("Aaahh, I love me some " + choice.getName()); System.out.println(choice.getCost() + "$ was added to your tab"); consumedItems.add(choice.getName()); if(choice.getQuantity() > 1){ choice.setQuantity(choice.getQuantity()-1); } else { itemlist.remove(choice); } } public ArrayList<String> getConsumedItems() { return consumedItems; } public void setConsumedItems(ArrayList<String> consumedItems) { this.consumedItems = consumedItems; } public ArrayList<Item> getItemlist() { return itemlist; } public void setItemlist(ArrayList<Item> itemlist) { this.itemlist = itemlist; } public int getBarrevenue() { return barrevenue; } public void setBarrevenue(int barrevenue) { this.barrevenue = barrevenue; } }
/* ------------------------------------------------------------------------------ * 软件名称:他秀手机版 * 公司名称:多宝科技 * 开发作者:Yongchao.Yang * 开发时间:2014年7月15日/2014 * All Rights Reserved 2012-2015 * ------------------------------------------------------------------------------ * 注意:本内容均来自多宝科技研发部,仅限内部交流使用,未经过公司许可 禁止转发 * ------------------------------------------------------------------------------ * prj-name:com.duobao.video.logic * fileName:UserService.java * ------------------------------------------------------------------------------- */ package com.ace.database.service; import java.math.BigDecimal; import javax.transaction.UserTransaction; import org.apache.log4j.Logger; import com.ace.database.ds.UserTransactionManager; import com.ace.database.module.AccountModule; import com.ace.database.module.ExchangeModule; import com.rednovo.ace.constant.Constant.OperaterStatus; import com.rednovo.ace.constant.Constant.OrderStatus; import com.rednovo.ace.constant.Constant.logicType; import com.rednovo.ace.entity.ExchangeBindInfo; /** * @author yongchao.Yang/2014年7月15日 */ public class ExchangeService { private static Logger logger = Logger.getLogger(ExchangeService.class); public ExchangeService() {} public static ExchangeBindInfo getBindInfo(String userId) { ExchangeBindInfo ebi = null; UserTransaction ut = UserTransactionManager.getUserTransaction(); ExchangeModule eb = new ExchangeModule(); try { ut.begin(); ebi = eb.getBindInfo(userId); ut.commit(); } catch (Exception e) { try { logger.error("[获取用户 (" + userId + ")兑点绑定信息 失败]", e); ut.rollback(); } catch (Exception e1) { e1.printStackTrace(); } } finally { eb.release(); } return ebi; } public static String bind(String userId, String weChatId, String mobileId) { String exeCode = OperaterStatus.FAILED.getValue(); UserTransaction ut = UserTransactionManager.getUserTransaction(); ExchangeModule eb = new ExchangeModule(); try { ut.begin(); exeCode = eb.bind(userId, weChatId, mobileId); if (OperaterStatus.SUCESSED.getValue().equals(exeCode)) { ut.commit(); } else { ut.rollback(); } } catch (Exception e) { try { logger.error("[用户 (" + userId + ")兑点绑定信息 失败]", e); ut.rollback(); } catch (Exception e1) { e1.printStackTrace(); } } finally { eb.release(); } return exeCode; } public static String request(String userId, BigDecimal coinAmount) { String exeCode = OperaterStatus.FAILED.getValue(); UserTransaction ut = UserTransactionManager.getUserTransaction(); ExchangeModule eb = new ExchangeModule(); AccountModule am = new AccountModule(); try { ut.begin(); // 扣币 exeCode = am.reduceIncome(userId, userId, coinAmount, logicType.EXCHANGE); if (!OperaterStatus.SUCESSED.getValue().equals(exeCode)) { ut.rollback(); return exeCode; } // 添加明细 exeCode = eb.request(userId, coinAmount); if (!OperaterStatus.SUCESSED.getValue().equals(exeCode)) { ut.rollback(); return exeCode; } ut.commit(); } catch (Exception e) { try { logger.error("[用户 (" + userId + ")申请兑点失败]", e); ut.rollback(); } catch (Exception e1) { e1.printStackTrace(); } } finally { eb.release(); am.release(); } return exeCode; } /** * 打款 * * @param requestId * @param status * @param payerId * @return * @author Yongchao.Yang * @since 2016年3月19日上午11:20:23 */ public static String applyRequest(String requestId, OrderStatus status, String payerId) { String exeCode = OperaterStatus.FAILED.getValue(); UserTransaction ut = UserTransactionManager.getUserTransaction(); ExchangeModule eb = new ExchangeModule(); AccountModule am = new AccountModule(); try { ut.begin(); // 添加明细 exeCode = eb.applyRequest(requestId, status.getValue(), payerId); if (!OperaterStatus.SUCESSED.getValue().equals(exeCode)) { ut.rollback(); return exeCode; } ut.commit(); } catch (Exception e) { try { logger.error("[" + requestId + "打款失败]", e); ut.rollback(); } catch (Exception e1) { e1.printStackTrace(); } } finally { eb.release(); am.release(); } return exeCode; } }
package collection_framework; import java.util.*; public class ComprableSorting { public static void main(String[] args) { List<Family1> list=new ArrayList<Family1>(); list.add(new Family1("Pitamber rana", 70, "old but for me always gold")); list.add(new Family1("Vishal rana", 20, "youngster")); list.add(new Family1("Arun rana ", 21, "Youngster")); Collections.sort(list); for(Family1 item : list) { Family1 val=(Family1)item; System.out.println(val); } } } class Family1 implements Comparable { String name; int age; String status; public Family1(String name, int age, String status) { super(); this.name = name; this.age = age; this.status = status; } @Override public int compareTo(Object obj1) { Family1 obj=(Family1)obj1; return this.name.compareTo(obj.name); } @Override public String toString() { return "Family1 [name=" + name + ", age=" + age + ", status=" + status + "]"; } }
package edu.mit.needlstk; public enum IdentifierType { STREAM, RELATION, COLUMN, AGG_FUNC, STATE, STATE_OR_COLUMN, }
package model.SQLserver; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the fakturak database table. * */ @Entity @NamedQuery(name="Fakturak.findAll", query="SELECT f FROM Fakturak f") public class Fakturak implements Serializable { private static final long serialVersionUID = 1L; @Id private int id; private int bez; private String data; private String egoera; private int guztira; private String izena; //bi-directional many-to-one association to Bezeroak @ManyToOne @JoinColumn(name="BezeroIdHornitzailea") private Bezeroak bezeroak; public Fakturak() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public int getBez() { return this.bez; } public void setBez(int bez) { this.bez = bez; } public String getData() { return this.data; } public void setData(String data) { this.data = data; } public String getEgoera() { return this.egoera; } public void setEgoera(String egoera) { this.egoera = egoera; } public int getGuztira() { return this.guztira; } public void setGuztira(int guztira) { this.guztira = guztira; } public String getIzena() { return this.izena; } public void setIzena(String izena) { this.izena = izena; } public Bezeroak getBezeroak() { return this.bezeroak; } public void setBezeroak(Bezeroak bezeroak) { this.bezeroak = bezeroak; } }
package com.worldchip.bbp.bbpawmanager.cn.utils; import android.util.Log; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import com.worldchip.bbp.bbpawmanager.cn.callbak.HttpResponseCallBack; public class HttpUtils { public static final String DEBUG_TAG = "HttpUtils"; /** * Http post请求 * @param xml 参数 * @param callBack 回调 */ public static void doPost(final String httpUrl, final HttpResponseCallBack callBack,final String httpTag){ new Thread(new Runnable(){ @Override public void run() { refresh(httpUrl, callBack, httpTag); } }).start(); } private static void refresh(String httpUrl,HttpResponseCallBack callBack,final String httpTag) { StringBuffer resultData = new StringBuffer(); URL url = null; try { if (callBack != null) { callBack.onStart(httpTag); } // 创建一个URL对象 url = new URL(httpUrl); } catch (MalformedURLException e) { Log.d(DEBUG_TAG, "create URL Exception"); if (callBack != null) { callBack.onFailure(e, httpTag); } } // 声明HttpURLConnection对象 HttpURLConnection urlConn = null; // 声明InputStreamReader对象 InputStreamReader in = null; // 声明BufferedReader对象 BufferedReader buffer = null; String inputLine = null; // 声明DataOutputStream流 DataOutputStream out = null; if (url != null) { try { // 使用HttpURLConnection打开连接 urlConn = (HttpURLConnection) url.openConnection(); // 因为这个是POST请求所以要设置为true urlConn.setDoInput(true); urlConn.setDoOutput(true); //设置连接主机及从主机读取数据超时时间 urlConn.setConnectTimeout(Utils.HTTP_CONNECT_TIMEOUT); urlConn.setReadTimeout(Utils.HTTP_READ_TIMEOUT); // 设置POST方式 urlConn.setRequestMethod("POST"); // POST请求不能设置缓存 urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(false); // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); //urlConn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成 // 要注意的是connectio.getOutputStream会隐含的进行connect // DataOutputStream流 out = new DataOutputStream(urlConn.getOutputStream()); urlConn.setReadTimeout(2000); out.write(httpUrl.getBytes("UTF-8")); urlConn.connect(); int code = urlConn.getResponseCode(); System.out.println("code  " + code); // 得到读取的内容(流) in = new InputStreamReader(urlConn.getInputStream()); // 创建BufferReader对象,输出时候用到 buffer = new BufferedReader(in); // 使用循环来读取数据 while ((inputLine = buffer.readLine()) != null) { // 在每一行后面加上换行 resultData.append(inputLine).append("\n"); } // 设置显示取的的内容 if (resultData != null && !resultData.equals("")) { if (callBack != null) { callBack.onSuccess(resultData.toString(),httpTag); } } else { if (callBack != null) { callBack.onSuccess("",httpTag); } } } catch (IOException e) { if (callBack != null) { callBack.onFailure(e,httpTag); } e.printStackTrace(); } finally { try { if(out!=null) { // 刷新DataOutputStream流 out.flush(); // 关闭DataOutputStream流 out.close(); } // 关闭InputStreamReader if(in!=null){ in.close(); } if(urlConn!=null) { // 关闭URL连接 urlConn.disconnect(); } if (callBack != null) { callBack.onFinish(0,httpTag); } } catch (IOException e) { if (callBack != null) { callBack.onFailure(e,httpTag); } e.printStackTrace(); } } } else { Log.d(DEBUG_TAG, "URL is NULL"); } } }
package com.chinasoft.test; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.chinasoft.dao.CkDao; import com.chinasoft.domain.Ck; import com.chinasoft.service.CkService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class CkTest { @Resource(name="ckService") private CkService ckService; @Test // Ck 添加 public void demo1(){ Ck ck = new Ck(); ck.setKcl(600); ck.setLxr("张三"); ck.setName("一号仓库"); ck.setNum("CK0010"); ck.setDh("122222222222"); try { ckService.save(ck); } catch (Exception e) { e.printStackTrace(); } } @Test public void demo2() throws Exception{ Ck ck = new Ck(); ck.setNum("CK20160701145333"); ck.setName("一号仓库"); List<Ck> cks = this.ckService.findAllCk(ck); System.out.println(cks); } }
/** * Dragster.java */ /** * Dragster is a class to represent a dragster that races at a drag strip. Create Dragster objects and "race" them to * determine their elapsed time for a 1/4 mile race. * * @author James Veith jmv5576 */ public class Dragster { /** * Private instance variable for the time it takes the driver to react to the "go" signal. * Typical time is around 0.5 second. */ private double reactionTime; /** * Private instance variable for the amount of torque (ft-lbs) generated by the engine. * Typical values are around 1000. */ private int torque; /** * Private constant to convert torque values to equivalent time. Value = 5000 */ private final double TORQUE2TIME = 5000.0; /** * Private instance variable for the amount of traction the tires have. Typical values for traction are between * 0.5 and 1.0. Tires are "conditioned" prior to racing by "burning out" (squealing the tires in place) to remove * a layer of oxidized rubber and to preheat the tire. Typical burnout times are a few seconds (under 10 seconds). */ private double traction; /** * Private instance variable for the number of seconds to "burn out" the tires. Typically under 10 seconds. */ private int burnTime; /** * Constructor for a Dragster. * @param reactionTime - time to react to start signal * @param torque - power generated by the engine * @param traction - how good the traction is * @param burn - how many seconds to "burn out" the tires */ public Dragster(double reactionTime, int torque, double traction, int burn){ this.reactionTime = reactionTime; this.torque = torque; this.traction = traction; this.burnTime = burn; } /** * Conditioning function to prepare tires for race * 2.5 * ( e^ -( (time * time - (10 * time) + 25) / 50 ) ) / sqrt( 2 * PI ) * @param time - The number of seconds to burnout the tires * @return The effectiveness of that time (a number between 0 and 1) */ private double conditionTires(double time){ return 2.5 * Math.pow( Math.E, -( (time * time - (10 * time) + 25) / 50 ) ) / Math.sqrt(2 * Math.PI); } /** * Function to "burn out" the dragster tires just prior to racing. Sets the traction as a result of "burning out" * the tires. traction = traction * burnFactor Where burnFactor is the value returned from conditionTires(). */ public void burnout(){ this.traction = conditionTires(this.burnTime); } /** * Perform the race. Calculates a race time. The race time will be determined by the following: * reactionTime + ( 1 / ( (torque / TORQUE2TIME) * effectiveTraction ) ) * @return The time for the dragster to travel 1/4 mile */ public double race(){ return this.reactionTime + ( 1 / ( (this.torque / this.TORQUE2TIME) * this.traction ) ); } /** * Returns the following String representation of this Dragster object with the following format: * Reaction Time: w Torque: x Traction: y Burn Time: z Where w, x, y, and z are the reactionTime, torque, traction and burnTime * @return a String representation of this dragster with reaction time, torque, traction and burnout time */ @Override public String toString(){ return "Reaction Time: " + this.reactionTime + " Torque: " + this.torque + " Traction: " + this.traction + " Burn Time: " + this.burnTime; } }//Class Dragster
package com.example.g0294.tutorial.memoryleak; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.g0294.tutorial.R; public class MemoryTwo extends Activity{ public static final String TAG = "Memory Two"; private Object[] mObjs = new Object[10000];//快速消耗記憶體 private Button mBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.memorytwo_layout); mBtn = (Button) findViewById(R.id.btn); mBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (int i = 0; i < mObjs.length; i++) { mObjs[i] = new Object(); } finish(); } }); ActivityManager.instance().registActivity(this); } @Override protected void onDestroy() { super.onDestroy(); // ActivityManager.instance().unRigistActivity(this); } }
package com.bigpotato.async.hystrix; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; /** * Created by hjy on 16/9/20. */ public class HelloCommand extends HystrixCommand<String> { private final String name; public HelloCommand(String name) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.name = name; } @Override protected String run() throws Exception { Thread.sleep(1000); System.out.println("Thread ID: " + Thread.currentThread().getId() + "HelloCommand"); return "hello " + name; } }
/* * 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 dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import model.Assignment; import model.AssignmentInCourse; import model.Course; import model.Student; import model.StudentInCourse; import model.Trainer; import model.TrainerInCourse; import utils.DBUtils; /** * * @author Los_e */ public class AssignmentInCourseDAO { public static ArrayList<AssignmentInCourse> getAllAssignmentsPerCourse() { ArrayList<AssignmentInCourse> list = new ArrayList<>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "SELECT * FROM courses c " + "inner join " + "assignmentsincourses sc on sc.courseid = c.courseid " + "inner join " + "assignments s on sc.assignmentid = s.assignmentid " + "order by c.courseid;"; try { pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(sql); while (rs.next()) { Course course = new Course(); course.setCourseid(rs.getInt(1)); course.setTitle(rs.getString(2)); course.setStream(rs.getString(3)); course.setType(rs.getString(4)); course.setStartdate(rs.getString(5)); course.setStartdate(rs.getString(6)); Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(10)); assignment.setTitle(rs.getString(11)); assignment.setDescription(rs.getString(12)); AssignmentInCourse assignmentincourse = new AssignmentInCourse(); assignmentincourse.setAssignment(assignment); assignmentincourse.setCourse(course); assignmentincourse.setSubmissiondatetime(rs.getString(9)); list.add(assignmentincourse); } } catch (SQLException ex) { Logger.getLogger(AssignmentInCourseDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentInCourseDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentInCourseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static ArrayList<Assignment> getAssignmentsNotAppointedToCourse(int courseid) { ArrayList<Assignment> list = new ArrayList<Assignment>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "select table1.* from " + "" + "(select s2.* from assignments s2 ) as table1 " + "" + "left join " + "" + "(select s1.* from assignments s1 " + "left join assignmentsincourses sc1 on sc1.assignmentid = s1.assignmentid " + "where sc1.courseid=?) as table2 " + "" + "on table1.assignmentid = table2.assignmentid " + "where table2.assignmentid is null " + ";"; try { pst = con.prepareStatement(sql); pst.setInt(1, courseid); ResultSet rs = pst.executeQuery(); while (rs.next()) { Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(1)); assignment.setTitle(rs.getString(2)); assignment.setDescription(rs.getString(3)); list.add(assignment); } } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static ArrayList<Assignment> getAssignmentsAppointedToCourse(int courseid) { ArrayList<Assignment> list = new ArrayList<Assignment>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "SELECT * " + "FROM assignments s " + "LEFT JOIN assignmentsincourses sc ON sc.assignmentid = s.assignmentid " + "WHERE sc.courseid=?;"; try { pst = con.prepareStatement(sql); pst.setInt(1, courseid); ResultSet rs = pst.executeQuery(); while (rs.next()) { Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(1)); assignment.setTitle(rs.getString(2)); assignment.setDescription(rs.getString(3)); list.add(assignment); } } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static void insertAssignmentInCourse(AssignmentInCourse assignmentincourse) { Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "insert into assignmentsincourses(courseid, assignmentid, submissiondatetime) values (?, ?, ?)"; boolean result = false; try { pst = con.prepareStatement(sql); pst.setInt(1, assignmentincourse.getCourse().getCourseid()); pst.setInt(2, assignmentincourse.getAssignment().getAssignmentid()); pst.setString(3, assignmentincourse.getSubmissiondatetime().toString()); pst.executeUpdate(); result = true; } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); result = false; } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } } if (result) { System.out.println("Appointed Assignment to Course"); } // return result; } public static void updateAssignmentInCourse(AssignmentInCourse assignmentincourse) { Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "UPDATE assignmentsincourses SET submissiondatetime = ? /*1*/ WHERE assignmentid = ? /*2*/ and courseid = ? /*3*/ "; boolean result = false; try { pst = con.prepareStatement(sql); pst.setString(1, assignmentincourse.getSubmissiondatetime().toString()); pst.setInt(2, assignmentincourse.getAssignment().getAssignmentid()); pst.setInt(3, assignmentincourse.getCourse().getCourseid()); pst.executeUpdate(); result = true; } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); result = false; } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } } if (result) { System.out.println("Enrolled Assignment to Course"); } // return result; } public static void deleteAssignmentFromCourse(int assignmentid, int courseid) { Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "DELETE from assignmentsincourses WHERE assignmentid = ? /*1*/ and courseid = ? /*2*/ "; boolean result = false; try { pst = con.prepareStatement(sql); pst.setInt(1, assignmentid); pst.setInt(2, courseid); pst.executeUpdate(); result = true; } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); result = false; } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(AssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } } if (result) { System.out.println("Deleted Assignment from Course"); } // return result; } }
package com.marcioalexfig.blognoticias.modelo; /** * Created by alex on 25/05/2016. */ public class Noticia { String titulo; String link; String imageLink; public Noticia() {} public Noticia(String titulo, String link, String imageLink) { this.titulo = titulo; this.link = link; this.imageLink = imageLink; } public String getTitulo() { return titulo; } public String getLink() { return link; } public String getImageLink() { return imageLink; } public void setTitulo(String titulo) { this.titulo = titulo; } public void setLink(String link) { this.link = link; } public void setImageLink(String imageLink) { this.imageLink = imageLink; } }
package com.pwq.Stream; import org.junit.Test; import java.io.*; /** * Created by pwq on 2018/1/14. */ public class BufferStreamTest { public static void main(String[] args) throws IOException { FileInputStream fileInputStream = new FileInputStream("示例图片_02.jpg"); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); FileOutputStream fileOutputStream = new FileOutputStream("示例图片copybuff.jpg"); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); int b = 0; while((b=bufferedInputStream.read())!=-1){ bufferedOutputStream.write(b); } bufferedInputStream.close(); bufferedOutputStream.close(); } public void CloseAndFlush() throws IOException { BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("示例图片_02.jpg")); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("示例图片copyflush.jpg")); int b = 0; while((b=bufferedInputStream.read())!=-1){ bufferedOutputStream.write(b); } //不关闭的情况:close具备刷新的功能,在关闭流之前,会帅新一次缓冲区,将缓冲区的字节流全都刷新到文件中区 } @Test public void BufferT() throws IOException { BufferedReader bf = new BufferedReader(new FileReader("pom.xml")); BufferedWriter bw = new BufferedWriter(new FileWriter("pwq.xml")); int x ; while((x=bf.read())!=-1){ bw.write(x); } bf.close(); bw.close(); } @Test public void BufferT1() throws IOException { BufferedReader bf = new BufferedReader(new FileReader("pom.xml")); BufferedWriter bw = new BufferedWriter(new FileWriter("pwq.xml")); String line ; while((line=bf.readLine())!=null){ System.out.println(line); } bf.close(); bw.close(); } }
package by.htp.cratemynewpc.controller.command.impl; import by.htp.cratemynewpc.controller.command.Command; import by.htp.cratemynewpc.domain.PCBean; import by.htp.cratemynewpc.service.PcService; import by.htp.cratemynewpc.service.ServiceFactory; import by.htp.cratemynewpc.service.exception.ServiceException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public class DeleteUserPC implements Command { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int pcId = Integer.parseInt(request.getParameter("pcId")); String login = request.getParameter("login"); String goToPage = null; ServiceFactory factory = ServiceFactory.getInstance(); try { factory.getPCService().deleteService(pcId); } catch (ServiceException e) { e.printStackTrace(); } try { PcService pcService = factory.getPCService(); List<PCBean> findPC = pcService.findAllService(); request.setAttribute("findPC", findPC); }catch(ServiceException e) { //TODO log } request.setAttribute("login", login); try { goToPage = JSPPagePath.USER_MAIN; request.getRequestDispatcher(goToPage).forward(request, response); } catch (ServletException | IOException e) { //TODO log; } } }
package com.example.prova; import androidx.annotation.StringRes; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class TrisActivity extends AppCompatActivity { private static final String TAG= "TrisActivity"; private int m[][]; private boolean g1; private TextView lblTit; private TextView txtTurniTris; //possibilità 1 Button b00, b01, b02; Button b10, b11, b12; Button b20, b21, b22; private Button btnPlay; //possibilità 2 Button b[][]; /*private Button btn00, btn01, btn02; private Button btn10, btn11, btn12; private Button btn20, btn21, btn22; private Button btnPlay; private TextView txtTurniTris; private int num = 1; private boolean win = false;*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tris); bindComponent(); setupEventListener(); lblTit = findViewById(R.id.lblTit); Intent intent; intent = getIntent(); lblTit.setText(intent.getStringExtra("g1")+ " VS "+ intent.getStringExtra("g2")); //init giocatore g1=true; //init matrice m= new int[3][3]; for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ m[i][j]=0; } } //poss 1 /*b00.setOnClickListener(new myListener()); b01.setOnClickListener(new myListener()); b02.setOnClickListener(new myListener()); b10.setOnClickListener(new myListener()); b11.setOnClickListener(new myListener()); b12.setOnClickListener(new myListener()); b20.setOnClickListener(new myListener()); b21.setOnClickListener(new myListener()); b22.setOnClickListener(new myListener());*/ //possibilità 2 for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ b[i][j].setOnClickListener(new myListener()); } } } private void bindComponent(){ lblTit = findViewById(R.id.lblTit); txtTurniTris = findViewById(R.id.txtTurniTris); btnPlay = findViewById(R.id.btnPlay); //possibilità 1 /*b00 = findViewById(R.id.btn00); b01 = findViewById(R.id.btn01); b02 = findViewById(R.id.btn02); b10 = findViewById(R.id.btn10); b11 = findViewById(R.id.btn11); b12 = findViewById(R.id.btn12); b20 = findViewById(R.id.btn20); b21 = findViewById(R.id.btn21); b22 = findViewById(R.id.btn22);*/ //possibilità 2 b = new Button[3][3]; b[0][0]= findViewById(R.id.btn00); //b[0][0].setTransitionName("btn_0_0"); b[0][1]= findViewById(R.id.btn01); //b[0][1].setTransitionName("btn_0_1"); b[0][2]= findViewById(R.id.btn02); //b[0][2].setTransitionName("btn_0_2"); b[1][0]= findViewById(R.id.btn10); //b[1][0].setTransitionName("btn_1_0"); b[1][1]= findViewById(R.id.btn11); //b[1][1].setTransitionName("btn_1_1"); b[1][2]= findViewById(R.id.btn12); //b[1][2].setTransitionName("btn_1_2"); b[2][0]= findViewById(R.id.btn20); //b[2][0].setTransitionName("btn_2_0"); b[2][1]= findViewById(R.id.btn21); //b[2][1].setTransitionName("btn_2_1"); b[2][2]= findViewById(R.id.btn22); //b[2][2].setTransitionName("btn_2_2"); } private void setupEventListener(){ btnPlay.setOnClickListener(new View.OnClickListener() { boolean res = false; public void onClick(View v) { for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ b[i][j].setEnabled(true); } } txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); btnPlay.setText("Reset"); if(res==true){ //reset del gioco (è uguale all'onCreate) /*lblTit = findViewById(R.id.lblTit); Intent intent; intent = getIntent(); lblTit.setText(intent.getStringExtra("g1")+ " VS "+ intent.getStringExtra("g2")); //init giocatore g1=true; //init matrice m= new int[3][3]; for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ m[i][j]=0; } } for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ b[i][j].setOnClickListener(new myListener()); } }*/ Intent intent = new Intent(TrisActivity.this, TrisActivity.class); intent.putExtra("g1", "Giocatore 1"); intent.putExtra("g2", "Giocatore 2"); startActivity(intent); res=false; } res = true; } }); } void reset(){ //init giocatore g1=true; //init matrice m= new int[3][3]; for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ m[i][j]=0; } } for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ b[i][j].setOnClickListener(new myListener()); } } } void vince(String g){ Toast.makeText(this, g, Toast.LENGTH_LONG).show(); } void bloccaPulsanti(){ //Possibilità 1 /*b00.setEnabled(false); b01.setEnabled(false); b02.setEnabled(false); b10.setEnabled(false); b11.setEnabled(false); b12.setEnabled(false); b20.setEnabled(false); b21.setEnabled(false); b22.setEnabled(false);*/ //possibilità 2 for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ b[i][j].setEnabled(false); } } } class myListener implements View.OnClickListener{ private static final String TAG= "ClassListener"; @Override public void onClick(View v) { boolean vittoria; int x,y; // 1. rintracciare pulsante chiamante Button bL = (Button) v; Log.i(TAG, String.valueOf(bL.getId())); //2. assegno a x y le coordinate lette dal Button x= Integer.parseInt(bL.getTransitionName().split("_")[1]); y= Integer.parseInt(bL.getTransitionName().split("_")[2]); if(g1){ m[x][y]=1; g1= false; bL.setBackgroundResource(R.color.colorLRed); }else{ m[x][y]=2; g1 = true; bL.setBackgroundResource(R.color.colorLBlue); } bL.setEnabled(false); //disabilitiamo il click del pulsante vittoria = false; //controllo vittoria //VERTICALE if(m[0][y] == m[x][y] && m[1][y]==m[x][y] && m[2][y]==m[x][y]){ //vittoria verticale vittoria = true; }else{ //ORIZZONTALE if(m[x][0] == m[x][y] && m[x][1] == m[x][y] && m[x][2] == m[x][y]){ vittoria = true; }else{ //DIAGONALE principale if(m[0][0]== m[x][y] && m[1][1]== m[x][y] && m[2][2]== m[x][y]){ vittoria = true; }else if(m[2][0]== m[x][y] && m[1][1]== m[x][y] && m[0][2]== m[x][y]){ //diagonale secondaria vittoria = true; } } } if(vittoria){ if (!g1) { //ATTENZIONE, G1 (DOPO IL CLICK) DIVENTA FALSE Log.d(TAG, "Vince giocatore 1"); vince("Vince giocatore 1"); }else { Log.d(TAG, "Vince giocatore 2"); vince("Vince giocatore 2"); } bloccaPulsanti(); } } } /* private void setupEventListener() { btnPlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btn00.setEnabled(true); btn01.setEnabled(true); btn02.setEnabled(true); btn10.setEnabled(true); btn11.setEnabled(true); btn12.setEnabled(true); btn20.setEnabled(true); btn21.setEnabled(true); btn22.setEnabled(true); txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); btnPlay.setEnabled(false); } }); //Bottone 00 btn00.setOnClickListener(new View.OnClickListener() { @SuppressLint({"ResourceAsColor", "SetTextI18n"}) @Override public void onClick(View v) { if (num%2==0) { num++; btn00.setText("O"); btn00.setBackgroundResource(R.color.colorLBlue); //controllo se ha fatto una serie di 3 if((btn01.getText().equals("O") && btn02.getText().equals("O")) || (btn10.getText().equals("O") && btn20.getText().equals("O")) || (btn11.getText().equals("O") && btn22.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn00.setEnabled(false); }else{ num++; btn00.setText("X"); btn00.setBackgroundResource(R.color.colorLRed); if((btn01.getText().equals("X") && btn02.getText().equals("X")) || (btn10.getText().equals("X") && btn20.getText().equals("X")) || (btn11.getText().equals("X") && btn22.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g1")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn00.setEnabled(false); } if(num==10 && win==false){ txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); //Bottone 01 btn01.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { if (num%2==0) { num++; btn01.setText("O"); btn01.setBackgroundResource(R.color.colorLBlue); if((btn00.getText().equals("O") && btn02.getText().equals("O")) || (btn11.getText().equals("O") && btn21.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn01.setEnabled(false); }else{ num++; btn01.setText("X"); btn01.setBackgroundResource(R.color.colorLRed); if((btn00.getText().equals("X") && btn02.getText().equals("X")) || (btn11.getText().equals("X") && btn21.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g1")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn01.setEnabled(false); } if(num==10 && win==false){ txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); //Bottone 02 btn02.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { if (num%2==0) { num++; btn02.setText("O"); btn02.setBackgroundResource(R.color.colorLBlue); if((btn00.getText().equals("O") && btn01.getText().equals("O")) || (btn11.getText().equals("O") && btn20.getText().equals("O")) || (btn12.getText().equals("O") && btn22.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn02.setEnabled(false); }else{ num++; btn02.setText("X"); btn02.setBackgroundResource(R.color.colorLRed); if((btn00.getText().equals("X") && btn01.getText().equals("X")) || (btn11.getText().equals("X") && btn20.getText().equals("X")) || (btn12.getText().equals("X") && btn22.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g1")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn02.setEnabled(false); } if(num==10 && win==false){ txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); //Bottone 10 btn10.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { if (num%2==0) { num++; btn10.setText("O"); btn10.setBackgroundResource(R.color.colorLBlue); if((btn00.getText().equals("O") && btn20.getText().equals("O")) || (btn11.getText().equals("O") && btn12.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn10.setEnabled(false); }else{ num++; btn10.setText("X"); btn10.setBackgroundResource(R.color.colorLRed); if((btn00.getText().equals("X") && btn20.getText().equals("X")) || (btn11.getText().equals("X") && btn12.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g1")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn10.setEnabled(false); } if(num==10 && win==false){ txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); //Bottone 11 btn11.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { if (num%2==0) { num++; btn11.setText("O"); btn11.setBackgroundResource(R.color.colorLBlue); if((btn00.getText().equals("O") && btn22.getText().equals("O")) || (btn10.getText().equals("O") && btn12.getText().equals("O")) || (btn20.getText().equals("O") && btn02.getText().equals("O")) || (btn01.getText().equals("O") && btn21.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn11.setEnabled(false); }else{ num++; btn11.setText("X"); btn11.setBackgroundResource(R.color.colorLRed); if((btn00.getText().equals("X") && btn22.getText().equals("X")) || (btn10.getText().equals("X") && btn12.getText().equals("X")) || (btn20.getText().equals("X") && btn02.getText().equals("X")) || (btn01.getText().equals("X") && btn21.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn11.setEnabled(false); } if(num==10 && win==false){ txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); //Bottone 12 btn12.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { if (num%2==0) { num++; btn12.setText("O"); btn12.setBackgroundResource(R.color.colorLBlue); if((btn02.getText().equals("O") && btn22.getText().equals("O")) || (btn10.getText().equals("O") && btn11.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn12.setEnabled(false); }else{ num++; btn12.setText("X"); btn12.setBackgroundResource(R.color.colorLRed); if((btn02.getText().equals("X") && btn22.getText().equals("X")) || (btn10.getText().equals("X") && btn11.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn12.setEnabled(false); } if(num==10 && win==false){ txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); //bottone 20 btn20.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { if (num%2==0) { num++; btn20.setText("O"); btn20.setBackgroundResource(R.color.colorLBlue); if((btn00.getText().equals("O") && btn10.getText().equals("O")) || (btn11.getText().equals("O") && btn02.getText().equals("O")) || (btn21.getText().equals("O") && btn22.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn20.setEnabled(false); }else{ num++; btn20.setText("X"); btn20.setBackgroundResource(R.color.colorLRed); if((btn00.getText().equals("X") && btn10.getText().equals("X")) || (btn11.getText().equals("X") && btn02.getText().equals("X")) || (btn21.getText().equals("X") && btn12.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn20.setEnabled(false); } if(num==10 && win==false){ txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); //Bottone 21 btn21.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { if (num%2==0) { num++; btn21.setText("O"); btn21.setBackgroundResource(R.color.colorLBlue); if((btn01.getText().equals("O") && btn11.getText().equals("O")) || (btn20.getText().equals("O") && btn22.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn21.setEnabled(false); }else{ num++; btn21.setText("X"); btn21.setBackgroundResource(R.color.colorLRed); if((btn01.getText().equals("X") && btn11.getText().equals("X")) || (btn20.getText().equals("X") && btn22.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn21.setEnabled(false); } if(num==10 && win==false){ txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); //Bottone 22 btn22.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { if (num%2==0) { num++; btn22.setText("O"); btn22.setBackgroundResource(R.color.colorLBlue); if((btn00.getText().equals("O") && btn11.getText().equals("O")) || (btn02.getText().equals("O") && btn12.getText().equals("O")) || (btn20.getText().equals("O") && btn21.getText().equals("O"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLRed); txtTurniTris.setText(getIntent().getStringExtra("g1")); } btn22.setEnabled(false); }else{ num++; btn22.setText("X"); btn22.setBackgroundResource(R.color.colorLRed); if((btn02.getText().equals("X") && btn12.getText().equals("X")) || (btn00.getText().equals("X") && btn11.getText().equals("X")) || (btn20.getText().equals("X") && btn21.getText().equals("X"))){ txtTurniTris.setBackgroundResource(R.color.colorGreen); txtTurniTris.setText("Ha vinto "+ getIntent().getStringExtra("g2")); btn01.setEnabled(false); btn02.setEnabled(false); btn10.setEnabled(false); btn11.setEnabled(false); btn12.setEnabled(false); btn20.setEnabled(false); btn21.setEnabled(false); btn22.setEnabled(false); win=true; }else { txtTurniTris.setBackgroundResource(R.color.colorLBlue); txtTurniTris.setText(getIntent().getStringExtra("g2")); } btn22.setEnabled(false); } if(num==10 && win==false) { txtTurniTris.setBackgroundResource(R.color.colorLYel); txtTurniTris.setText("Pareggio!"); } } }); } private void bindComponent(){ txtTurniTris= findViewById(R.id.txtTurniTris); btnPlay = findViewById(R.id.btnPlay); btn00 = findViewById(R.id.btn00); btn01 = findViewById(R.id.btn01); btn02 = findViewById(R.id.btn02); btn10 = findViewById(R.id.btn10); btn11 = findViewById(R.id.btn11); btn12 = findViewById(R.id.btn12); btn20 = findViewById(R.id.btn20); btn21 = findViewById(R.id.btn21); btn22 = findViewById(R.id.btn22); }*/ }
package com.example.gubee.hexagon.api.impl; import java.util.List; import com.example.gubee.hexagon.api.ServicoTecnologia; import com.example.gubee.hexagon.domain.Tecnologia; import com.example.gubee.hexagon.spi.TecnologiaRepository; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class ServicoTecnologiaImpl implements ServicoTecnologia{ private final TecnologiaRepository repository; @Override public Tecnologia save(Tecnologia tecnologia) { return repository.save(tecnologia); } @Override public void update(int id, Tecnologia tecnologia) { repository.update(id, tecnologia); } @Override public void delete(int id) { repository.delete(id); } @Override public Tecnologia getById(int id) { return repository.getById(id); } @Override public List<Tecnologia> getAll() { return repository.getAll(); } }
package com.forestry.service.sys; import com.forestry.model.sys.SensorLastData; import core.service.Service; /** * @框架唯一的升级和技术支持地址:https://item.taobao.com/item.htm?spm=a230r.7195193.1997079397.8.wNJFq2&id=551763724593&abbucket=20 */ public interface SensorLastDataService extends Service<SensorLastData> { }
package com.flavio.android.petlegal.view; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.flavio.android.petlegal.R; import com.flavio.android.petlegal.controll.ControlaPessoa; import com.flavio.android.petlegal.controll.ControlaTelefone; import com.flavio.android.petlegal.controll.ControlaUsuario; import com.flavio.android.petlegal.model.Pessoa; import com.flavio.android.petlegal.model.Telefone; import com.flavio.android.petlegal.model.Usuario; import java.util.ArrayList; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; public class UserPerfil extends AppCompatActivity { private static final int TELEFONE_CODE_REQUEST = 10; private CircleImageView foto; private ImageButton btnAtualiza; private TextView verNoMaps,nomeUsuario,nomeCompleto,email,endereco,bairro,cep,complemento; private ListView listaTelefones; private int id; ControlaPessoa cp; ControlaUsuario cu; ControlaTelefone ct; Pessoa pessoa; Usuario user; Telefone telefoneSelecionado; private String localArquivoFoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_user_perfil ); foto = (CircleImageView)findViewById (R.id.imgFotoUserPerfil ); btnAtualiza = findViewById ( R.id.btnAtualizaUsuarioPerfil ); nomeUsuario = findViewById ( R.id.txtPerfilUserNome ); nomeCompleto = findViewById ( R.id.txtUserPerfilNomeCompleto ); email = findViewById ( R.id.txtUserPerfilEmail ); endereco = findViewById ( R.id.txtUserPerfilEndereco ); bairro = findViewById ( R.id.txtUserPerfilBairro ); complemento = findViewById ( R.id.txtUserPerfilComplemento ); cep = findViewById ( R.id.txtUserPerfilCep) ; listaTelefones = (ListView)findViewById ( R.id.listaUserPerfilTelefones ); verNoMaps = (TextView) findViewById ( R.id.txtVerMaps ); cp = new ControlaPessoa ( getApplicationContext () ); cu = new ControlaUsuario ( getApplicationContext () ); ct = new ControlaTelefone ( getApplicationContext () ); Bundle bundle = getIntent ().getExtras (); id = bundle.getInt ( "id" ); listaTelefones(); /**Carrega pessoa e usuario*/ this.pessoa = cp.returnPessoaById ( id ); this.user = cu.consultraUsuarioById ( id ); localArquivoFoto = pessoa.getCaminhoFotoPessoa (); /**Carrega as textViews*/ nomeUsuario.setText ( pessoa.getNome () ); nomeCompleto.setText ( pessoa.getNome ()+" "+pessoa.getSobrenome ()); email.setText ( "Email: "+pessoa.getEmail () ); endereco.setText ("Endereço: "+ pessoa.getLogradouro ()+"\t Número: "+String.valueOf ( pessoa.getNumero () ) ); bairro.setText ("Bairro: "+ pessoa.getBairro () ); complemento.setText ( "Complemento: "+pessoa.getComplemento () ); cep.setText ("CEP: "+ String.valueOf ( pessoa.getCep () ) ); //Latitude -23.6632222 //Longitude -46.7290609 da Fatec zona sul verNoMaps.setOnClickListener ( new View.OnClickListener () { @Override public void onClick(View view) { Uri gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=-23.663183, -46.729104"); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); mapIntent.setPackage("com.google.android.apps.maps"); startActivity(mapIntent); } } ); btnAtualiza.setOnClickListener ( new View.OnClickListener () { @Override public void onClick(View view) { Intent it = new Intent(UserPerfil.this, AtualizaPerfil.class); it.putExtra ( "id",id); startActivity ( it ); } } ); registerForContextMenu(listaTelefones); carregaImagem (); } public void sendMessage(String texto){ Toast.makeText ( this, texto, Toast.LENGTH_SHORT ).show (); } public void listaTelefones(){ List<Telefone> telefones = new ArrayList<> ( ); telefones = ct.listaTelefones ( id ); ArrayAdapter<Telefone> adaptador = new ArrayAdapter<Telefone> (this,android.R.layout.simple_list_item_1,telefones ); listaTelefones.setAdapter ( adaptador ); } @Override protected void onResume() { super.onResume(); listaTelefones (); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; telefoneSelecionado = (Telefone) listaTelefones.getAdapter().getItem(info.position); //Ligar MenuItem ligar = menu.add("Ligar"); ligar.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { String permissaoLigacao = android.Manifest.permission.CALL_PHONE; if (ActivityCompat.checkSelfPermission(UserPerfil.this, permissaoLigacao) == PackageManager.PERMISSION_GRANTED) { fazerLigacao(); } else { ActivityCompat.requestPermissions(UserPerfil.this, new String[]{permissaoLigacao}, TELEFONE_CODE_REQUEST); } return false; } } ); //Enviar SMS if(telefoneSelecionado.getTipoTel ()==0) { MenuItem sms = menu.add ( "Enviar SMS" ); Intent intentSms = new Intent ( Intent.ACTION_VIEW ); intentSms.setData ( Uri.parse ( "sms:" + telefoneSelecionado.getNumeroTel () ) ); intentSms.putExtra ( "sms_body", "Mensagem" ); sms.setIntent ( intentSms ); } MenuItem deletar = menu.add("Deletar"); deletar.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { //Metodo para deletar @Override public boolean onMenuItemClick(MenuItem item) { ct.deletaTelefone ( telefoneSelecionado ); listaTelefones(); return false; } }); } private void fazerLigacao() { Intent intentLigar = new Intent(Intent.ACTION_CALL); intentLigar.setData(Uri.parse("tel:" + telefoneSelecionado.getNumeroTel ())); //CUIDADO O NOME DENTRO DE "" DEVE XTAR EM MINIUSCULA tel if (ActivityCompat.checkSelfPermission(UserPerfil.this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { return; } startActivity(intentLigar); } public void carregaImagem() { if (localArquivoFoto != null && !localArquivoFoto.equals ( "" )) { Bitmap imagemFoto = BitmapFactory.decodeFile ( localArquivoFoto ); Bitmap imagemFotoReduzida = Bitmap.createScaledBitmap ( imagemFoto, 600, 300, false ); foto.setImageBitmap ( imagemFotoReduzida ); foto.setTag ( localArquivoFoto ); //foto1.setScaleType(ImageView.ScaleType.FIT_XY); } } @Override public void onBackPressed() { Intent intent = new Intent ( this, User.class ); intent.putExtra ( "id",id ); startActivity ( intent ); } }
/* * 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 calculadora; /** * * @author Aluno */ public class ViewCalculadora extends javax.swing.JFrame { /** * Creates new form NewJFrame */ public ViewCalculadora() { initComponents(); } double valor1; double valor2; String sinal; /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnNumero5 = new javax.swing.JButton(); btnSomar = new javax.swing.JButton(); btnNumero6 = new javax.swing.JButton(); txtVisorCalculator = new javax.swing.JTextField(); btnLimparVariaveis = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); btnNumero1 = new javax.swing.JButton(); btnDividir = new javax.swing.JButton(); btnNumero7 = new javax.swing.JButton(); btnNumero3 = new javax.swing.JButton(); btnNumero9 = new javax.swing.JButton(); btnSubtrair = new javax.swing.JButton(); btnNumero8 = new javax.swing.JButton(); btnNumero0 = new javax.swing.JButton(); btnLimparVisot = new javax.swing.JButton(); btnPonto = new javax.swing.JButton(); btnMultiplicar = new javax.swing.JButton(); btnIgual = new javax.swing.JButton(); btnNumero4 = new javax.swing.JButton(); btNumero2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnNumero5.setText("5"); btnNumero5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero5ActionPerformed(evt); } }); btnSomar.setText("+"); btnSomar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSomarActionPerformed(evt); } }); btnNumero6.setText("6"); btnNumero6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero6ActionPerformed(evt); } }); btnLimparVariaveis.setText("C"); btnLimparVariaveis.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLimparVariaveisActionPerformed(evt); } }); jPanel1.setBackground(new java.awt.Color(51, 102, 255)); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setText("CALCULADORA"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(84, 84, 84)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jLabel1) .addContainerGap(23, Short.MAX_VALUE)) ); btnNumero1.setText("1"); btnNumero1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero1ActionPerformed(evt); } }); btnDividir.setText("/"); btnDividir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDividirActionPerformed(evt); } }); btnNumero7.setText("7"); btnNumero7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero7ActionPerformed(evt); } }); btnNumero3.setText("3"); btnNumero3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero3ActionPerformed(evt); } }); btnNumero9.setText("9"); btnNumero9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero9ActionPerformed(evt); } }); btnSubtrair.setText("-"); btnSubtrair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSubtrairActionPerformed(evt); } }); btnNumero8.setText("8"); btnNumero8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero8ActionPerformed(evt); } }); btnNumero0.setText("0"); btnNumero0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero0ActionPerformed(evt); } }); btnLimparVisot.setText("CE"); btnLimparVisot.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLimparVisotActionPerformed(evt); } }); btnPonto.setText("."); btnPonto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPontoActionPerformed(evt); } }); btnMultiplicar.setText("*"); btnMultiplicar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnMultiplicarActionPerformed(evt); } }); btnIgual.setText("="); btnIgual.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnIgualActionPerformed(evt); } }); btnNumero4.setText("4"); btnNumero4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNumero4ActionPerformed(evt); } }); btNumero2.setText("2"); btNumero2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btNumero2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtVisorCalculator) .addGroup(layout.createSequentialGroup() .addComponent(btnNumero7, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnNumero8, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnNumero9, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnLimparVisot, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnMultiplicar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(btnNumero0, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnPonto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(btnNumero1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btNumero2, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnNumero3, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(btnNumero4, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnNumero5, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnNumero6, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnLimparVariaveis, javax.swing.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE) .addComponent(btnIgual, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnDividir, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSubtrair, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSomar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, 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(26, 26, 26) .addComponent(txtVisorCalculator, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNumero7) .addComponent(btnNumero9) .addComponent(btnNumero8) .addComponent(btnLimparVisot) .addComponent(btnMultiplicar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNumero4) .addComponent(btnNumero5) .addComponent(btnNumero6) .addComponent(btnLimparVariaveis) .addComponent(btnDividir)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNumero1) .addComponent(btnNumero3) .addComponent(btNumero2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNumero0) .addComponent(btnPonto))) .addComponent(btnIgual, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(btnSubtrair) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnSomar))) .addGap(0, 42, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnNumero5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero5ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "5"); }//GEN-LAST:event_btnNumero5ActionPerformed private void btnNumero6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero6ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "6"); }//GEN-LAST:event_btnNumero6ActionPerformed private void btnNumero1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero1ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "1"); }//GEN-LAST:event_btnNumero1ActionPerformed private void btnNumero7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero7ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "7"); }//GEN-LAST:event_btnNumero7ActionPerformed private void btnNumero3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero3ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "3"); }//GEN-LAST:event_btnNumero3ActionPerformed private void btnNumero9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero9ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "9"); }//GEN-LAST:event_btnNumero9ActionPerformed private void btnNumero8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero8ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "8"); }//GEN-LAST:event_btnNumero8ActionPerformed private void btnNumero0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero0ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "0"); }//GEN-LAST:event_btnNumero0ActionPerformed private void btnLimparVisotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparVisotActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(""); }//GEN-LAST:event_btnLimparVisotActionPerformed private void btnPontoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPontoActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "."); }//GEN-LAST:event_btnPontoActionPerformed private void btnNumero4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNumero4ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "4"); }//GEN-LAST:event_btnNumero4ActionPerformed private void btNumero2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNumero2ActionPerformed // TODO add your handling code here: txtVisorCalculator.setText(txtVisorCalculator.getText() + "2"); }//GEN-LAST:event_btNumero2ActionPerformed private void btnSomarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSomarActionPerformed // TODO add your handling code here: valor1 = Double.parseDouble(txtVisorCalculator.getText()); txtVisorCalculator.setText(""); sinal = "somar"; }//GEN-LAST:event_btnSomarActionPerformed private void btnIgualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIgualActionPerformed // TODO add your handling code here: valor2 = Double.parseDouble(txtVisorCalculator.getText()); if(sinal == "somar") { txtVisorCalculator.setText(String.valueOf(valor1 + valor2)); } if(sinal == "subtrair") { txtVisorCalculator.setText(String.valueOf(valor1 - valor2)); } if(sinal == "dividir") { txtVisorCalculator.setText(String.valueOf(valor1 / valor2)); } if(sinal == "multiplicar") { txtVisorCalculator.setText(String.valueOf(valor1 * valor2)); } }//GEN-LAST:event_btnIgualActionPerformed private void btnSubtrairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubtrairActionPerformed // TODO add your handling code here: valor1 = Double.parseDouble(txtVisorCalculator.getText()); txtVisorCalculator.setText(""); sinal = "subtrair"; }//GEN-LAST:event_btnSubtrairActionPerformed private void btnDividirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDividirActionPerformed // TODO add your handling code here: valor1 = Double.parseDouble(txtVisorCalculator.getText()); txtVisorCalculator.setText(""); sinal = "dividir"; }//GEN-LAST:event_btnDividirActionPerformed private void btnMultiplicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMultiplicarActionPerformed // TODO add your handling code here: valor1 = Double.parseDouble(txtVisorCalculator.getText()); txtVisorCalculator.setText(""); sinal = "multiplicar"; }//GEN-LAST:event_btnMultiplicarActionPerformed private void btnLimparVariaveisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparVariaveisActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnLimparVariaveisActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewCalculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewCalculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewCalculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewCalculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewCalculadora().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btNumero2; private javax.swing.JButton btnDividir; private javax.swing.JButton btnIgual; private javax.swing.JButton btnLimparVariaveis; private javax.swing.JButton btnLimparVisot; private javax.swing.JButton btnMultiplicar; private javax.swing.JButton btnNumero0; private javax.swing.JButton btnNumero1; private javax.swing.JButton btnNumero3; private javax.swing.JButton btnNumero4; private javax.swing.JButton btnNumero5; private javax.swing.JButton btnNumero6; private javax.swing.JButton btnNumero7; private javax.swing.JButton btnNumero8; private javax.swing.JButton btnNumero9; private javax.swing.JButton btnPonto; private javax.swing.JButton btnSomar; private javax.swing.JButton btnSubtrair; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JTextField txtVisorCalculator; // End of variables declaration//GEN-END:variables }
import java.util.*; class ques1d11 { static int palin(String s) { int a[]=new int[26]; s=s.toUpperCase(); for(int i=65;i<=90;i++) { for(int j=0;j<s.length();j++) { if((int)s.charAt(j)==i) a[i-65]++; } } int c=0; for(int i=0;i<26;i++) { if(a[i]%2!=0) c++; if(c>1) return 0; } return 1; } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter String "); String s=sc.next(); if(palin(s)==1) System.out.println("YES"); else System.out.println("NO"); } }
package com.experian.brand.entity; /** * 映射表: brand_category_check */ public class BrandCategoryCheck { /** * 映射字段: id */ private Integer id; /** * 映射字段: content */ private String content; /** * 映射字段: category_id */ private Integer categoryId; /** * 用于显示 */ private String category; /** * 对应BrandType */ private String type; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content == null ? null : content.trim(); } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
package com.lsjr.zizi.chat.xmpp.listener; public interface AuthStateListener { public static final int AUTH_STATE_NOT = 1; // 未登录 public static final int AUTH_STATE_ING = 2; // 登录中 public static final int AUTH_STATE_SUCCESS = 3;// 已经认证 public void onAuthStateChange(int authState); }
package org.pdffusion; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class PdfFusion extends GUIApplication { public static void main(String[] args) { try { createAndShowGUI(); String inputFolder = FileHelper.getCurrentPath() + File.separator + Const.INPUT_FOLDER; String outputFolder = FileHelper.getCurrentPath() + File.separator + Const.OUTPUT_FOLDER; String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()); String outputFileName = Const.OUTPUT_FILE_PREFIX + timeStamp + Const.OUTPUT_FILE_SUFFIX; String outputFilePath = outputFolder + File.separator + outputFileName; FileHelper.ensureFolder(inputFolder); FileHelper.ensureFolder(outputFolder); List<InputStream> pdfs = FileHelper.getPdfFilesFromFolder(inputFolder); if (pdfs.size() == 0) { displayWarningPopup("No PDF file to merge. Please put PDF files in the folder:\n" + FileHelper.getWindowsPath(inputFolder)); } else { OutputStream outputPdf = FileHelper.createPdfFile( outputFolder, outputFileName); PdfEngine.concatPDFs(pdfs, outputPdf); displayMessagePopup("The PDF files have been merged successfully. The merge PDF file is available here:\n" + FileHelper.getWindowsPath(outputFilePath)); } } catch (Exception e) { String errorMessage = "An error occurred during the process. Details:\n\n"; System.out.print(errorMessage); e.printStackTrace(); if (frame != null) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); displayErrorPopup(errorMessage + sw.toString()); } } finally { terminateGUI(); } } }
/* * Copyright 2014 Basho Technologies Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.basho.riak.client.core.operations; import com.basho.riak.client.core.FutureOperation; import com.basho.riak.client.core.RiakMessage; import com.basho.riak.protobuf.RiakMessageCodes; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Brian Roach <roach at basho dot com> */ public class PingOperation extends FutureOperation<Void, Void, Void> { private final Logger logger = LoggerFactory.getLogger(PingOperation.class); @Override protected Void convert(List<Void> rawResponse) { return null; } @Override protected RiakMessage createChannelMessage() { return new RiakMessage(RiakMessageCodes.MSG_PingReq, new byte[0]); } @Override protected Void decode(RiakMessage rawMessage) { return null; } @Override public Void getQueryInfo() { return null; } }
package com.esum.web.monitor.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.esum.appetizer.controller.AbstractController; import com.esum.appetizer.exception.ErrorCode; import com.esum.appetizer.vo.RestResult; import com.esum.web.monitor.service.MonCompStatusService; import com.esum.web.monitor.vo.MonCompStatus; @RestController public class MonCompStatusRestController extends AbstractController{ @Autowired private MonCompStatusService monCompStatusService; @RequestMapping("/rest/monitor/comp/getCompIdList") public RestResult getCompIdList(String nodeId){ try { List<String> list = monCompStatusService.getCompIdList(nodeId); Map<String, Object> data = new HashMap<String, Object>(); data.put("list", list); return new RestResult(ErrorCode.SUCCESS, data); } catch (Exception e) { return new RestResult(e); } } @RequestMapping("/rest/monitor/comp/channelData") public RestResult channelData( String searchDate ,String nodeId ,String compId){ try { List<MonCompStatus> list = monCompStatusService.channelData(searchDate, nodeId, compId); Map<String, Object> data = new HashMap<String, Object>(); data.put("list", list); return new RestResult(ErrorCode.SUCCESS, data); } catch (Exception e) { return new RestResult(e); } } @RequestMapping("/rest/monitor/comp/channelData24H") public RestResult channelData24h( String searchDate ,String nodeId ,String compId ,String channelName){ try { List<MonCompStatus> list = monCompStatusService.channelData24h(searchDate, nodeId, compId, channelName); Map<String, Object> data = new HashMap<String, Object>(); data.put("list", list); return new RestResult(ErrorCode.SUCCESS, data); } catch (Exception e) { return new RestResult(e); } } }
package org.xtext.tortoiseshell.lib.view; import com.google.inject.Inject; import org.eclipse.jface.action.Action; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.eclipse.xtext.ui.PluginImageHelper; import org.xtext.tortoiseshell.lib.view.TortoisePartListener; import org.xtext.tortoiseshell.lib.view.TortoiseView; @SuppressWarnings("all") public class ToggleStopModeAction extends Action { @Inject private TortoiseView view; @Inject public ToggleStopModeAction(final PluginImageHelper helper) { super("Toggle stop mode"); Image _image = helper.getImage("stopmode.gif"); ImageDescriptor _createFromImage = ImageDescriptor.createFromImage(_image); this.setImageDescriptor(_createFromImage); this.setChecked(false); } public void run() { TortoisePartListener _tortoisePartListener = this.view.getTortoisePartListener(); boolean _ggleStopMode = _tortoisePartListener.toggleStopMode(); this.setChecked(_ggleStopMode); } }
package world.tile; public class Material { public static final Material GRASS = new Material().setBounds(new boolean[] {true, true, true, true}); public static final Material DIRT = new Material().setBounds(new boolean[] {true, true, true, true}); public static final Material STONE = new Material().setBounds(new boolean[] {true, true, true, true}); boolean climbable=false; boolean transparent = false; boolean translucent = false; int lightingOutput = 0; float opacity = Float.POSITIVE_INFINITY; //how much light is resisted per block. if infinity, no light gets through. boolean[] boundingRules = new boolean[4]; //1: top, 2: right, 3: bottom, 4: left //definition methods public Material(){ } public Material setOpacity(float f){ opacity = f; return this; } public Material setLightingOutput(int l){ lightingOutput = l; return this; } public Material setTransparent(boolean b){ if(b){ return this.setBounds(new boolean[] {false, false, false, false}); }else{ return this; } } public Material setTransLucent(boolean b){ translucent = b; return this; } public Material setClimbable(boolean b){ climbable = b; return this; } public Material setBounds(boolean[] bounds){ if(bounds.length == 4){ boundingRules = bounds; return this; }else{ return null; } } //hook methods public void onCollision(){ } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * ImportView.java * * Created on Nov 25, 2010, 8:49:31 AM */ package josteo.views; import java.text.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import java.io.*; import java.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.commons.io.*; import josteo.infrastructure.UI.*; import josteo.infrastructure.helpers.*; import org.xml.sax.SAXException; /** * * @author cristiano */ public class ImportView extends ViewBase implements josteo.infrastructure.UI.IView { String _choosertitle; String _selectedFolder; java.util.List<String> _files2Import; Map<String, String[]> _tabFiels; /** Creates new form ImportView */ public ImportView() { initComponents(); this.btnSelectFolder.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelectFolderActionPerformed(evt); } }); this.btnImport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnImportActionPerformed(evt); } }); _tabFiels = new HashMap<String, String[]>(); _tabFiels.put("anamnesi_prossima", new String[]{"ID_consulto","prima_volta","tipologia","localizzazione","irradiazione","periodo_insorgenza","durata","familiarita","altre_terapie","varie"}); _tabFiels.put("anamnesi_remota", new String[]{"ID","data","tipo","descrizione"}); _tabFiels.put("consulto", new String[]{"ID","data","problema_iniziale"}); _tabFiels.put("esame", new String[]{"ID","ID_consulto","data","descrizione"}); _tabFiels.put("lkp_anamnesi", new String[]{"ID","descrizione"}); _tabFiels.put("lkp_esame", new String[]{"ID","descrizione"}); _tabFiels.put("lkp_provincia", new String[]{"sigla","descrizione"}); _tabFiels.put("paziente", new String[]{"ID","cognome","nome","data_nascita","professione","indirizzo","citta","telefono","cellulare","prov","cap"}); _tabFiels.put("trattamento", new String[]{"ID","ID_consulto","data","descrizione"}); _tabFiels.put("valutazione", new String[]{"ID","ID_consulto","strutturale","cranio_sacrale","ak_ortodontica"}); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnSelectFolder = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); lstXmlFile = new javax.swing.JList(); btnImport = new javax.swing.JButton(); btnSelectFolder.setText("Select Folder with xml dumps"); lstXmlFile.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane1.setViewportView(lstXmlFile); btnImport.setText("Create Import Script"); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(btnSelectFolder)) .add(layout.createSequentialGroup() .addContainerGap() .add(btnImport)) .add(layout.createSequentialGroup() .addContainerGap() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 452, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap(350, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(btnSelectFolder) .add(18, 18, 18) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 189, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(18, 18, 18) .add(btnImport) .addContainerGap(171, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnImport; private javax.swing.JButton btnSelectFolder; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JList lstXmlFile; // End of variables declaration//GEN-END:variables public void Init(){ this.lstXmlFile.setVisible(false); this.btnImport.setVisible(false); this._files2Import = new ArrayList<String>(); } public void btnSelectFolderActionPerformed(ActionEvent e) { int result; this._files2Import.clear(); JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle(_choosertitle); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // // disable the "All files" option. // chooser.setAcceptAllFileFilterUsed(false); // if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { _selectedFolder = chooser.getSelectedFile().getAbsolutePath(); fillList(); System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); } else { System.out.println("No Selection "); } } public void btnImportActionPerformed(ActionEvent e) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); String msg = ""; try{ msg = "sql import file created successfully at " + createImportFile(); }catch(Exception exc){ ConfigHelper.getInstance().WriteLog(exc); msg = "An error occurred creating import script: \n" + exc.getMessage(); }finally{ JOptionPane.showMessageDialog(this, msg); } this.setCursor(Cursor.getDefaultCursor()); } private String createImportFile() throws java.io.IOException, javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException, java.text.ParseException{ String importFileName = String.format("import_%1$tY-%1$tm-%1$td-%1$tH-%1$tM-%1$tS.sql", Calendar.getInstance()); String importFilePath = FilenameUtils.concat(_selectedFolder, importFileName); PrintWriter pw = new PrintWriter(new FileWriter(importFilePath)); for(String fileName : this._files2Import){ //try { File file = new File(FilenameUtils.concat(_selectedFolder, fileName)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); System.out.println("Root element " + doc.getDocumentElement().getNodeName()); String tabName = FilenameUtils.removeExtension(fileName); NodeList nodeLst = doc.getElementsByTagName(tabName); createInsert(pw, nodeLst, ((String[])this._tabFiels.get(tabName)), tabName); //}catch(Exception exc){ //} } pw.close(); return importFilePath; } public void fillList(){ // Directory path here String path = this._selectedFolder; String files; File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++){ if (listOfFiles[i].isFile()){ files = listOfFiles[i].getName(); if (files.endsWith(".xml") || files.endsWith(".XML")){ System.out.println(files); this._files2Import.add(files); } } } java.util.List<String> missingFiles = new ArrayList<String>(); for(Map.Entry<String,String[]> entry : this._tabFiels.entrySet()){ if(!this._files2Import.contains(entry.getKey()+".xml")){ missingFiles.add(entry.getKey()); } } if(missingFiles.isEmpty()){ showImport(); } else showMissingFiles(missingFiles); } private void showImport(){ this.lstXmlFile.setListData(this._files2Import.toArray()); this.btnImport.setVisible(true); this.lstXmlFile.setVisible(true); } private void showMissingFiles(java.util.List<String> missingFiles){ String msg = "Due missing file(s) import cannot be executed:\n" + StringHelper.join(missingFiles,"\n"); JOptionPane.showMessageDialog(this, msg); } private void createInsert(PrintWriter pw, NodeList nodeLst, String[] fields, String tabName) throws java.text.ParseException{ //String[] fields = new String[]{"ID","cognome","nome","data_nascita","professione","indirizzo","citta","telefono","cellulare","prov","cap"}; Map<String,String> dic; //String s = "INSERT INTO paziente () VALUES ()"; pw.println( String.format("-- %1$s", tabName) ); DateFormat df; for (int s = 0; s < nodeLst.getLength(); s++) { dic = new HashMap<String,String>(); Node fstNode = nodeLst.item(s); String value; if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; for(String field : fields){ NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(field); Element fstNmElmnt = (Element) fstNmElmntLst.item(0); NodeList fstNm = fstNmElmnt.getChildNodes(); if(fstNm.getLength()>0){ value = ((Node) fstNm.item(0)).getNodeValue(); if(field.indexOf("data")>-1){ df = new SimpleDateFormat("yyyy-MM-dd"); value = df.format(df.parse(value)); } }else{ value = ""; } value = String.format("'%1$s'",value.replaceAll("'", "\\\\'")); dic.put(field, value); } pw.println( String.format("INSERT INTO %1$s (%2$s) VALUES (%3$s);", tabName, StringHelper.join(Arrays.asList(fields),","), StringHelper.join(dic.values(),",")) ); } } } }
package com.san.user; import com.san.tokenUserInfo.TokenUserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import javax.persistence.ParameterMode; import javax.persistence.PersistenceContext; import javax.persistence.StoredProcedureQuery; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class UserService implements UserDetailsService { @Autowired private UserRepository userRepository; // @Autowired // private PasswordEncoder passwordEncoder; @PersistenceContext EntityManager entityManager; public List<User> getAll() { List<User> records = new ArrayList<>(); userRepository.findAll().forEach(records::add); return records; } public User getOne(Integer id) { return userRepository.findOne(id); } public boolean add(User user) { // user.setPassword(passwordEncoder.encode(user.getPassword())); // userRepository.save(user); return false; } public boolean update() { return false; } public boolean delete(Integer id) { userRepository.delete(id); return false; } public User getUser(Integer id) { return userRepository.findOne(id); } @Override public UserDetails loadUserByUsername(String identifier) throws UsernameNotFoundException { Optional<User> optionalUser = userRepository.findByEmail(identifier); optionalUser.orElseThrow(() -> new UsernameNotFoundException("UserName Not Found")); return optionalUser.map(CustomUserDetails::new).get(); } public TokenUserInfo getTokenUserInfo(LoginRequest loginRequest, String ip, String agent) { StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("get_token_user_info_sp"); storedProcedureQuery.registerStoredProcedureParameter(1, String.class, ParameterMode.IN); storedProcedureQuery.registerStoredProcedureParameter(2, String.class, ParameterMode.IN); storedProcedureQuery.setParameter(1, loginRequest.getEmailOrUsername()); storedProcedureQuery.setParameter(2, loginRequest.getPassword()); List<Object[]> l = storedProcedureQuery.getResultList(); if (l.size() > 0) { Object[] firstRow = l.get(0); Integer id = (Integer) firstRow[0]; String access_token = (String) firstRow[1]; String language = (String) firstRow[2]; List<String> roles = new ArrayList<>(); for (Object[] result: l) { roles.add((String) result[3]); } return new TokenUserInfo(id, access_token, roles, ip, agent, language); } return null; } }
package com.codingchili.instance.model.spells; import com.codingchili.instance.context.GameContext; import com.codingchili.instance.context.Ticker; import com.codingchili.instance.model.entity.Entity; import com.codingchili.instance.model.items.CollectionFactory; import java.time.Instant; import java.util.*; /** * @author Robin Duda * <p> * Spell state that is stored on creatures, handles cooldowns and spell charges. * <p> * charges - charges can be consumed instead of waiting for a spells cooldown to pass. * cooldown - the amount of milliseconds that needs to pass before a spell can be cast again. * global cooldown - the amount of milliseconds that needs to pass between casting a spell - * this applies even if there are charges available for the given spell. * <p> * Unix epochs are used to set the cooldown and getGcd. It is up to the caller to determine * if the point in time has passed. This is better than using a boolean because the delay of * the network does not affect the cooldown/getGcd state (clients are kept in sync more accurately.) */ public class SpellState { private static final Integer GCD_MS = 250; private Set<String> learned = CollectionFactory.set(); private Map<String, Long> casted = CollectionFactory.map(); private Map<String, Float> charges = CollectionFactory.map(); private Long gcd = 0L; /** * Consumes a charge for the given spell if available - otherwise puts the spell on cooldown. * * @param spell the spell to be put on cooldown. */ public void setCooldown(Spell spell) { long now = Instant.now().toEpochMilli(); long cooldownEndsAt = now + (1000 * spell.getCooldown().longValue()); casted.put(spell.getId(), cooldownEndsAt); gcd = now + GCD_MS; charges.compute(spell.getId(), (id, count) -> (count == null || count == 0) ? 0 : (count -= 1)); } /** * Checks if a spell is on cooldown - a spell is on cooldown if the global cooldown is active, * if there are no charges available and finally if the spell was last put on cooldown within * the configured cooldown for the spell. * * @param spell the spell to check if it is on cooldown. * @return true if the spell is on cooldown and cannot be casted. */ public boolean isOnCooldown(Spell spell) { if (!isOnGCD()) { if (charges(spell) > 0) { // disregard cooldown if there are charges available. return false; } else { // check if the spell is on cooldown or out of charges if the spell is chargeable. Long lastCastCooldownEnds = casted.getOrDefault(spell.getId(), 0L); boolean cooldown = (Instant.now().toEpochMilli() < lastCastCooldownEnds); boolean excharged = spell.getCharges() > 0 && charges(spell) <= 0; return cooldown || excharged; } } else { // global cooldown applies to charges as well. return true; } } /** * @return true if the global cooldown is active. */ public boolean isOnGCD() { return System.currentTimeMillis() < gcd; } /** * @return the epoch in milliseconds of when the last activated global cooldown ends. * this point in time could have already passed. */ public Long getGcd() { return gcd; } /** * Sets the end time for global cooldown, use #{@link #triggerGcd(long)} instead. * * @param end the unix epoch for when gcd ends. */ public void setGcd(Long end) { this.gcd = end; } /** * @param ms the number of milliseconds the GCD is active for. * @return manually invoke gcd. */ public SpellState triggerGcd(long ms) { gcd = System.currentTimeMillis() + ms; return this; } /** * Returns the point in time when the given spells cooldown ended. * * @param spell the spell to get the cooldown for. * @return the epoch in milliseconds when the last cooldown of this spell ended. */ public long cooldown(Spell spell) { return casted.getOrDefault(spell.getId(), 0L); } /** * Check the number of available charges for the given spell. * * @param spell the spell to check how many charges are available. * @return an integer indicating number of charges available. */ public int charges(Spell spell) { charges.putIfAbsent(spell.getId(), 0f); return charges.get(spell.getId()).intValue(); } /** * Processes the current cooldown and generates new charges if enough time has passed. * * @param entity the entity being updated, used for sending updates. * @param spells a reference to the spell database. * @param ticker ticker with delta */ public void tick(Entity entity, SpellDB spells, Ticker ticker) { for (String spellName : learned) { Optional<Spell> lookup = spells.getById(spellName); if (lookup.isPresent()) { Spell spell = lookup.get(); float recharge = GameContext.secondsToMs(spell.getRecharge()); if (spell.getCharges() > 1) { boolean modified = charge(spell, ticker.deltaMS() / recharge); if (modified) { entity.handle(new SpellStateEvent(this, spell)); } } } } } /** * Adds a charge for the given spell - has no effect if the owner of the spell-state * has not learned the spell. * * @param spell the spell to add a charge for. * @param amount the amount of charge being added. * @return true if the amount of usable charges modified. */ public boolean charge(Spell spell, float amount) { if (learned.contains(spell.getId())) { Float charge = charges.getOrDefault(spell.getId(), 0f); Float next = amount + charge; charges.put(spell.getId(), Math.min(next, spell.getCharges())); return (next.intValue() > charge.intValue()); } else { return false; } } /** * @return a set of ID's of the spells that has been learned. */ public Collection<String> getLearned() { return learned; } /** * @return a map of spell id's and the number of available charges. */ public Map<String, Float> getCharges() { return this.charges; } /** * @return a map of spell id's and the unix epoch at which the cooldown expires. */ public Map<String, Long> getCooldowns() { return this.casted; } /** * @param spellSet a set of spells to set as learned. * @return fluent. */ public SpellState setLearned(Set<String> spellSet) { learned = spellSet; return this; } /** * @param spellId the id of the spell to add as a learned spell. * @return fluent. */ public SpellState addLearned(String spellId) { learned.add(spellId); return this; } /** * @param spellId the id of the spell to unlearn. * @return fluent. */ public SpellState setNotLearned(String spellId) { learned.remove(spellId); return this; } /** * @param spellId the id of a spell to check if it has been learned. * @return fluent. */ public boolean learned(String spellId) { return learned.contains(spellId); } }
package Problem_1929; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int M = sc.nextInt(); int N = sc.nextInt(); boolean[] arr = new boolean[1000001]; arr[0] = true; arr[1] = true; for(int i = 2; i<=1000000;i++) { if(arr[i]) continue; for(int j = i*2; j <=1000000;j+=i) { arr[j] = true; } } for(int a = M; a <= N; a++) if(!arr[a]) System.out.println(a); } }
package com.smart.droidies.tamil.natkati.library; import java.util.List; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Typeface; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.smart.droidies.tamil.natkati.R; import com.smart.droidies.tamil.natkati.library.util.Constant; import com.smart.droidies.tamil.natkati.library.util.Festive; import com.smart.droidies.tamil.natkati.library.util.TamizUtil; public class MonthlyFestiveListAdaper extends ArrayAdapter<Festive> { private List<Festive> lstMonthFestive; private Activity context; boolean bTamilView; Typeface fontFaceTamil; SharedPreferences preferences; public MonthlyFestiveListAdaper(Activity pContext, int textViewResourceId, List<Festive> listMonthlyFestive) { super(pContext, textViewResourceId, listMonthlyFestive); context = pContext; lstMonthFestive = listMonthlyFestive; preferences = PreferenceManager.getDefaultSharedPreferences(this.context); bTamilView = preferences.getBoolean(Constant.C_ARG_TAMIL_VIEW, true); fontFaceTamil = Typeface.createFromAsset(this.getContext().getAssets(), Constant.C_TAMIL_FONT_BAMINI); } public static class ViewHolder { public TextView day; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; Festive festive = null; if (convertView == null) { LayoutInflater inflator = context.getLayoutInflater(); view = inflator.inflate(R.layout.auspicious_day, null); final ViewHolder viewHolder = new ViewHolder(); viewHolder.day = (TextView) view.findViewById(R.id.txt_auspicious_day); view.setTag(viewHolder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); festive = lstMonthFestive.get(position); if (bTamilView) { holder.day.setTypeface(fontFaceTamil, Typeface.BOLD); holder.day.setText(TamizUtil.getMonthDay(festive.getFestiveDate()) + " - " + TamizUtil.getStringResourceByName(context, festive.getName())); } else { holder.day.setText(TamizUtil.getMonthDay(festive.getFestiveDate()) + " - " + festive.getName()); } return view; } }
package org.androware.androbeans.beans; import android.util.JsonReader; import java.io.IOException; import java.util.HashMap; import java.util.Stack; import org.androware.androbeans.legacy.InstaBean; import org.androware.androbeans.legacy.JSONinstaBean; import org.androware.androbeans.utils.ConstructorSpec; /** * Created by jkirkley on 5/7/16. */ public class Step extends JSONinstaBean { public static final int MAX_PARAMS = 1024; public String layout; public String processor; public String parentContainer; public String transitionClassName; public String targetFlow; public UI ui; public ConstructorSpec viewCustomizerSpec; private Nav currNav; public HashMap<String, String> meta; public HashMap<String, String> data; public HashMap<String, Nav> navMap; private Stack<Object> paramStack = new Stack<>(); String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void __init__() { l("__init__: has been called !!!!!!!!!!!!!!! --------------------------------"); } public Step() { } public Step(Nav nav) { this.currNav = nav; this.name = nav.target; } public Step(JsonReader reader, Class type, InstaBean parent) throws IOException { super(reader, type, parent); } public Step(JsonReader reader, Class type) throws IOException { super(reader, type); } }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util.xml; import java.io.StringWriter; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.w3c.dom.Node; import org.xmlunit.util.Predicate; import org.springframework.core.testfixture.xml.XmlContent; import static org.assertj.core.api.Assertions.assertThat; class XMLEventStreamWriterTests { private static final String XML = "<?pi content?><root xmlns='namespace'><prefix:child xmlns:prefix='namespace2'><!--comment-->content</prefix:child></root>"; private XMLEventStreamWriter streamWriter; private StringWriter stringWriter; @BeforeEach void createStreamReader() throws Exception { stringWriter = new StringWriter(); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stringWriter); streamWriter = new XMLEventStreamWriter(eventWriter, XMLEventFactory.newInstance()); } @Test void write() throws Exception { streamWriter.writeStartDocument(); streamWriter.writeProcessingInstruction("pi", "content"); streamWriter.writeStartElement("namespace", "root"); streamWriter.writeDefaultNamespace("namespace"); streamWriter.writeStartElement("prefix", "child", "namespace2"); streamWriter.writeNamespace("prefix", "namespace2"); streamWriter.writeComment("comment"); streamWriter.writeCharacters("content"); streamWriter.writeEndElement(); streamWriter.writeEndElement(); streamWriter.writeEndDocument(); Predicate<Node> nodeFilter = n -> n.getNodeType() != Node.DOCUMENT_TYPE_NODE && n.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE; assertThat(XmlContent.from(stringWriter)).isSimilarTo(XML, nodeFilter); } }
package ar.edu.utn.d2s.model.addres; import org.uqbar.geodds.Point; public class Address { private String mainStreet; private String street1; private String street2; private int streetNumber; private byte floor; private byte apartment; private byte unit; private int postalCode; private String city; private String district; private String state; private String country; private Point point; public Address(String mainStreet, String street1, String street2, int streetNumber, byte floor, byte apartment, byte unit, int postalCode, String city, String district, String state, String country, Point point) { this.mainStreet = mainStreet; this.street1 = street1; this.street2 = street2; this.streetNumber = streetNumber; this.floor = floor; this.apartment = apartment; this.unit = unit; this.postalCode = postalCode; this.city = city; this.district = district; this.state = state; this.country = country; this.point = point; } public String getMainStreet() { if (mainStreet == null) { mainStreet = ""; } return mainStreet; } public void setMainStreet(String mainStreet) { this.mainStreet = mainStreet; } public String getStreet1() { if (street1 == null) { street1 = ""; } return street1; } public void setStreet1(String street1) { this.street1 = street1; } public String getStreet2() { if (street2 == null) { street2 = ""; } return street2; } public void setStreet2(String street2) { this.street2 = street2; } public int getStreetNumber() { return streetNumber; } public void setStreetNumber(int streetNumber) { this.streetNumber = streetNumber; } public byte getFloor() { return floor; } public void setFloor(byte floor) { this.floor = floor; } public byte getApartment() { return apartment; } public void setApartment(byte apartment) { this.apartment = apartment; } public byte getUnit() { return unit; } public void setUnit(byte unit) { this.unit = unit; } public int getPostalCode() { return postalCode; } public void setPostalCode(int postalCode) { this.postalCode = postalCode; } public String getCity() { if (city == null) { city = ""; } return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { if (district == null) { district = ""; } return district; } public void setDistrict(String district) { this.district = district; } public String getState() { if (state == null) { state = ""; } return state; } public void setState(String state) { this.state = state; } public String getCountry() { if (country == null) { country = ""; } return country; } public void setCountry(String country) { this.country = country; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } }