repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/chain/web/DownloadSmtTrackingListController.java
9538
package com.swfarm.biz.chain.web; import java.io.OutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.PrintSetup; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import com.swfarm.biz.chain.bo.CustomerOrder; import com.swfarm.biz.chain.bo.SaleChannelAccount; import com.swfarm.biz.chain.srv.ChainService; import com.swfarm.biz.warehouse.bo.AllocationProductVoucher; import com.swfarm.biz.warehouse.bo.AllocationProductVoucherList; import com.swfarm.biz.warehouse.srv.WarehouseService; import com.swfarm.pub.utils.ImageUtils; public class DownloadSmtTrackingListController extends AbstractController { private static final String[] titles = { "订单编号", "发货单号", "平台单号", "货运单号", "店铺编号" }; private static final double MAGIC_FACTOR = 1.112877583; private WarehouseService warehouseService; private ChainService chainService; public void setWarehouseService(WarehouseService warehouseService) { this.warehouseService = warehouseService; } public void setChainService(ChainService chainService) { this.chainService = chainService; } @Override protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse res) throws Exception { Long apvlId = new Long(req.getParameter("apvl")); AllocationProductVoucherList allocationProductVoucherList = this.warehouseService .findAllocationProductVoucherList(apvlId); HSSFWorkbook wb = new HSSFWorkbook(); Map<String, CellStyle> styles = createStyles(wb); HSSFSheet sheet = wb.createSheet("客户订单"); sheet.setFitToPage(true); sheet.setHorizontallyCenter(true); PrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(false); sheet.setAutobreaks(true); printSetup.setFitHeight((short) 1); printSetup.setFitWidth((short) 1); HSSFRow headerRow = sheet.createRow(0); headerRow.setHeightInPoints(12.75f); for (int i = 0; i < titles.length; i++) { HSSFCell cell = headerRow.createCell(i); cell.setCellValue(titles[i]); cell.setCellStyle(styles.get("header")); } HSSFRow row = null; HSSFCell cell = null; for (int i = 0; i < 4; i++) { sheet.setColumnWidth(i, (int) (15 * 256 * MAGIC_FACTOR)); } int rowCounter = 1; for (Iterator iter = allocationProductVoucherList .getAllocationProductVoucherList().iterator(); iter.hasNext();) { AllocationProductVoucher apv = (AllocationProductVoucher) iter .next(); CustomerOrder customerOrder = apv.getCustomerOrder(); String sfmCode = apv.getShippingForwarderMethod(); String[] ywPySfmCodes = new String[] { "YUB", "YWCNPY", "BJGH", "BKGH" }; row = sheet.createRow(rowCounter); int cellCounter = 0; // A cell = row.createCell(cellCounter++); cell.setCellValue(customerOrder.getCustomerOrderNo()); cell.setCellStyle(styles.get("cell_normal")); // B cell = row.createCell(cellCounter++); cell.setCellValue(apv.getAllocationProductVoucherNo()); cell.setCellStyle(styles.get("cell_normal")); // C cell = row.createCell(cellCounter++); cell.setCellValue(customerOrder.getSaleChannelOrderId()); cell.setCellStyle(styles.get("cell_normal")); // D cell = row.createCell(cellCounter++); if (ArrayUtils.contains(ywPySfmCodes, sfmCode)) { cell.setCellValue(apv.getRefShippingOrderNo()); } else { cell.setCellValue(apv.getShippingOrderNo()); } cell.setCellStyle(styles.get("cell_normal")); // E cell = row.createCell(cellCounter++); String accountNumber = customerOrder.getAccountNumber(); if (StringUtils.isNotEmpty(accountNumber)) { SaleChannelAccount saleChannelAccount = this.chainService .findSaleChannelAccountByAccountNumber(accountNumber); cell.setCellValue(saleChannelAccount.getAccountNumberSeq()); } cell.setCellStyle(styles.get("cell_normal")); rowCounter++; } res.setContentType("application/ms-excel"); String fileName = "客户订单.xls"; res.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); OutputStream out = res.getOutputStream(); wb.write(out); return null; } private static Map<String, CellStyle> createStyles(HSSFWorkbook wb) { Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); DataFormat df = wb.createDataFormat(); CellStyle style; Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); headerFont.setFontHeightInPoints((short) 10); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(headerFont); styles.put("header", style); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(headerFont); style.setDataFormat(df.getFormat("d-mmm")); styles.put("header_date", style); Font font1 = wb.createFont(); font1.setBoldweight(Font.BOLDWEIGHT_BOLD); font1.setFontHeightInPoints((short) 10); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_LEFT); style.setFont(font1); styles.put("cell_b", style); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_CENTER); style.setFont(font1); styles.put("cell_b_centered", style); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setFont(font1); style.setDataFormat(df.getFormat("d-mmm")); styles.put("cell_b_date", style); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setFont(font1); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setDataFormat(df.getFormat("d-mmm")); styles.put("cell_g", style); Font font2 = wb.createFont(); font2.setColor(IndexedColors.BLUE.getIndex()); font2.setBoldweight(Font.BOLDWEIGHT_BOLD); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_LEFT); style.setFont(font2); styles.put("cell_bb", style); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setFont(font1); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setDataFormat(df.getFormat("d-mmm")); styles.put("cell_bg", style); Font font3 = wb.createFont(); font3.setFontHeightInPoints((short) 10); font3.setColor(IndexedColors.DARK_BLUE.getIndex()); font3.setBoldweight(Font.BOLDWEIGHT_BOLD); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_LEFT); style.setFont(font3); style.setWrapText(true); styles.put("cell_h", style); Font normalFont = wb.createFont(); normalFont.setFontHeightInPoints((short) 10); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_LEFT); style.setWrapText(true); style.setFont(normalFont); styles.put("cell_normal", style); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_CENTER); style.setWrapText(true); styles.put("cell_normal_centered", style); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_RIGHT); style.setWrapText(true); style.setDataFormat(df.getFormat("d-mmm")); styles.put("cell_normal_date", style); style = createBorderedStyle(wb); style.setAlignment(CellStyle.ALIGN_LEFT); style.setIndention((short) 1); style.setWrapText(true); styles.put("cell_indented", style); style = createBorderedStyle(wb); style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); styles.put("cell_blue", style); return styles; } private static CellStyle createBorderedStyle(HSSFWorkbook wb) { CellStyle style = wb.createCellStyle(); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); return style; } private static byte[] getImage(String url) { return ImageUtils.generateImage(url); } }
mit
bhatti/PlexServices
plexsvc-framework/src/main/java/com/plexobject/service/impl/InterceptorLifecycleImpl.java
6829
package com.plexobject.service.impl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.plexobject.handler.BasePayload; import com.plexobject.handler.Request; import com.plexobject.handler.Response; import com.plexobject.service.AroundInterceptor; import com.plexobject.service.Interceptor; import com.plexobject.service.InterceptorsLifecycle; public class InterceptorLifecycleImpl implements InterceptorsLifecycle { private final List<Interceptor<Request>> requestInterceptors = new ArrayList<>(); private final List<Interceptor<Response>> responseInterceptors = new ArrayList<>(); private final List<Interceptor<BasePayload<Object>>> inputInterceptors = new ArrayList<>(); private final List<Interceptor<BasePayload<Object>>> outputInterceptors = new ArrayList<>(); private AroundInterceptor aroundInterceptor; private boolean hasRequestInterceptors; private boolean hasResponseInterceptors; private boolean hasInputInterceptors; private boolean hasOutputInterceptors; /** * This method adds interceptor, which is invoked before passing request is * passed to handler * * @param interceptor */ @Override public synchronized void addRequestInterceptor( Interceptor<Request> interceptor) { if (!requestInterceptors.contains(interceptor)) { requestInterceptors.add(interceptor); } hasRequestInterceptors = requestInterceptors.size() > 0; } /** * This method removes interceptor, which is invoked before passing request * is passed to handler * * @param interceptor */ @Override public synchronized boolean removeRequestInterceptor( Interceptor<Request> interceptor) { int ndx = requestInterceptors.indexOf(interceptor); if (ndx != -1) { requestInterceptors.remove(ndx); } hasRequestInterceptors = requestInterceptors.size() > 0; return ndx != -1; } /** * This method returns request interceptors, which is invoked before passing * request is passed to handler * * @return */ @Override public synchronized Collection<Interceptor<Request>> getRequestInterceptors() { return requestInterceptors; } /** * This method adds interceptor, which allows overriding response object set * by handler. * * @param interceptor */ @Override public synchronized void addResponseInterceptor( Interceptor<Response> interceptor) { if (!responseInterceptors.contains(interceptor)) { responseInterceptors.add(interceptor); } hasResponseInterceptors = responseInterceptors.size() > 0; } /** * This method removes interceptor, which allows overriding response object * set by handler. * * @param interceptor */ @Override public synchronized boolean removeResponseInterceptor( Interceptor<Response> interceptor) { int ndx = responseInterceptors.indexOf(interceptor); if (ndx != -1) { responseInterceptors.remove(ndx); } hasResponseInterceptors = responseInterceptors.size() > 0; return ndx != -1; } /** * This method returns response interceptors, which allows overriding * response object set by handler. * * @return */ @Override public synchronized Collection<Interceptor<Response>> getResponseInterceptors() { return responseInterceptors; } /** * This method adds interceptor for raw JSON/XML input before it's decoded * into object * * @param interceptor */ @Override public synchronized void addInputInterceptor( Interceptor<BasePayload<Object>> interceptor) { if (!inputInterceptors.contains(interceptor)) { inputInterceptors.add(interceptor); } hasInputInterceptors = inputInterceptors.size() > 0; } /** * This method remove interceptor for raw JSON/XML input before it's decoded * into object * * @param interceptor */ @Override public synchronized boolean removeInputInterceptor( Interceptor<BasePayload<Object>> interceptor) { int ndx = inputInterceptors.indexOf(interceptor); if (ndx != -1) { inputInterceptors.remove(ndx); } hasInputInterceptors = inputInterceptors.size() > 0; return ndx != -1; } /** * This method returns interceptors for raw JSON/XML input before it's * decoded into object * * @return */ @Override public synchronized Collection<Interceptor<BasePayload<Object>>> getInputInterceptors() { return inputInterceptors; } /** * This method adds interceptor for raw JSON/XML output before it's send to * client * * @param interceptor */ @Override public synchronized void addOutputInterceptor( Interceptor<BasePayload<Object>> interceptor) { if (!outputInterceptors.contains(interceptor)) { outputInterceptors.add(interceptor); } hasOutputInterceptors = outputInterceptors.size() > 0; } /** * This method remove interceptor for raw JSON/XML output before it's send * to client * * @param interceptor */ @Override public synchronized boolean removeOutputInterceptor( Interceptor<BasePayload<Object>> interceptor) { int ndx = outputInterceptors.indexOf(interceptor); if (ndx != -1) { outputInterceptors.remove(ndx); } hasOutputInterceptors = outputInterceptors.size() > 0; return ndx != -1; } /** * This method returns interceptors for raw JSON/XML output before it's send * to client * * @return */ @Override public synchronized Collection<Interceptor<BasePayload<Object>>> getOutputInterceptors() { return outputInterceptors; } @Override public synchronized boolean hasInputInterceptors() { return hasInputInterceptors; } @Override public synchronized boolean hasRequestInterceptors() { return hasRequestInterceptors; } @Override public synchronized boolean hasOutputInterceptors() { return hasOutputInterceptors; } @Override public synchronized boolean hasResponseInterceptors() { return hasResponseInterceptors; } @Override public void setAroundInterceptor(AroundInterceptor interceptor) { this.aroundInterceptor = interceptor; } @Override public AroundInterceptor getAroundInterceptor() { return aroundInterceptor; } }
mit
pshynin/JavaRushTasks
1.JavaSyntax/src/com/javarush/task/task04/task0423/Solution.java
496
package com.javarush.task.task04.task0423; /* Фейс-контроль */ import java.io.*; import java.util.Scanner; public class Solution { public static void main(String[] args) throws Exception { //напишите тут ваш код Scanner scanner = new Scanner(System.in); String name = scanner.nextLine(); int age = scanner.nextInt(); if (age > 20) { System.out.println("И 18-ти достаточно"); } } }
mit
B2MSolutions/reyna
reyna-test/src/test/Assert.java
1028
package test; import android.content.Intent; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.robolectric.Shadows.shadowOf; public class Assert { public static Intent assertServiceStarted(java.lang.Class<?> expected) { Intent intent = shadowOf(org.robolectric.RuntimeEnvironment.application).getNextStartedService(); assertNotNull(intent); org.robolectric.shadows.ShadowIntent shadowIntent = shadowOf(intent); assertEquals(expected, shadowIntent.getIntentClass()); return intent; } public static void assertServiceNotStarted(java.lang.Class<?> expected) { Intent intent = shadowOf(org.robolectric.RuntimeEnvironment.application).getNextStartedService(); if(intent != null) { org.robolectric.shadows.ShadowIntent shadowIntent = shadowOf(intent); assertNotSame(expected, shadowIntent.getIntentClass()); } } }
mit
mbarbie1/SliceMap
src/main/be/ua/mbarbier/slicemap/Manual_Annotation_Curation.java
35671
/* * The MIT License * * Copyright 2017 mbarbier. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package main.be.ua.mbarbier.slicemap; import fiji.util.gui.GenericDialogPlus; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.plugin.PlugIn; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyListener; import java.io.File; import ij.plugin.frame.RoiManager; import ij.gui.ImageCanvas; import ij.gui.MessageDialog; import ij.gui.Overlay; import ij.gui.PolygonRoi; import ij.gui.Roi; import ij.gui.TextRoi; import ij.gui.Toolbar; import ij.process.FloatPolygon; import java.awt.Button; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Panel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.file.Files; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import static main.be.ua.mbarbier.slicemap.lib.LibIO.findFiles; import main.be.ua.mbarbier.slicemap.lib.congealing.Congealing; import main.be.ua.mbarbier.slicemap.lib.roi.LibRoi; import static main.be.ua.mbarbier.slicemap.lib.roi.LibRoi.minusRoi; import static main.be.ua.mbarbier.slicemap.lib.roi.LibRoi.saveRoiAlternative; import net.lingala.zip4j.exception.ZipException; /** * * @author mbarbier */ public class Manual_Annotation_Curation implements PlugIn { public static final String METHOD_KEY = "key"; public static final String METHOD_BUTTON = "button"; public final String METHOD_ANNOTATION = "button"; public boolean DEBUG = false; LinkedHashMap< String, Integer > sig = new LinkedHashMap<>(); ArrayList< String > roiNameList; public void setRoiNameList(ArrayList<String> roiNameList) { this.roiNameList = roiNameList; } /** * The Tap class implements the interaction with the user interface with * keys where the ROI names are presented one by one and the user uses "g" * to go to the next region name and "z" to save all roi of the slice. */ public class Tap extends KeyAdapter { RoiManager rm; ImagePlus imp; ArrayList< String > roiNameList; String outputPath; public Tap( RoiManager rm, ImagePlus imp, ArrayList< String > roiNameList, String outputPath ) { this.rm = rm; this.imp = imp; this.roiNameList = roiNameList; this.outputPath = outputPath; } public void keyPressed( KeyEvent event ) { int keyCode = event.getKeyCode(); if (KeyEvent.VK_G == keyCode) { if ( this.roiNameList.size() < this.rm.getCount()+1 ) { IJ.log("All ROIs are already defined, it not possible to create new ones"); event.consume(); // AVOID propagation to other key listeners return; } this.rm.addRoi( this.imp.getRoi() ); int roiIndex = this.rm.getCount()-1; this.rm.select(roiIndex); String roiName = this.roiNameList.get(roiIndex); this.rm.runCommand("Rename", roiName); this.rm.runCommand("Show All"); IJ.log("ROI added: " + roiName); if ( this.roiNameList.size() > roiIndex+1 ) { String roiNameNext = this.roiNameList.get(roiIndex+1); imageMessage(this.imp, "Next ROI = " + roiNameNext, 2); } else { IJ.log("All ROIs defined!"); imageMessage(this.imp, "All ROIs defined!", 2); } event.consume(); // AVOID propagation to other key listeners } if (KeyEvent.VK_Z == keyCode) { IJ.log("Saving to " + this.outputPath); this.rm.runCommand("Save", this.outputPath); this.imp.close(); this.rm.close(); event.consume(); // AVOID propagation to other key listeners } } } public class ChoiceList2 extends Panel implements ActionListener { public final String OVERLAY_NEW = "New regions"; public final String OVERLAY_CURRENT = "Current regions"; public final String OVERLAY_OLD = "Old regions"; String title; LinkedHashMap< String, String > roiNameMap; ArrayList<String> roiNameList; LinkedHashMap< String, Button > roiButtonMap; LinkedHashMap< String, Roi > roiMap; LinkedHashMap< String, Roi > roiMapNew; LinkedHashMap< String, Roi > roiMapOld; LinkedHashMap< String, Boolean > roiActive; Overlay overlayOld; Overlay overlayCurrent; Overlay overlayNew; Overlay overlaySlice; String overlayType = ""; String selectedRoi = null; Roi editRoi = null; Roi overlaySelection = null; //Roi textMessage = null; Roi overlayTypeText = null; //TextField overlayTypeTextField; ImagePlus imp = null; File outputRoiFolder = null; boolean roiInterpolation; double interpolationSmoothDistance; boolean overlayVisible; double defaultRoiThickness; double selectedRoiThickness; Color buttonDefaultForeGroundColor; String outputNamePrefix = ""; File outputFile; File outputRoiFile; Panel regionPanel; Panel controlPanel; Panel viewPanel; public ChoiceList2(ImagePlus imp, boolean useRois, LinkedHashMap<String, Roi> roiMapInput, ArrayList< String > roiNameList, File outputFile, File outputRoiFile, LinkedHashMap< String, Integer > sig ) { super(); sig.put("isReady", 0); this.outputFile = outputFile; this.outputRoiFile = outputRoiFile; this.roiNameList = roiNameList;//new ArrayList<>(); this.roiNameMap = new LinkedHashMap<>(); for ( String roiName : roiNameList ) { this.roiNameMap.put( roiName, roiName ); } this.imp = imp; this.setVisible(false); this.title = imp.getTitle(); this.roiMap = new LinkedHashMap<>(); this.roiMapNew = new LinkedHashMap<>(); this.roiMapOld = new LinkedHashMap<>(); this.roiButtonMap = new LinkedHashMap(); this.roiActive = new LinkedHashMap(); this.roiInterpolation = false; this.interpolationSmoothDistance = Math.ceil( 0.01 * imp.getWidth() ); this.outputNamePrefix = ""; this.overlayVisible = true; this.defaultRoiThickness = 2; this.selectedRoiThickness = this.defaultRoiThickness * 3; this.overlayOld = new Overlay();//this.imp.getOverlay().duplicate(); if (useRois) { if ( roiMapInput != null ) { this.roiMap.putAll( roiMapInput ); for ( String key : roiMap.keySet() ) { overlayOld.add( roiMap.get(key), key ); } } } this.overlayCurrent = this.overlayOld.duplicate(); this.imp.setOverlay(overlayCurrent); this.overlaySelection = null; this.overlayNew = new Overlay(); this.overlayType = this.OVERLAY_CURRENT; //this.overlayTypeTextField = new TextField( this.overlayType ); //this.overlayTypeTextField.setEditable(false); this.regionPanel = new Panel(); this.controlPanel = new Panel(); this.viewPanel = new Panel(); int nButtons = this.roiNameMap.keySet().size(); int nViewButtons = 1; int nControlButtons = 2; this.regionPanel.setLayout( new GridLayout( nButtons, 1 ) ); this.viewPanel = new Panel( new GridLayout( nViewButtons, 1 ) ); this.controlPanel = new Panel( new GridLayout( nControlButtons, 1 ) ); Button buttonSaveAndNext = new Button( "Save & Next" ); buttonSaveAndNext.addActionListener(this); this.controlPanel.add( buttonSaveAndNext ); Button buttonApply = new Button( "Confirm region" ); buttonApply.addActionListener(this); this.viewPanel.add( buttonApply ); Button buttonRedo = new Button( "Re-annotate" ); buttonRedo.addActionListener(this); //this.controlPanel.add( buttonRedo ); Button buttonRemoveOverlap = new Button( "Remove overlap" ); buttonRemoveOverlap.addActionListener(this); //this.viewPanel.add( buttonRemoveOverlap ); Button buttonToggleOverlay = new Button( "Toggle overlay" ); buttonToggleOverlay.addActionListener(this); //this.viewPanel.add( buttonToggleOverlay ); Button buttonTypeOverlay = new Button( "Overlay type" ); buttonTypeOverlay.addActionListener(this); //this.viewPanel.add( buttonTypeOverlay ); // // Add the label for the current overlay type shown //this.viewPanel.add( this.overlayTypeTextField ); for ( String roiKey : this.roiNameMap.keySet() ) { Button button = new Button( this.roiNameMap.get(roiKey) ); Color roiColor = Main.getDefaultColorMap().get( roiKey ); button.setBackground( roiColor ); button.addActionListener(this); this.roiButtonMap.put( roiKey, button ); this.regionPanel.add( button ); this.roiActive.put( roiKey, false ); } this.setLayout( new GridLayout(1, 3, 5, 5) ); this.add(this.regionPanel); this.add(this.viewPanel); this.viewPanel.validate(); this.add(this.controlPanel); this.controlPanel.validate(); Dimension panelDims = this.getPreferredSize(); //this.setPreferredSize( new Dimension( imp.getWindow().getWidth(), (int) Math.round( panelDims.getHeight() ) ) ); // Remove any overlap between the ROIs (should be actually already tackled in SliceMap) //roiRemoveOverlap( this.roiMap ); this.setVisible(true); this.validate(); //imp.getWindow().setLayout( new GridLayout() ); imp.getWindow().add(this); //imp.getWindow().add(this); imp.getWindow().pack(); this.validate(); this.buttonDefaultForeGroundColor = buttonSaveAndNext.getForeground(); } @Override public void actionPerformed(ActionEvent e) { String label = e.getActionCommand(); //IJ.log("Action performed with label: " + label ); if (label==null) return; String command = label; redrawOverlayCurrent(); switch( command ) { case "Log ROIs": logRoiMap(); logRoiOverlay(); logRoiOverlayNew(); break; case "Save & Next": LinkedHashMap< String, Roi > tempRoiMap = this.roiMap; if ( tempRoiMap.size() > 0 ) { saveRoiAlternative( this.outputRoiFile, tempRoiMap ); sig.put("noFinalRois", 0); } else { sig.put("noFinalRois", 1); } this.imp.close(); sig.put("isReady", 1); break; case "Re-annotate": redoRois(); IJ.setTool(Toolbar.FREEROI); break; case "Toggle overlay": imp.setHideOverlay(!imp.getHideOverlay()); break; case "Overlay type": switch( this.overlayType ) { case OVERLAY_CURRENT: this.overlayType = this.OVERLAY_NEW; imp.setOverlay(this.overlayNew); break; case OVERLAY_NEW: this.overlayType = this.OVERLAY_OLD; imp.setOverlay(this.overlayOld); break; case OVERLAY_OLD: this.overlayType = this.OVERLAY_CURRENT; imp.setOverlay(this.overlayCurrent); break; default: break; } //this.overlayTypeTextField.setText(this.overlayType); break; case "Remove overlap": removeOverlap(); break; case "Confirm region": doneRoi( this.selectedRoi ); break; default: //String[] roiNames = this.roiNameList.toArray(new String[]{""}); for ( String roiName : this.roiNameMap.keySet() ) { if ( command.equals( roiName ) ) { //if ( this.imp.getRoi() != null && !this.selectedRoi.equals(roiName) ) { // this.overlayCurrent.add( this.imp.getRoi() ); //} //if ( roiActive.get(roiName) ) { // doneRoi( roiName ); //} else { selectNewRoi( roiName ); //} } } break; } } public void removeOverlap() { roiRemoveOverlap( this.roiMap ); } public void deactivateAllRois() { for ( String key : this.roiButtonMap.keySet() ) { Button button = this.roiButtonMap.get(key); Font font = button.getFont(); button.setFont(font.deriveFont(Font.PLAIN)); //button.setForeground( this.buttonDefaultForeGroundColor ); // TODO roiActive to true instead of false? roiActive.put( key, false); } } public void logRoiMap() { IJ.log( "logRoiMap: size = " + this.roiMap.size() ); for ( String key : this.roiMap.keySet() ) { //IJ.log( key + " position: " + this.roiMap.get(key).getPosition() + " , " + this.roiMap.get(key).getProperties() ); IJ.log( key + " position: " + this.roiMap.get(key) ); } } public void logRoiOverlay() { IJ.log( "logRoiOverlay: size = " + this.overlayCurrent.size() ); for ( Roi roi : this.overlayCurrent.toArray() ) { IJ.log( roi.getName() + " position: " + roi.getPosition() ); } } public void logRoiOverlayNew() { IJ.log( "logRoiOverlayNew: size = " + this.overlayNew.size() ); for ( Roi roi : this.overlayNew.toArray() ) { IJ.log( roi.getName() + " position: " + roi.getPosition() ); } } public void redrawOverlayCurrent() { //this.overlayCurrent.clear(); //removeOverlap(); for ( Roi roi : this.overlayCurrent.toArray() ) { this.overlayCurrent.remove(roi); } for ( String key : this.roiMap.keySet() ) { this.overlayCurrent.add(this.roiMap.get(key), key); } } public void selectNewRoi( String roiName ) { IJ.setTool(Toolbar.FREEROI); redrawOverlayCurrent(); this.overlayCurrent.remove( this.roiMap.get(roiName) ); this.overlaySelection = this.roiMap.get(roiName); this.selectedRoi = roiName; deactivateAllRois(); Font font = this.roiButtonMap.get(roiName).getFont(); this.roiButtonMap.get(roiName).setFont( font.deriveFont( Font.BOLD ) ); roiActive.put( roiName, true ); Roi oldRoi = this.roiMap.get(roiName); if ( oldRoi != null ) { oldRoi.setStrokeWidth( this.selectedRoiThickness ); this.imp.setRoi( oldRoi ); } } public void doneRoi( String roiName ) { this.selectedRoi = roiName; this.overlayCurrent.remove( this.roiMap.get(roiName) ); this.overlayNew.remove( this.roiMap.get(roiName) ); this.editRoi = this.imp.getRoi(); if (this.editRoi != null) { if (roiInterpolation) { FloatPolygon fp = this.editRoi.getInterpolatedPolygon(this.interpolationSmoothDistance, false); this.editRoi = new PolygonRoi(fp, Roi.POLYGON); } this.editRoi.setStrokeWidth( this.defaultRoiThickness ); Color roiColor = Main.getDefaultColorMap().get( roiName ); this.editRoi.setStrokeColor( roiColor ); } this.roiMap.put(roiName, this.editRoi); this.overlayNew.add(this.editRoi); this.overlayCurrent.add(this.editRoi); this.imp.deleteRoi(); this.imp.updateImage(); if (this.editRoi != null) { roiMap.put(this.selectedRoi, this.editRoi); } else { roiMap.remove(this.selectedRoi); } removeOverlap(); } public void redoRois() { //String[] roiNames = roiNameList.toArray(new String[]{""}); for (String roiName : roiNameList) { this.roiActive.put( roiName, true ); Font font = this.roiButtonMap.get(roiName).getFont(); this.roiButtonMap.get(roiName).setFont( font.deriveFont( Font.BOLD ) ); this.overlayCurrent.remove( this.roiMap.get(roiName) ); } removeRoiFromOverlay( this.overlayNew ); } /** * * @param overlay * @param roiName * @param roiPosition */ public void removeRoiFromOverlay( Overlay overlay, String roiName ) { for (Roi roi : overlay.toArray()) { if ( roiName.equals( roi.getName() ) ) { overlay.remove( roi ); } } } /** * Remove all ROIs from a certain slice-position * * @param overlay * @param roiPosition */ public void removeRoiFromOverlay( Overlay overlay ) { for (Roi roi : overlay.toArray()) { overlay.remove( roi ); } } /** * Return the ROI from an overlay with a given roi name * * @param overlay * @param roiName */ public Roi getRoiFromOverlay( Overlay overlay, String roiName ) { for (Roi roi : overlay.toArray()) { if ( roiName.equals( roi.getName() ) ) { return roi ; } } return null; } public void roiRemoveOverlap( LinkedHashMap< String, Roi > roiMap ) { String[] keyset = roiMap.keySet().toArray( new String[]{""} ); for ( String key1 : keyset ) { Roi roi1 = roiMap.get(key1); if ( roi1 != null ) { for ( String key2 : keyset ) { Roi roi2 = roiMap.get(key2); if ( roi2 != null ) { if ( !key1.equals(key2) ) { Color sc = roi2.getStrokeColor(); float sw = roi2.getStrokeWidth(); Roi[] rois2 = minusRoi( roi2, roi1).getRois(); if ( rois2.length > 0 ) { roi2 = rois2[0]; roi2.setName(key2); roi2.setStrokeColor(sc); roi2.setStrokeWidth(sw); roiMap.put(key2, roi2); } else { roiMap.remove(key2); } } } } } } for ( String key : keyset ) { // If the roi exists in the roiMap exchange it for the cropped one in the "current regions" overlay if ( this.roiMap.get(key) != null ) { removeRoiFromOverlay( this.overlayCurrent, key ); Roi roi = this.roiMap.get(key); // The position is already set? this.overlayCurrent.add( roi ); // If roi was in new overlay exchange it for the cropped one in the "new regions" overlay if ( getRoiFromOverlay( this.overlayNew, key ) != null ) { removeRoiFromOverlay( this.overlayNew, key ); roi = this.roiMap.get(key); this.overlayNew.add( roi ); } } } this.imp.deleteRoi(); //this.imp.updateImage(); this.imp.repaintWindow(); } } /** * The ChoiceList class implements the user interface where the user has to * use the buttons at the bottom of the image with the ROI names and next * button. */ public class ChoiceList extends Panel implements ActionListener { LinkedHashMap< String, String > roiNameMap; ArrayList< String > roiNameList; LinkedHashMap< String, Button > roiButtonMap; LinkedHashMap< String, Roi > roiMap; Overlay overlayCurrent; String selectedRoi = null; Roi editRoi = null; ImagePlus imp = null; File outputFile; boolean roiInterpolation; double interpolationSmoothDistance; boolean overlayVisible; double defaultRoiThickness; double selectedRoiThickness; Panel regionPanel; Panel controlPanel; Panel viewPanel; public ChoiceList( ImagePlus imp, boolean useRois, LinkedHashMap<String, Roi> roiMapInput, ArrayList< String > roiNameList, String outputPath ) { super(); this.imp = imp; this.outputFile = new File(outputPath); this.setVisible(false); this.roiMap = new LinkedHashMap<>(); this.roiNameList = roiNameList; this.roiNameMap = new LinkedHashMap<>(); for ( String roiName : roiNameList ) { this.roiNameMap.put( roiName, roiName ); } this.roiButtonMap = new LinkedHashMap(); this.roiInterpolation = false; this.interpolationSmoothDistance = Math.ceil( 0.01 * imp.getWidth() ); this.overlayVisible = true; this.defaultRoiThickness = 2; this.selectedRoiThickness = this.defaultRoiThickness * 3; this.overlayCurrent = new Overlay(); // if there are previously defined ROIs if (useRois) { if ( roiMapInput != null ) { this.roiMap.putAll( roiMapInput ); for ( String key : this.roiMap.keySet() ) { this.overlayCurrent.add( this.roiMap.get(key) ); } } } this.imp.setOverlay(overlayCurrent); this.regionPanel = new Panel(); this.controlPanel = new Panel(); this.viewPanel = new Panel(); int nButtons = this.roiNameList.size(); int nViewButtons = 2; int nControlButtons = 1; int maxButtons = 6; int nButtonCols = (int) Math.ceil( ( (double) nButtons ) / ( (double) maxButtons ) ); int nButtonRows = (int) Math.floor( ( (double) nButtons ) / ( (double) nButtonCols ) ); this.regionPanel.setLayout( new GridLayout( nButtonRows, nButtonCols ) ); this.viewPanel = new Panel( new GridLayout( nViewButtons, 1 ) ); this.controlPanel = new Panel( new GridLayout( nControlButtons, 1 ) ); Button buttonSave = new Button( "Save & Next" ); buttonSave.addActionListener(this); this.controlPanel.add( buttonSave ); Button buttonRemoveOverlap = new Button( "Remove overlap" ); buttonRemoveOverlap.addActionListener(this); this.viewPanel.add( buttonRemoveOverlap ); Button buttonToggleOverlay = new Button( "Toggle overlay" ); buttonToggleOverlay.addActionListener(this); this.viewPanel.add( buttonToggleOverlay ); for ( String roiKey : this.roiNameMap.keySet() ) { Button button = new Button( this.roiNameMap.get(roiKey) ); Color roiColor = Main.getDefaultColorMap().get( roiKey ); button.setBackground( roiColor ); button.addActionListener(this); //this.roiActive.put( roiKey, false ); this.roiButtonMap.put( roiKey, button ); this.regionPanel.add( button ); } this.setLayout( new GridLayout(1, 3, 5, 5) ); this.add(this.regionPanel); this.add(this.viewPanel); this.viewPanel.validate(); this.add(this.controlPanel); this.controlPanel.validate(); Dimension panelDims = this.getPreferredSize(); //this.setPreferredSize( new Dimension( imp.getWindow().getWidth(), (int) Math.round( panelDims.getHeight() ) ) ); this.setVisible(true); this.validate(); imp.getWindow().add(this); imp.getWindow().pack(); this.validate(); } @Override public void actionPerformed(ActionEvent e) { String label = e.getActionCommand(); //IJ.log("Action performed with label: " + label ); if (label==null) return; String command = label; for ( String roiName : roiMap.keySet() ) { this.roiButtonMap.get( roiName ).setForeground(Color.black); } switch( command ) { case "Save & Next": LinkedHashMap< String, Roi > tempRoiMap = this.roiMap; File outputRoiFile = outputFile; saveRoiAlternative( outputRoiFile, tempRoiMap ); this.imp.close(); break; case "Toggle overlay": imp.setHideOverlay(!imp.getHideOverlay()); break; case "Remove overlap": removeOverlap(); break; default: for ( String roiName : this.roiNameList ) { if ( command.equals( roiName ) ) { doneRoi( roiName ); } } break; } } public void removeOverlap() { roiRemoveOverlap( this.roiMap ); } public void doneRoi( String roiName ) { this.selectedRoi = roiName; this.overlayCurrent.remove( this.roiMap.get(roiName) ); this.editRoi = this.imp.getRoi(); Color roiColor = Main.CONSTANT_COLOR_LIST[ this.roiNameList.indexOf(roiName) % Main.CONSTANT_COLOR_LIST.length ]; if (this.editRoi != null) { if (roiInterpolation) { FloatPolygon fp = this.editRoi.getInterpolatedPolygon(this.interpolationSmoothDistance, false); this.editRoi = new PolygonRoi(fp, Roi.POLYGON); } this.editRoi.setStrokeWidth( this.defaultRoiThickness ); this.editRoi.setStrokeColor( roiColor ); } this.roiMap.put(roiName, this.editRoi); this.overlayCurrent.add(this.editRoi); this.imp.deleteRoi(); this.imp.updateImage(); this.roiButtonMap.get(roiName).setForeground(Color.red); if (this.editRoi != null) { roiMap.put(this.selectedRoi, this.editRoi); } else { roiMap.remove(this.selectedRoi); } } /** * Remove the ROI from an overlay with a given roi name * * @param overlay * @param roiName * @param roiPosition */ public void removeRoiFromOverlay( Overlay overlay, String roiName ) { for (Roi roi : overlay.toArray()) { if ( roiName.equals( roi.getName() ) ) { overlay.remove( roi ); } } } /** * Return the ROI from an overlay with a given roi name * * @param overlay * @param roiName */ public Roi getRoiFromOverlay( Overlay overlay, String roiName ) { for (Roi roi : overlay.toArray()) { if ( roiName.equals( roi.getName() ) ) { return roi ; } } return null; } public void roiRemoveOverlap( LinkedHashMap< String, Roi > roiMap ) { String[] keyset = roiMap.keySet().toArray( new String[]{""} ); for ( String key1 : keyset ) { Roi roi1 = roiMap.get(key1); for ( String key2 : keyset ) { Roi roi2 = roiMap.get(key2); if ( !key1.equals(key2) ) { if (roi2 != null) { Color sc = roi2.getStrokeColor(); float sw = roi2.getStrokeWidth(); roi2.setName(key2); // Is it allowed to make this a ShapeRoi? roi2 = minusRoi( roi2, roi1);//.getRois()[0]; roi2.setStrokeColor(sc); roi2.setStrokeWidth(sw); roiMap.put(key2, roi2); } } } } for ( String key : keyset ) { // If the roi exists in the roiMap: exchange it for the cropped one in the "current regions" overlay if (!this.roiMap.get(key).equals(null)) { removeRoiFromOverlay( this.overlayCurrent, key ); this.overlayCurrent.add( this.roiMap.get(key) ); } } this.imp.repaintWindow(); } } @Override public void run(String arg) { try { this.DEBUG = true; // PARAMETER INPUT GenericDialogPlus gdp = new GenericDialogPlus("SliceMap: Manual Annotation & Curation"); gdp.addHelp( "https://github.com/mbarbie1/SliceMap" ); // Get the last used folder String userPath = IJ.getDirectory("current"); if (userPath == null) { userPath = ""; } if (this.DEBUG) { gdp.addDirectoryField( "Sample folder", "G:/triad_temp_data/demo/Curation_2/images/multiChannel" ); gdp.addDirectoryField( "ROIs folder folder", "G:/triad_temp_data/demo/Curation_2/rois" ); gdp.addDirectoryField( "Output folder", "G:/triad_temp_data/demo/Curation_2/output" ); } else { gdp.addDirectoryField( "Sample folder", userPath ); gdp.addDirectoryField( "ROIs folder folder", userPath ); gdp.addDirectoryField( "Output folder", userPath ); } //gdp.addStringField("Sample file extension", ""); gdp.addStringField("Sample name contains", ""); gdp.addStringField("Output file name prefix", ""); gdp.addCheckbox( "Overwriting existing output ROIs", true ); //gdp.addCheckbox( "Use existing ROIs", true ); gdp.addStringField("List of ROI-names (comma separated)", "hp,cx,cb,th,bs,mb"); gdp.showDialog(); if ( gdp.wasCanceled() ) { return; } // EXTRACTION OF PARAMETERS FROM DIALOG File sampleFile = new File( gdp.getNextString() ); if (!sampleFile.exists()) { String warningStr = "(Exiting) Error: Given sample folder does not exist: " + sampleFile; IJ.log(warningStr); MessageDialog md = new MessageDialog( null, "SliceMap: Manual annotation", warningStr ); return; } File roiFile = new File( gdp.getNextString() ); File outputFile = new File( gdp.getNextString() ); outputFile.mkdirs(); String ext = gdp.getNextString(); String sampleFilter = "";//gdp.getNextString(); String outputNamePrefix = gdp.getNextString(); boolean overwriteRois = gdp.getNextBoolean(); boolean useRois = true;//gdp.getNextBoolean(); String nameList = gdp.getNextString(); ArrayList< String > roiNameList = new ArrayList<>(); // nameList is a comma separated list of roiNames as a single String, // convert to ArrayList of roiNames String[] nameListSplit = nameList.split(","); for ( String roiName : nameListSplit ) { roiNameList.add(roiName); } ArrayList< File > fileList = findFiles( sampleFile, sampleFilter, "sl;dj;klsd" ); IJ.log("------------------------------------------------------"); IJ.log(" Manual Annotation & Curation "); IJ.log("------------------------------------------------------"); IJ.log("List of images:"); for (File file : fileList) { String fileName = file.getName(); IJ.log(fileName); } for (File file : fileList) { // Check for file extension String fileName = file.getName(); if( !fileName.endsWith(ext) ) continue; String sample_id; if (fileName.contains(".")) { sample_id = fileName.substring(0,fileName.lastIndexOf(".")); } else { sample_id = fileName; } String roiFileName = sample_id + ".zip"; String roiPath = roiFile.getAbsolutePath() + "/" + roiFileName; String outputName = outputNamePrefix + sample_id + ".zip"; // check for existing output files String outputPath = outputFile.getAbsolutePath() + "/" + outputName; if ( overwriteRois ) { try { Files.deleteIfExists( new File(outputPath).toPath() ); } catch (IOException ex) { Logger.getLogger(Manual_Annotation.class.getName()).log(Level.SEVERE, null, ex); } } IJ.log("Starting manual annotation & curation: " + fileName); process( sampleFile, roiFile, useRois, outputNamePrefix, outputFile, fileName, roiFileName, roiNameList, outputName, this.sig); IJ.log("Finished manual annotation & curation: " + fileName); } IJ.log( "Finished manual Annotation of all samples" ); IJ.log("------------------------------------------------------"); IJ.log("------------------------------------------------------"); IJ.log("------------------------------------------------------"); MessageDialog md = new MessageDialog(null, "SliceMap: Manual annotation", "Manual annotation finished.\n" + "Output folder: " + outputFile ); } catch( Exception e ) { StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); String stackTraceString = errors.toString(); String warningStr = "(Exiting) Error: An unknown error occurred.\n\n"+ "Please contact Michael Barbier if the error persists:\n\n\t michael(dot)barbier(at)gmail(dot)com\n\n"+ "with the following error:\n\n" + stackTraceString + "\n"; IJ.log(warningStr); MessageDialog md = new MessageDialog( null, "SliceMap: Manual annotation", warningStr ); return; //throw new RuntimeException(Macro.MACRO_CANCELED); } //if ( !md.isVisible() ) { // md.setVisible(true); //} } public void process( File inputFolder, File roiFolder, boolean useRois, String outputPrefix, File outputFolder, String inputName, String roiName, ArrayList< String > roiNameList, String outputName, LinkedHashMap< String, Integer > sig ) { String inputPath = inputFolder.getAbsolutePath() + "/" + inputName; String roiPath = roiFolder.getAbsolutePath() + "/" + roiName; String outputPath = outputFolder.getAbsolutePath() + "/" + outputName; String outputRoiPath = outputFolder.getAbsolutePath() + "/" + outputName; // Get current ImagePlus ImagePlus imp = IJ.openImage( inputPath ); if ( !imp.isVisible() ) { imp.show(); //imp.updateAndRepaintWindow() } // Get the ROI if it exists LinkedHashMap<String, Roi> roiMapInput = null; if ( Files.exists( new File(roiPath).toPath() ) ) { try { roiMapInput = LibRoi.loadRoiAlternative( new File(roiPath) ); } catch (ZipException ex) { Logger.getLogger(Manual_Annotation_Curation.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Manual_Annotation_Curation.class.getName()).log(Level.SEVERE, null, ex); } } imp.setDisplayMode(IJ.COMPOSITE); //imp.setActiveChannels("1010"); imp.setC(1); IJ.run(imp, "Enhance Contrast", "saturated=0.05"); //imp.setC(3) //IJ.run(imp, "Enhance Contrast", "saturated=0.05"); // //imageMessage(imp, inputName, 1) // Polygon point selection tool IJ.setTool("freehand"); // Select ROIs switch ( this.METHOD_ANNOTATION ) { // User interface with buttons case Manual_Annotation.METHOD_BUTTON: ChoiceList2 cl = new ChoiceList2( imp, useRois, roiMapInput, roiNameList, new File(outputPath), new File(outputRoiPath), sig ); //ChoiceList cl = new ChoiceList( imp, useRois, roiMapInput, roiNameList, outputPath ); break; // User interface using short keys case Manual_Annotation.METHOD_KEY: // RoiManager RoiManager rm = RoiManager.getInstance(); if (rm == null) { rm = new RoiManager(); rm.reset(); } selectROI(imp, rm, roiNameList, outputPath ); break; } // Wait for the ROIs to be written before continuing try { while ( this.sig.get("isReady").intValue() == 0 ) { //while ( ( !new File(outputRoiPath).exists() && (this.sig.get("noFinalRois").intValue() == 0) ) || ( this.sig.get("isReady").intValue() == 0 ) ) { TimeUnit.SECONDS.sleep(1); } } catch (Exception ex) { Logger.getLogger(Manual_Annotation.class.getName()).log(Level.SEVERE, null, ex); } } public void imageMessage( ImagePlus imp, String text, int line) { int tx = 10; int ty = line * 10; Font font = new Font( "Arial", Font.PLAIN, 12 ); Color color = Color.red; TextRoi t = new TextRoi( tx, ty, text, font); t.setNonScalable( true ); imp.setOverlay( t, color, 1, Color.black ); } public void selectROI( ImagePlus imp, RoiManager rm, ArrayList< String > roiNameList, String outputPath ) { // Remove keyListeners ImageCanvas canvas = imp.getWindow().getCanvas(); KeyListener[] kls = canvas.getKeyListeners(); for (KeyListener kl : kls) { canvas.removeKeyListener( kl ); } // Add custom keylisteners KeyListener listener = new Tap( rm, imp, roiNameList, outputPath ); canvas.addKeyListener( listener ); // Re-add existing key listeners for (KeyListener kl : kls) { canvas.addKeyListener( kl ); } imageMessage( imp, "Next ROI = " + roiNameList.get(0), 2); } public static void main(String[] args) { Class<?> clazz = Manual_Annotation_Curation.class; System.out.println(clazz.getName()); String url = clazz.getResource("/" + clazz.getName().replace('.', '/') + ".class").toString(); String pluginsDir = url.substring(5, url.length() - clazz.getName().length() - 6); System.out.println(pluginsDir); System.setProperty("plugins.dir", pluginsDir); ImageJ imagej = new ImageJ(); //IJ.log("START RUN Manual annotation"); IJ.runPlugIn(clazz.getName(), ""); //IJ.log("END RUN Manual annotation"); } }
mit
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/mail/testCheckPermissionRequest.java
2401
package generated.zcsclient.mail; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for checkPermissionRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="checkPermissionRequest"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="target" type="{urn:zimbraMail}targetSpec" minOccurs="0"/> * &lt;element name="right" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "checkPermissionRequest", propOrder = { "target", "right" }) public class testCheckPermissionRequest { protected testTargetSpec target; protected List<String> right; /** * Gets the value of the target property. * * @return * possible object is * {@link testTargetSpec } * */ public testTargetSpec getTarget() { return target; } /** * Sets the value of the target property. * * @param value * allowed object is * {@link testTargetSpec } * */ public void setTarget(testTargetSpec value) { this.target = value; } /** * Gets the value of the right property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the right property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRight().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getRight() { if (right == null) { right = new ArrayList<String>(); } return this.right; } }
mit
elliottsj/ftw-android
mobile/src/main/java/com/elliottsj/ftw/sync/Authenticator.java
1799
package com.elliottsj.ftw.sync; import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.NetworkErrorException; import android.content.Context; import android.os.Bundle; public class Authenticator extends AbstractAccountAuthenticator { public Authenticator(Context context) { super(context); } @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { throw new UnsupportedOperationException(); } @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { return null; } @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { return null; } @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { throw new UnsupportedOperationException(); } @Override public String getAuthTokenLabel(String authTokenType) { throw new UnsupportedOperationException(); } @Override public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { throw new UnsupportedOperationException(); } @Override public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { throw new UnsupportedOperationException(); } }
mit
valavanisleonidas/Automatic_Image_Classification
src/ImageRepresentationModels/Mixed/FusionTypes/LateFusion.java
9816
package ImageRepresentationModels.Mixed.FusionTypes; import Classification.TuningSVM; import Classification.TestImages; import Classification.TrainClassifier; import Utils.Statistics; import Utils.Utilities; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; public class LateFusion { private static TestImages testModel1; private static TestImages testModel2; private static List<Double> FinalProbabilities; private static List<Integer> FinalCategories; public static void main (String[] args) throws Exception{ String Type = "exhaustive"; // exhaustive , simpleWeight LateFusion latefusion = new LateFusion(); String projectPath = "C:\\Users\\Leonidas\\workspace\\BachelorThesis\\Clef2"; String dBSourcePath = "C:\\Users\\Leonidas\\Desktop\\clef2016\\databases\\Clef2013\\Compoundless"; String args1[] = new String [11]; // gboc train test args1[0] = projectPath+"\\train_libSVM_2x2_CIELab_128.txt"; args1[1] = projectPath+"\\test_libSVM_2x2_CIELab_128.txt"; // boc train test args1[2] = projectPath+"\\phow_1000Train.txt"; args1[3] = projectPath+"\\phow_1000Test.txt"; //models args1[4] = projectPath+"\\modelGboc"; args1[5] = projectPath+"\\ModelBovw"; //result files args1[6] = projectPath+"\\ResultsGboc"; args1[7] = projectPath+"\\ResultsBovw"; args1[8] = projectPath; args1[9] = dBSourcePath; //final result file args1[10] = projectPath+"\\ResultsLateFusion"; if (Type.equals("exhaustive")){ latefusion.performExhaustiveLateFusion(args1); } else{ double weight = 0.5; latefusion.performLateFusion(args1,weight,null); } } private void performExhaustiveLateFusion(String[] args1) throws Exception{ LateFusion latefusion = new LateFusion(); double BestAccuracy=-1; double BestWeight=-1; //array with weights from 0 to 100 with step 0.1 double[] weights = new double[101]; for(int i=0;i<=100;i++) weights[i] = (double)i/100; for (int i = 0;i<weights.length;i++){ System.out.println("weight :" +weights[i] ); double acc = latefusion.performLateFusion(args1,weights[i],null); if (acc >= BestAccuracy){ BestAccuracy =acc; BestWeight= weights[i]; System.out.println("weight :" +weights[i]+" max with acc "+ BestAccuracy); } } System.out.println("Best found with weight :" +BestWeight+" , acc "+ BestAccuracy); } public double performLateFusion(String[] args,double weight,Shell shell) throws Exception{ String trainPathModel1 = args[0] , testPathModel1 = args[1], trainPathModel2 = args[2], testPathModel2 = args[3], ModelPath1 = args[4], ModelPath2 = args[5], ResultPath1 = args[6], ResultPath2 = args[7], projectPath= args[8], DBSourcePath= args[9], resultsFilePath= args[10], command1 = null, command2 = null; double accuracy; double weightModel1,weightModel2 ; if( weight == 1 || weight == 0 ){ weightModel1 = 1; weightModel2 = 1; } else{ weightModel1 = weight; weightModel2 = 1 - weight; } // perfom tuning for models // String[] commands = FindBestParametersForModels(trainPathModel1,trainPathModel2,command1,command2,shell); // command1 = commands[0]; // command2 = commands[1]; command1= "-c 16 -g 16 -b 1 -q"; command2 = "-c 4.0 -g 0.5 -b 1 -q"; //if train files exist dont train if( !( new File(ModelPath1).exists() && new File(ModelPath2).exists() ) ){ System.out.println("Training"); trainModels(trainPathModel1, trainPathModel2, ModelPath1, ModelPath2, command1, command2, shell); } if( !( new File(ResultPath1).exists() && new File(ResultPath2).exists() ) ){ System.out.println("Testing"); testModels(testPathModel1, testPathModel2, ModelPath1, ModelPath2, ResultPath1, ResultPath2, shell); } // System.out.println("--------model 1 probs -----------"); // for(int i =0; i<testModel1.getProbabilities().size();i++){ // for(int j =0; j<testModel1.getProbabilities().get(i).length;j++){ // System.out.print(testModel1.getProbabilities().get(i)[j]+" "); // } // System.out.println(); // } // System.out.println("--------model 2 probs -----------"); // // for(int i =0; i<testModel2.getProbabilities().size();i++){ // for(int j =0; j<testModel2.getProbabilities().get(i).length;j++){ // System.out.print(testModel2.getProbabilities().get(i)[j]+" "); // } // System.out.println(); // } //perform late fusion with probabilities lateFusion(weightModel1,weightModel2); writeResultsToFile(projectPath,resultsFilePath,shell); accuracy = writeStatisticsToFile(projectPath,DBSourcePath,resultsFilePath,shell); // for(int i =0 ; i<FinalProbabilities.size();i++){ // System.out.println("image : "+i+" with proba : "+FinalProbabilities.get(i) +" category " + FinalCategories.get(i) ); // } return accuracy; } private String[] FindBestParametersForModels(String trainPathModel1,String trainPathModel2, String command1, String command2, Shell shlClassification) throws InterruptedException{ // First Model TuningSVM bestParameters1=new TuningSVM(trainPathModel1,shlClassification); Thread bestParametersThread1 = new Thread(bestParameters1); bestParametersThread1.start(); //second Model TuningSVM bestParameters2=new TuningSVM(trainPathModel2,shlClassification); Thread bestParametersThread2 = new Thread(bestParameters2); bestParametersThread2.start(); bestParametersThread1.join(); bestParametersThread2.join(); command1 = "-c "+(double)bestParameters1.getBestc()+" -g "+(double)bestParameters1.getBestg()+" -b 1 -q"; command2 = "-c "+(double)bestParameters2.getBestc()+" -g "+(double)bestParameters2.getBestg()+" -b 1 -q"; System.out.println("command1:" +command1 +" acc: "+(double)bestParameters1.getBestcv()); System.out.println("command2:" +command2 +" acc: "+(double)bestParameters2.getBestcv()); return new String[] { command1, command2}; } private void trainModels(String trainDataPath1,String trainDataPath2,String saveModelPathTrain1,String saveModelPathTrain2, String command1,String command2,Shell shlClassification) throws InterruptedException{ TrainClassifier trainModel1=new TrainClassifier(command1,trainDataPath1, saveModelPathTrain1,shlClassification); Thread threadModel1 = new Thread(trainModel1); threadModel1.start(); TrainClassifier trainModel2=new TrainClassifier(command2,trainDataPath2, saveModelPathTrain2,shlClassification); Thread threadModel2 = new Thread(trainModel2); threadModel2.start(); threadModel1.join(); threadModel2.join(); } private void testModels(String testPathModel1,String testPathModel2,String ModelPath1,String ModelPath2, String resultFilePath1,String resultFilePath2,Shell shlClassification) throws InterruptedException{ //for probabilities String command = "-b 1"; //test images given with command testModel1=new TestImages(testPathModel1,ModelPath1,resultFilePath1,command,shlClassification); Thread threadingModel1 = new Thread(testModel1); threadingModel1.start(); //test images given with command testModel2=new TestImages(testPathModel2,ModelPath2,resultFilePath2,command,shlClassification); Thread threadingModel2 = new Thread(testModel2); threadingModel2.start(); threadingModel1.join(); threadingModel2.join(); } private void lateFusion(double weightModel1,double weightModel2){ FinalProbabilities = new ArrayList<Double>(); FinalCategories = new ArrayList<Integer>(); int imageLength = testModel1.getProbabilities().size(); int labelsLength = testModel1.getLabels().length; // for each image for(int i =0; i<imageLength;i++){ double maxProbability = -1; int Category=-1; double score=-1; // for each probability in image for(int j =0;j<labelsLength;j++){ score = weightModel1*testModel1.getProbabilities().get(i)[j] + weightModel2*testModel2.getProbabilities().get(i)[j]; if(maxProbability<=score){ maxProbability = score; Category=testModel1.getLabelsIndex(j); } } FinalProbabilities.add(maxProbability); FinalCategories.add(Category); } } private void writeResultsToFile(String projectPath,String resultsPath,Shell shell) throws IOException { BufferedWriter writer = null; File file=null;//to arxeio xml pou tha grapsoume try { //to apothikeuei ston kainourgio fakelo tou project me katalixi to onoma tou project file = new File (resultsPath); }//se periptwsh pou den uparxei to arxeio st disko na emfanisw t adistoixo mhnuma catch (NullPointerException e ){ e.printStackTrace(); MessageDialog.openError(shell, "Error","File Not Found!"); } try{ writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); // me parametro to f } catch(FileNotFoundException ex){ ex.printStackTrace(); MessageDialog.openError(shell, "Error","Error opening file!"); } for (int i =0;i<FinalProbabilities.size();i++){ writer.write(FinalCategories.get(i)+" "+FinalProbabilities.get(i)+"\n"); } writer.close(); } private double writeStatisticsToFile(String projectPath,String DBsource,String resultsFile,Shell shell) throws Exception{ Statistics statistics = new Statistics(); statistics.createMetrics(projectPath, DBsource, resultsFile,true, shell); return statistics.getAccuracy(); } }
mit
rafaelfccg/JMSImplementation
JMSImplementation/src/topic/MyTopic.java
399
package topic; import java.io.Serializable; import javax.jms.JMSException; import javax.jms.Topic; public class MyTopic implements Topic, Serializable { /** * */ private static final long serialVersionUID = -5010233988379309842L; private String name; public MyTopic(String name){ this.name = name; } @Override public String getTopicName() throws JMSException { return name; } }
mit
Disputes/FredBoat
FredBoat/src/main/java/fredboat/command/fun/RollCommand.java
2286
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fredboat.command.fun; import fredboat.commandmeta.abs.IFunCommand; import fredboat.feature.I18n; import net.dv8tion.jda.core.MessageBuilder; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.TextChannel; import java.text.MessageFormat; public class RollCommand extends RandomImageCommand implements IFunCommand { public RollCommand(String[] urls) { super(urls); } public RollCommand(String imgurAlbumUrl) { super(imgurAlbumUrl); } @Override public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) { Message ourMessage = new MessageBuilder() .append("_") .append(MessageFormat.format(I18n.get(guild).getString("rollSuccess"), invoker.getAsMention())) .append("_") .build(); super.sendRandomFileWithMessage(channel, ourMessage); } @Override public String help(Guild guild) { return "{0}{1}\n#Roll around."; } }
mit
diirt/diirt
pvmanager/datasource-timecache/src/main/java/org/diirt/datasource/timecache/query/QueryParameters.java
610
/** * Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.datasource.timecache.query; import org.diirt.datasource.timecache.Parameter; import org.diirt.util.time.TimeRelativeInterval; /** * @author Fred Arnaud (Sopra Group) - ITER */ public class QueryParameters { TimeRelativeInterval timeInterval; public Parameter config = Parameter.Default; public QueryParameters timeInterval(TimeRelativeInterval timeInterval) { this.timeInterval = timeInterval; return this; } }
mit
sachinlala/SimplifyLearning
algorithms/src/test/java/com/sl/algorithms/sort/advanced/wave/WiggleSortIITest.java
1957
package com.sl.algorithms.sort.advanced.wave; import static com.sl.algorithms.core.utils.ArrayOps.printArray; import com.sl.algorithms.core.interfaces.sort.SortingEngine; import com.sl.algorithms.sort.BaseTest; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @SuppressWarnings("unchecked") public class WiggleSortIITest extends BaseTest { private SortingEngine sortingEngine; @Before public void setup() { sortingEngine = new WiggleSortII(); } @Test public void assertWaveForSortedList() { assertBaseCases(sortingEngine); { Integer[] sampleNumbers = new Integer[]{1, 2, 3, 4, 5}; sortingEngine.sort(sampleNumbers); Assert.assertEquals("[3,5,1,4,2]", printArray(sampleNumbers)); } { String[] sampleData = new String[]{"A", "B", "C", "D", "E"}; sortingEngine.sort(sampleData); Assert.assertEquals("[C,E,A,D,B]", printArray(sampleData)); } } @Test public void assertSmallSets() { { Integer[] sampleData = new Integer[]{1}; sortingEngine.sort(sampleData); Assert.assertEquals("[1]", printArray(sampleData)); } { Integer[] sampleData = new Integer[]{2, 1}; sortingEngine.sort(sampleData); Assert.assertEquals("[1,2]", printArray(sampleData)); } } @Test public void assertWaveForListWithDupes() { Integer[] sampleData = new Integer[]{2, 2, 2, 1, 1, 1}; sortingEngine.sort(sampleData); Assert.assertEquals("[1,2,1,2,1,2]", printArray(sampleData)); } @Test public void assertWaveForUnsortedList() { { Integer[] sampleNumbers = new Integer[]{3, 5, 2, 1, 6, 4}; sortingEngine.sort(sampleNumbers); Assert.assertEquals("[3,6,2,4,1,5]", printArray(sampleNumbers)); } { String[] sampleData = new String[]{"E", "A", "B", "D", "C"}; sortingEngine.sort(sampleData); Assert.assertEquals("[C,E,A,D,B]", printArray(sampleData)); } } }
mit
slemke/tpp4j
src/test/java/de/fhkoeln/tests/tasks/AllTasksTests.java
2408
package de.fhkoeln.tests.tasks; import de.fhkoeln.Pipeline; import de.fhkoeln.exceptions.OCRException; import de.fhkoeln.io.TextReader; import de.fhkoeln.tasks.ImageProcessingTask; import de.fhkoeln.tasks.NLPTask; import de.fhkoeln.tasks.OCRTask; import de.fhkoeln.tasks.TextCleaningTask; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Properties; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class AllTasksTests { @Test public void allTasksTests() throws OCRException, IOException { String document2 = "src/test/resources/images/input/document2/"; String document1 = "src/test/resources/images/input/document1/"; String workspace = "src/test/resources/images/tasks/all/"; Properties prop = new Properties(); prop.put("annotators", "tokenize, ssplit, pos, ner, lemma"); prop.put("tokenize.language", "de"); prop.put("ner.model", "edu/stanford/nlp/models/ner/german.hgc_175m_600.crf.ser.gz"); prop.put("ner.applyNumericClassifiers", "false"); prop.put("ner.useSUTime", "false"); prop.put("pos.model", "edu/stanford/nlp/models/pos-tagger/german/german-hgc.tagger"); ImageProcessingTask imp = new ImageProcessingTask(1.0, 10, 0.0, true, true, false); OCRTask task = new OCRTask("deu"); TextCleaningTask cleaningTask = new TextCleaningTask(""); NLPTask nlpTask = new NLPTask(prop); Pipeline pipeline = new Pipeline(workspace); pipeline.addDocument(document1); pipeline.addDocument(document2); System.out.println("Anzahl der Dokumente: " + pipeline.numberOfDocuments()); pipeline.addTask(imp); pipeline.addTask(task); pipeline.addTask(cleaningTask); pipeline.addTask(nlpTask); pipeline.apply(); File ocr = new File("src/test/resources/images/tasks/all/document2/ocr/document2.txt"); TextReader reader = new TextReader(); String read = reader.read(ocr); assertEquals(true, ocr.exists()); assertThat(read, not("")); File data = new File("src/test/resources/images/tasks/nlp/text/data.txt"); String datatext = reader.read(data); assertEquals(true, data.exists()); assertThat(datatext, not("")); } }
mit
DocuWare/PlatformJavaClient
src/com/docuware/dev/settings/common/ObjectFactory.java
814
package com.docuware.dev.settings.common; import java.net.URI; import com.docuware.dev.Extensions.*; import java.util.concurrent.CompletableFuture; import java.util.*; import com.docuware.dev.schema._public.services.Link; import javax.xml.bind.annotation.XmlRegistry; @XmlRegistry public class ObjectFactory { public ObjectFactory() { } public DWRectangle createDWRectangle() { return new DWRectangle(); } public KeyValuePair createKeyValuePair() { return new KeyValuePair(); } public KeyValuePairs createKeyValuePairs() { return new KeyValuePairs(); } public DWPoint createDWPoint() { return new DWPoint(); } public DWSize createDWSize() { return new DWSize(); } }
mit
ScreenBasedSimulator/ScreenBasedSimulator2
src/main/java/mil/tatrc/physiology/datamodel/bind/MaskLeakData.java
2000
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.12.09 at 06:16:52 PM EST // package mil.tatrc.physiology.datamodel.bind; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for MaskLeakData complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MaskLeakData"> * &lt;complexContent> * &lt;extension base="{uri:/mil/tatrc/physiology/datamodel}AnesthesiaMachineActionData"> * &lt;sequence> * &lt;element name="Severity" type="{uri:/mil/tatrc/physiology/datamodel}ScalarFractionData"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MaskLeakData", propOrder = { "severity" }) public class MaskLeakData extends AnesthesiaMachineActionData { @XmlElement(name = "Severity", required = true) protected ScalarFractionData severity; /** * Gets the value of the severity property. * * @return * possible object is * {@link ScalarFractionData } * */ public ScalarFractionData getSeverity() { return severity; } /** * Sets the value of the severity property. * * @param value * allowed object is * {@link ScalarFractionData } * */ public void setSeverity(ScalarFractionData value) { this.severity = value; } }
mit
ArjanO/KenIkJouNietErgensVan
spring-ws/src/test/java/com/dare2date/domein/facebook/FacebookWorkHistoryTest.java
2428
/** * Copyright (c) 2013 HAN University of Applied Sciences * Arjan Oortgiese * Joëll Portier * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package com.dare2date.domein.facebook; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; public class FacebookWorkHistoryTest { private FacebookWorkHistory work; @Before public void before() { work = new FacebookWorkHistory(); } @Test public void testSetId() { work.setId("12345"); Assert.assertEquals("12345", work.getId()); } @Test public void testSetName() { work.setName("Test B.V."); Assert.assertEquals("Test B.V.", work.getName()); } @Test public void testEquals() { FacebookWorkHistory item1 = new FacebookWorkHistory(); FacebookWorkHistory item2 = new FacebookWorkHistory(); item1.setId("1"); item1.setName("Test"); item2.setId("1"); item2.setName("Test"); Assert.assertTrue(item1.equals(item2)); } @Test public void testNotEquals() { FacebookWorkHistory item1 = new FacebookWorkHistory(); FacebookWorkHistory item2 = new FacebookWorkHistory(); item1.setId("1"); item1.setName("Test"); item2.setId("2"); item2.setName("Test2"); Assert.assertFalse(item1.equals(item2)); } }
mit
joaogalli/sovi-classroom
src/main/java/br/com/sovi/classroom/service/UserService.java
382
package br.com.sovi.classroom.service; import br.com.sovi.classroom.entity.User; import br.com.sovi.classroom.exception.ValidationException; /** * @author Joao Eduardo Galli <joaogalli@gmail.com> */ public interface UserService { User findUserByUsername(String username); String getUserPassword(String id); User registerNewUser(User user) throws ValidationException; }
mit
Dimensions/Solar
src/main/java/solar/dimensions/api/event/player/PlayerGameModeChangeEvent.java
163
package solar.dimensions.api.event.player; import solar.dimensions.api.event.common.PlayerEvent; public class PlayerGameModeChangeEvent extends PlayerEvent { }
mit
ericminio/sandbox
learning-java/src/test/java/ericminio/CompareDateTimeTest.java
618
package ericminio; import org.junit.Test; import java.time.Duration; import java.time.LocalDateTime; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertThat; public class CompareDateTimeTest { @Test public void isPossibleWithDuration() { LocalDateTime now = LocalDateTime.now(); LocalDateTime later = now.plusSeconds(2); Duration duration = Duration.between(now, later); assertThat(duration.toMillis(), greaterThan(0l)); assertThat(duration.toMillis(), lessThan(3 * 1000l)); } }
mit
tektyte/Log4-Desktop-PC
power-log-it/src/view_and_controller/MonitorChartPanel.java
18085
package view_and_controller; import model.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.MenuElement; import org.jfree.chart.*; import org.jfree.chart.axis.*; import org.jfree.chart.plot.*; import org.jfree.chart.renderer.xy.*; import org.jfree.chart.title.TextTitle; import org.jfree.ui.Layer; import org.jfree.data.Range; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesChangeListener; import org.jfree.data.time.Millisecond; import org.jfree.data.time.TimeSeries; @SuppressWarnings("serial") public class MonitorChartPanel extends JPanel implements MouseListener, MouseMotionListener, Observer, ActionListener, SeriesChangeListener { /** The standard fonts used within this panel */ private static final String STD_FONT_STR = "Planer"; /** Fills the entire MonitorChartPanel */ private ChartPanel chartPanel; /** The plot associated with chartPanel */ private XYPlot plot; /** Contains the plot cursors to be displayed on the screen */ private ArrayList<MyValueMarker> myMarkers; /** Used to mark the area between cursors, or before or after a single cursor */ private IntervalMarker intervalMarker; /** Scaling factor used for determining a cursor click */ private static final double FRAC_OF_DOMAIN = 0.0129; /** */ private ElectricalDataModel dataModel; public MonitorChartPanel(ElectricalDataModel dataModel, JMenuBar menuBar, ArrayList<MyValueMarker> myMarkers, IntervalMarker intervalMarker) { // Initialise the main chart panel //setLayout(new GridLayout(1,1)); setLayout(new BorderLayout()); chartPanel = initialiseChartPanel(dataModel); add(chartPanel); // Initialise the main chart cursors this.myMarkers = myMarkers; this.intervalMarker = intervalMarker; // Register this component as an ActionListener with the cursor activation menu buttons JMenu viewMenu = menuBar.getMenu(menuBar.getMenuCount()-2); JMenu cursorMenu = (JMenu) viewMenu.getSubElements()[0].getSubElements()[0]; MenuElement[] cursorEnableButtons = cursorMenu.getSubElements()[0].getSubElements(); for (int i=0; i < cursorEnableButtons.length; i++) { JRadioButtonMenuItem currItem = (JRadioButtonMenuItem) cursorEnableButtons[i]; currItem.addActionListener(this); } // Panel listens to changes in series data to adjust interval marker when appropriate this.dataModel = dataModel; dataModel.addDataCollectionListener(this); } /** * * @param dataModel the data for an electrical data type * @return chart panel for the given electrical data type data */ private ChartPanel initialiseChartPanel(ElectricalDataModel dataModel) { // Initialise the main chart title and axes titles to correspond to dataModel String chartTitle = dataModel.getElectricalDataTitle() + " Monitor"; String chartAxisLabelY = dataModel.getElectricalDataTitle(); // Initialise plot color based on the electrical data type Color plotColor = dataModel.getElectricalColour(); // Generate the graph JFreeChart chart = ChartFactory.createXYAreaChart( chartTitle, // Title "", // x-axis Label dataModel.getElectricalDataTitle() + " (" + dataModel.getBaseDataUnitString() + ")", // y-axis Label dataModel.getDataCollection(), // data PlotOrientation.VERTICAL, false, // show Legend? true, // use tooltips? false ); // generate URLs? // change the chart title font chart.getTitle().setFont(new Font(STD_FONT_STR, Font.BOLD, 30)); // Change the domain axis to a dateaxis plot = (XYPlot) chart.getXYPlot(); plot.setDomainAxis(new DateAxis("")); // Initialise the plot settings plot.setBackgroundPaint(Color.WHITE); plot.setDomainGridlinePaint(Color.GRAY); plot.setRangeGridlinePaint(Color.GRAY); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); plot.getDomainAxis().setLowerMargin(0.001); plot.getDomainAxis().setUpperMargin(0.0); ((NumberAxis)plot.getRangeAxis()).setAutoRangeIncludesZero(true); ((NumberAxis)plot.getRangeAxis()).setNumberFormatOverride(new DecimalFormat("0.00E0")); // Set the plot fonts Font axesFont = new Font(STD_FONT_STR, Font.PLAIN, 20); plot.getDomainAxis().setLabelFont(axesFont); plot.getRangeAxis().setLabelFont(axesFont); plot.getDomainAxis().setTickLabelFont(axesFont); plot.getRangeAxis().setTickLabelFont(axesFont); // Set the 2nd plot renderer for rendering darker line across the area XYAreaRenderer renderer = new XYAreaRenderer(); renderer.setSeriesVisible(0, true); renderer.setSeriesVisible(1, false); renderer.setSeriesPaint(0, new Color(plotColor.getRed(), plotColor.getGreen(), plotColor.getBlue(), 50)); plot.setRenderer(0, renderer); plot.setDataset(1, dataModel.getLineDataCollection()); XYLineAndShapeRenderer lineAndShapeRenderer = new XYLineAndShapeRenderer(true, false); lineAndShapeRenderer.setSeriesPaint(0, plotColor); lineAndShapeRenderer.setSeriesStroke(0, new BasicStroke(1f)); plot.setRenderer(1, lineAndShapeRenderer); //((NumberAxis)plot.getRangeAxis()).centerRange(0.0); // Add the graph to the panel chartPanel = new ChartPanel(chart); chartPanel.createToolTip(); chartPanel.setMouseWheelEnabled(true); chartPanel.addMouseListener(this); chartPanel.addMouseMotionListener(this); // Disable mouse wheel zooming chartPanel.setMouseWheelEnabled(false); //set min and max draw dimensions for resizing chartPanel.setMinimumDrawHeight(0); chartPanel.setMinimumDrawWidth(0); chartPanel.setMaximumDrawHeight(30000); chartPanel.setMaximumDrawWidth(30000); removeUnwantedChartProperties(); return chartPanel; } /** * Removes the unwanted right click options from the main chart panel. */ private void removeUnwantedChartProperties() { // remove the 'properties' option from the chart right-click chartPanel.getPopupMenu().remove(0); chartPanel.getPopupMenu().remove(0); // remove the 'print' option from the chart right-click chartPanel.getPopupMenu().remove(2); chartPanel.getPopupMenu().remove(2); // remove the option to save as a pdf ((JMenu) chartPanel.getPopupMenu().getComponent(1)).remove(2); } /* Mouse listeners */ @Override /** * Changes the mouse cursor image if a marker is moused over */ public void mouseMoved(MouseEvent event) { if (checkMouseOnMarker(getCursorXPosition(event.getPoint()), getCursorYPosition(event.getPoint())) >= 0) { // mouse is on a cursor setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } else { // mouse is NOT on a cursor setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } @Override /** * If the mouse is pressed on a cursor, set the cursor dragging true and * disable mouse zooming. */ public void mousePressed(MouseEvent event) { int markerIndex = checkMouseOnMarker(getCursorXPosition(event.getPoint()), getCursorYPosition(event.getPoint())); if(markerIndex >= 0) { chartPanel.setMouseZoomable(false); myMarkers.get(markerIndex).setDragging(true); } } @Override /** * On a mouse release ensure all the markers have dragging set to false * and allow the chart to be mouse zoomable again. */ public void mouseReleased(MouseEvent e) { for(int i=0; i < myMarkers.size(); i++) myMarkers.get(i).setDragging(false); chartPanel.setMouseZoomable(true); } @Override /** * Used for updating a plot cursor value if it is being dragged. */ public void mouseDragged(MouseEvent event) { // If there are no cursors on the plot do nothing if(plot.getDomainMarkers(Layer.FOREGROUND) == null) return; double mouseChartDomainValu = getCursorXPosition(event.getPoint()); // upper bound and lower bound on data series domain values double lowerBound = dataModel.getSeriesXLowerBound(); double upperBound = dataModel.getSeriesXUpperBound(); // displayed domain axis range Range domainAxisRange = plot.getDomainAxis().getRange(); // Set upper bound to be minimum of the dataset maximum bound and the displayed domain maximum bound if (domainAxisRange.getUpperBound() < upperBound){ upperBound = domainAxisRange.getUpperBound(); } // Set lower bound to be maximum of the dataset lower bound and the displayed domain lower bound if (domainAxisRange.getLowerBound() > lowerBound) { lowerBound = domainAxisRange.getLowerBound(); } // Adjust the mouse value to max or min of domain if it is off the chart if(mouseChartDomainValu > upperBound) mouseChartDomainValu = upperBound; else if (mouseChartDomainValu < lowerBound) mouseChartDomainValu = lowerBound; // Go through the list of plot cursors and adjust the value of the cursor being dragged for(int i=0; i<myMarkers.size(); i++) { if (myMarkers.get(i).isDragging()) { myMarkers.get(i).getValueMarker().setValue(mouseChartDomainValu); myMarkers.get(i).setOffset(mouseChartDomainValu-dataModel.getSeriesXLowerBound()); addOrRemoveIntervalMarker(); return; } } } /** * * @param domainPressPos the position of a mouse press in terms of the chart domain * @param rangePressPos the position of a mouse press in terms of the chart range * @return -1 if the mouse is not on a marker, else the index of the marker the mouse is on */ private int checkMouseOnMarker(double domainPressPos, double rangePressPos) { ArrayList<ValueMarker> plotMarkers; // No cursors are on the plot, therefore mouse is not on a marker if(plot.getDomainMarkers(Layer.FOREGROUND) == null) return -1; // get the cursors currently on the plot plotMarkers = new ArrayList<ValueMarker>(plot.getDomainMarkers(Layer.FOREGROUND)); // get the axes ranges (in terms of what is displayed) Range domainAxisRange = plot.getDomainAxis().getRange(); Range rangeAxisRange = plot.getRangeAxis().getRange(); // the user error in a cursor click, in terms of the domain range double eps = domainAxisRange.getLength() * FRAC_OF_DOMAIN; for(int i=0; i<myMarkers.size(); i++) { ValueMarker currMarker = myMarkers.get(i).getValueMarker(); if(plotMarkers.contains(currMarker) && domainPressPos > currMarker.getValue() - eps/2 && domainPressPos < currMarker.getValue() + eps/2 && rangePressPos > rangeAxisRange.getLowerBound() && rangePressPos < rangeAxisRange.getUpperBound()) { return i; } } return -1; } /** * * @param p point corresponding to the mouse press, in terms of panel press * @return the domain axis value corresponding to where the user pressed */ private double getCursorXPosition(Point p) { Rectangle2D plotArea = chartPanel.getScreenDataArea(); return plot.getDomainAxis().java2DToValue(p.getX(), plotArea, plot.getDomainAxisEdge()); } /** * * @param p point corresponding to the mouse press, in terms of panel press * @return the range axis value corresponding to where the user pressed */ private double getCursorYPosition(Point p){ Rectangle2D plotArea = chartPanel.getScreenDataArea(); return plot.getRangeAxis().java2DToValue(p.getY(), plotArea, plot.getRangeAxisEdge()); } /* Action listeners */ @Override /** * Used for adding and removing cursors corresponding to view menu selections. */ public void actionPerformed(ActionEvent event) { // Check if the event source is a JRadioButtonMenuItem (i.e. a cursor selection) if (event.getSource() instanceof JRadioButtonMenuItem) { JRadioButtonMenuItem button = (JRadioButtonMenuItem) event.getSource(); // Add the cursors (markers) to the plot if(event.getActionCommand().equals("Cursor 0") && button.isSelected()) { double offset =addMarkerToPlot(myMarkers.get(0).getValueMarker()); myMarkers.get(0).setOffset(offset); } else if (event.getActionCommand().equals("Cursor 1") && button.isSelected()) { double offset = addMarkerToPlot(myMarkers.get(1).getValueMarker()); myMarkers.get(1).setOffset(offset); } // remove markers from the plot else if (event.getActionCommand().equals("Cursor 0") && !button.isSelected()) { plot.removeDomainMarker(myMarkers.get(0).getValueMarker()); } else if (event.getActionCommand().equals("Cursor 1") && !button.isSelected()) { plot.removeDomainMarker(myMarkers.get(1).getValueMarker()); } addOrRemoveIntervalMarker(); } } /** * Used when a plot cursor is initially enabled to add the cursor to the * plot, centered in the middle of the domain axis. * @param marker */ private double addMarkerToPlot(ValueMarker marker) { double lowerBound = dataModel.getSeriesXLowerBound(); double upperBound = dataModel.getSeriesXUpperBound(); double offset = ((upperBound-lowerBound)/2); marker.setValue(lowerBound+offset); // marker.setValue(plot.getDomainAxis().getRange().getCentralValue()); plot.addDomainMarker(marker); return offset; } private void addOrRemoveIntervalMarker() { // remove the interval marker from the plot plot.removeDomainMarker(intervalMarker, Layer.BACKGROUND); // check if both cursors are on the graph if(plot.getDomainMarkers(Layer.FOREGROUND) != null && plot.getDomainMarkers(Layer.FOREGROUND).size() == 2) { // both cursors are on the graph double start, end; // check which plot cursor has the smaller domain value if(myMarkers.get(0).getValueMarker().getValue() < myMarkers.get(1).getValueMarker().getValue()) { start = myMarkers.get(0).getValueMarker().getValue(); end = myMarkers.get(1).getValueMarker().getValue(); } else { start = myMarkers.get(1).getValueMarker().getValue(); end = myMarkers.get(0).getValueMarker().getValue(); } // mark the interval between the cursors intervalMarker.setStartValue(start); intervalMarker.setEndValue(end); plot.addDomainMarker(intervalMarker, Layer.BACKGROUND); } // check if cursor 0 is on the graph else if (plot.getDomainMarkers(Layer.FOREGROUND) != null && plot.getDomainMarkers(Layer.FOREGROUND).contains(myMarkers.get(0).getValueMarker())) { // mark the interval below cursor 0, uses the smallest data time value (ignores the displayed domain) intervalMarker.setStartValue(dataModel.getSeriesXLowerBound()); intervalMarker.setEndValue(myMarkers.get(0).getValueMarker().getValue()); plot.addDomainMarker(intervalMarker, Layer.BACKGROUND); } else if (plot.getDomainMarkers(Layer.FOREGROUND) != null && plot.getDomainMarkers(Layer.FOREGROUND).contains(myMarkers.get(1).getValueMarker())) { // mark the interval above cursor 1, uses the largest data time value (ignores the displayed domain) intervalMarker.setStartValue(myMarkers.get(1).getValueMarker().getValue()); intervalMarker.setEndValue(dataModel.getSeriesXUpperBound()); plot.addDomainMarker(intervalMarker, Layer.BACKGROUND); } } @Override public void update(Observable o, Object arg) { if (o instanceof ObTimeSeriesCollection) { // A channel has been added or removed from the model // Set the default statistics listeners to the first channel dataModel.addSeriesChangeListener(this, 0); } } @Override /** * Used to adjust the interval marker, when it extends above a cursor to the maximum value * in the plots data set. */ public void seriesChanged(SeriesChangeEvent arg0) { if(plot.getDomainMarkers(Layer.FOREGROUND) == null) return; // plot markers displayed on the graph ArrayList<ValueMarker> plotMarkers = new ArrayList<ValueMarker>(plot.getDomainMarkers(Layer.FOREGROUND)); for (int i=0; i<2; i++){ if (plotMarkers!= null && plotMarkers.contains(myMarkers.get(i).getValueMarker())){ myMarkers.get(i).getValueMarker().setValue(dataModel.getSeriesXLowerBound()+myMarkers.get(i).getOffset()); } //addOrRemoveIntervalMarker(); // Adjust plot so if only cursor 1 is on the graph it extends to the far right data value if (plotMarkers != null && plotMarkers.size() == 1){ if(plotMarkers.contains(myMarkers.get(1).getValueMarker())){ intervalMarker.setEndValue(dataModel.getSeriesXUpperBound()); intervalMarker.setStartValue(myMarkers.get(1).getValueMarker().getValue()); } else if (plotMarkers.contains(myMarkers.get(0).getValueMarker())){ intervalMarker.setEndValue(myMarkers.get(0).getValueMarker().getValue()); intervalMarker.setStartValue(dataModel.getSeriesXLowerBound()); } } else if (plotMarkers != null && plotMarkers.size() ==2){ if (myMarkers.get(0).getValueMarker().getValue() > myMarkers.get(1).getValueMarker().getValue()){ intervalMarker.setStartValue(myMarkers.get(1).getValueMarker().getValue()); intervalMarker.setEndValue(myMarkers.get(0).getValueMarker().getValue()); } else { intervalMarker.setStartValue(myMarkers.get(0).getValueMarker().getValue()); intervalMarker.setEndValue(myMarkers.get(1).getValueMarker().getValue()); } } } } /* Getters and Setters */ public ArrayList<MyValueMarker> getMarkers() { return myMarkers; } public XYPlot getXYPlot() { return plot; } public boolean getCursorStatus(int index){ if (plot.getDomainMarkers(Layer.FOREGROUND) != null && plot.getDomainMarkers(Layer.FOREGROUND).contains(myMarkers.get(index).getValueMarker())){ return true; } else { return false; } } /* Unused listener methods */ @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
mit
richardfearn/diirt
util/src/test/java/org/diirt/util/text/CsvParserDebug.java
1835
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.util.text; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFileChooser; import static org.diirt.util.text.StringUtil.DOUBLE_REGEX_WITH_NAN; /** * * @author carcassi */ public class CsvParserDebug { public static void main(String[] args) throws Exception { JFileChooser fc = new JFileChooser(); int result = fc.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); CsvParserResult parseResult = CsvParser.AUTOMATIC.parse(new FileReader(selectedFile)); for (int i = 0; i < parseResult.getColumnNames().size(); i++) { String columnName = parseResult.getColumnNames().get(i); Class<?> columnType = parseResult.getColumnTypes().get(i); if (columnType == String.class) { System.out.println(columnName + " - " + columnType + " - " + nonNumberMatching((List<String>) parseResult.getColumnValues().get(i))); } else { System.out.println(columnName + " - " + columnType); } } } } public static List<String> nonNumberMatching(List<String> strings) { Matcher matcher = Pattern.compile(DOUBLE_REGEX_WITH_NAN).matcher(""); List<String> nonMatching = new ArrayList<>(); for (String string : strings) { if (!matcher.reset(string).matches()) { nonMatching.add(string); } } return nonMatching; } }
mit
yext/serialization
src/com/yext/serialization/js/JsonUtil.java
1572
package com.yext.serialization.js; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * Helper class for dealing with json objects. * * @author Kevin Caffrey (kevin@yext.com) */ public class JsonUtil { /** * Converts a json object into a representation suitable for soy data. Objects * are represented by maps, and arrays are represented by lists. Primitives are * kept as-is. */ public static Object jsonToSoyData(Object obj) throws JSONException { if (obj instanceof JSONObject) { // Convert the object to a map JSONObject json = (JSONObject)obj; Map<String, Object> map = Maps.newHashMap(); JSONArray names = json.names(); for (int i = 0; i < names.length(); i++) { String name = names.getString(i); map.put(name, jsonToSoyData(json.get(name))); } return map; } else if (obj instanceof JSONArray) { // Conver the object to an array list JSONArray array = (JSONArray)obj; List<Object> list = Lists.newArrayListWithExpectedSize(array.length()); for (int i = 0; i < array.length(); i++) { list.add(jsonToSoyData(array.get(i))); } return list; } else { return obj; } } }
mit
simple-elf/selenide
src/main/java/com/codeborne/selenide/impl/LastCollectionElement.java
1856
package com.codeborne.selenide.impl; import com.codeborne.selenide.Condition; import com.codeborne.selenide.Driver; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.ex.ElementNotFound; import org.openqa.selenium.WebElement; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import java.lang.reflect.Proxy; import java.util.List; import static com.codeborne.selenide.Condition.visible; @ParametersAreNonnullByDefault public class LastCollectionElement extends WebElementSource { public static SelenideElement wrap(CollectionSource collection) { return (SelenideElement) Proxy.newProxyInstance( collection.getClass().getClassLoader(), new Class<?>[]{SelenideElement.class}, new SelenideElementProxy(new LastCollectionElement(collection))); } private final CollectionSource collection; LastCollectionElement(CollectionSource collection) { this.collection = collection; } @Override @CheckReturnValue @Nonnull public Driver driver() { return collection.driver(); } @Override @CheckReturnValue @Nonnull public WebElement getWebElement() { return lastElementOf(collection.getElements()); } private <T> T lastElementOf(List<T> collection) { return collection.get(collection.size() - 1); } @Override @CheckReturnValue @Nonnull public String getSearchCriteria() { return collection.description() + ":last"; } @Override @CheckReturnValue @Nonnull public ElementNotFound createElementNotFoundError(Condition condition, Throwable lastError) { if (collection.getElements().isEmpty()) { return new ElementNotFound(collection.driver(), description(), visible, lastError); } return super.createElementNotFoundError(condition, lastError); } }
mit
thbrown/SoftballSim
src/com/github/thbrown/softballsim/lineup/BattingLineup.java
1462
package com.github.thbrown.softballsim.lineup; import java.util.List; import java.util.stream.Collectors; import com.github.thbrown.softballsim.data.gson.DataPlayer; import com.github.thbrown.softballsim.data.gson.DataStats; /** * Implementers must make sure this their implementations are immutable. */ public interface BattingLineup { /** * Representation of this lineup as a simple list of players. As you'd write is on a lineup card. */ public List<DataPlayer> asList(); /** * Same as {@link #asList()}, but returns a list of playerIds instead of DataPlayer objects */ public default List<String> asListOfIds() { return asList().stream().map(p -> p.getId()).collect(Collectors.toList()); }; /** * Gets the batter at given index in the lineup */ public DataPlayer getBatter(int index); /** * String used to identify the type of lineup during serialization/deserialization * * @return */ public default String getLineupType() { return this.getClass().getSimpleName(); } /** * Player statistics aren't stored in serialized result data. So players will appear to have no * stats after deserialization. This method replaces the players that have empty stats objects with * their counterparts from DataStats that do have stats info. */ public void populateStats(DataStats battingData); public void populateStats(List<DataPlayer> playersWithStatsData); public int size(); }
mit
siepet/TAJmahal
Projekt2/src/testsuite/PsikusTestSuite.java
224
package testsuite; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ cyfroTest.class, hultajTest.class, niekszTest.class }) public class PsikusTestSuite { }
mit
Ernestyj/JDesignPatternStudy
src/eugene/creational/prototype/AppTest.java
221
package eugene.creational.prototype; import org.junit.Test; /** * Created by Jian on 2015/7/28. */ public class AppTest { @Test public void test() { String[] args = {}; App.main(args); } }
mit
atealxt/work-workspaces
jbpmDemo/officialdemo/org/jbpm/examples/custom/PrintDots.java
3206
/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jbpm.examples.custom; import java.util.Map; import org.jbpm.api.activity.ActivityExecution; import org.jbpm.api.activity.ExternalActivityBehaviour; /** * @author Tom Baeyens */ public class PrintDots implements ExternalActivityBehaviour { private static final long serialVersionUID = 1L; private static final String NEWLINE = System.getProperty("line.separator"); public void execute(ActivityExecution execution) { String executionId = execution.getId(); String dots = " "+".::::. " + NEWLINE + " " +" " +" .:::::" +":::. " + NEWLINE + " ::::::::::: " + NEWLINE + " " + " ':::::::::::.. " + NEWLINE +" ::::" +":::::::::::' " + NEWLINE +" ':::::::::::. " + NEWLINE + " .::::::::" +"::::::' " + NEWLINE +" " +".:::::::::::... " + NEWLINE + " ::::::::::::::''" + " " + NEWLINE +" .:::. '::::::::'':::: " + NEWLINE + " .::::::::. " + " ':::::' ':::: " + NEWLINE +" " +".::::':::::::. " +" ::::: '::::. " + NEWLINE +" .:::::' '::::" +":::::. ::::: ':::. " + NEWLINE +" .:::::' ':::::::::.::::: " +" '::. " + NEWLINE +" .::::'' ':::::::::::::: '::. " + NEWLINE +" .::'' ':::::" +"::::::: :::... " + NEWLINE +" ..:::: ':::::::::' " + " .:' '''' " + NEWLINE +" ..''''':' ':::::.' " + NEWLINE; System.out.println(dots); execution.waitForSignal(); } public void signal(ActivityExecution execution, String signalName, Map<String, ?> parameters) { execution.take(signalName); } }
mit
juniormesquitadandao/report4all
lib/src/net/sf/jasperreports/util/CastorUtil.java
9394
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.util; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.Writer; import java.util.List; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRRuntimeException; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.util.JRLoader; import org.exolab.castor.mapping.Mapping; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; import org.exolab.castor.xml.XMLContext; import org.w3c.dom.Node; import org.xml.sax.InputSource; /** * @author Teodor Danciu (teodord@users.sourceforge.net) * @version $Id: CastorUtil.java 7199 2014-08-27 13:58:10Z teodord $ */ public class CastorUtil { /** * */ private static final String CASTOR_XML_CONTEXT_KEY = "net.sf.jasperreports.castor.xml.context"; private JasperReportsContext jasperReportsContext; /** * */ private CastorUtil(JasperReportsContext jasperReportsContext) { this.jasperReportsContext = jasperReportsContext; } /** * */ public static CastorUtil getInstance(JasperReportsContext jasperReportsContext) { return new CastorUtil(jasperReportsContext); } /** * */ private XMLContext getXmlContext() { XMLContext xmlContext = (XMLContext)jasperReportsContext.getValue(CASTOR_XML_CONTEXT_KEY); if (xmlContext == null) { xmlContext = new XMLContext(); Mapping mapping = xmlContext.createMapping(); List<CastorMapping> castorMappings = jasperReportsContext.getExtensions(CastorMapping.class); for (CastorMapping castorMapping : castorMappings) { loadMapping(mapping, castorMapping.getPath()); } try { xmlContext.addMapping(mapping); } catch (MappingException e) { throw new JRRuntimeException("Failed to load Castor mappings", e); } jasperReportsContext.setValue(CASTOR_XML_CONTEXT_KEY, xmlContext); } return xmlContext; } /** * */ private void loadMapping(Mapping mapping, String mappingFile) { try { byte[] mappingFileData = JRLoader.loadBytesFromResource(mappingFile); InputSource mappingSource = new InputSource(new ByteArrayInputStream(mappingFileData)); mapping.loadMapping(mappingSource); } catch (JRException e) { throw new JRRuntimeException(e); } } /** * */ public static Object read(InputStream is, String mappingFile) { Object object = null; InputStream mis = null; try { mis = JRLoader.getLocationInputStream(mappingFile); Mapping mapping = new Mapping(); mapping.loadMapping( new InputSource(mis) ); object = read(is, mapping); } catch (JRException e) { throw new JRRuntimeException(e); } finally { if (mis != null) { try { mis.close(); } catch(IOException e) { } } } return object; } /** * */ public static Object read(Node node, String mappingFile) { Object object = null; InputStream mis = null; try { mis = JRLoader.getLocationInputStream(mappingFile); Mapping mapping = new Mapping(); mapping.loadMapping( new InputSource(mis) ); object = read(node, mapping); } catch (JRException e) { throw new JRRuntimeException(e); } finally { if (mis != null) { try { mis.close(); } catch(IOException e) { } } } return object; } /** * */ public static Object read(InputStream is, Mapping mapping) { Object object = null; try { Unmarshaller unmarshaller = new Unmarshaller(mapping);//FIXME initialization is not thread safe unmarshaller.setWhitespacePreserve(true); object = unmarshaller.unmarshal(new InputSource(is)); } catch (MappingException e) { throw new JRRuntimeException(e); } catch (MarshalException e) { throw new JRRuntimeException(e); } catch (ValidationException e) { throw new JRRuntimeException(e); } return object; } /** * */ public Object read(InputStream is) { try { Unmarshaller unmarshaller = getXmlContext().createUnmarshaller();//FIXME initialization is not thread safe unmarshaller.setWhitespacePreserve(true); Object object = unmarshaller.unmarshal(new InputSource(is)); return object; } catch (MarshalException e) { throw new JRRuntimeException(e); } catch (ValidationException e) { throw new JRRuntimeException(e); } } /** * */ public static Object read(Node node, Mapping mapping) { Object object = null; try { Unmarshaller unmarshaller = new Unmarshaller(mapping); unmarshaller.setWhitespacePreserve(true); object = unmarshaller.unmarshal(node); } catch (MappingException e) { throw new JRRuntimeException(e); } catch (MarshalException e) { throw new JRRuntimeException(e); } catch (ValidationException e) { throw new JRRuntimeException(e); } return object; } /** * */ public static Object read(InputStream is, Class<?> clazz) { return read(is, getMappingFileName(clazz)); } /** * */ public static Object read(Node node, Class<?> clazz) { return read(node, getMappingFileName(clazz)); } /** * */ public static void write(Object object, String mappingFile, Writer writer) { InputStream mis = null; try { mis = JRLoader.getLocationInputStream(mappingFile); Mapping mapping = new Mapping(); mapping.loadMapping( new InputSource(mis) ); write(object, mapping, writer); } catch (JRException e) { throw new JRRuntimeException(e); } finally { if (mis != null) { try { mis.close(); } catch(IOException e) { } } } } /** * */ public static void write(Object object, Mapping mapping, Writer writer) { try { Marshaller marshaller = new Marshaller(writer); marshaller.setMapping(mapping); marshaller.setMarshalAsDocument(false); marshaller.marshal(object); } catch (IOException e) { throw new JRRuntimeException(e); } catch (MappingException e) { throw new JRRuntimeException(e); } catch (MarshalException e) { throw new JRRuntimeException(e); } catch (ValidationException e) { throw new JRRuntimeException(e); } } /** * */ public static void write(Object object, String mappingFile, File file) { Writer writer = null; try { writer = new FileWriter(file); write(object, mappingFile, writer); } catch (IOException e) { throw new JRRuntimeException(e); } finally { if (writer != null) { try { writer.close(); } catch(IOException e) { } } } } /** * */ public static void write(Object object, Mapping mapping, File file) { Writer writer = null; try { writer = new FileWriter(file); write(object, mapping, writer); } catch (IOException e) { throw new JRRuntimeException(e); } finally { if (writer != null) { try { writer.close(); } catch(IOException e) { } } } } /** * */ public static String write(Object object, String mappingFile) { StringWriter writer = new StringWriter(); try { write(object, mappingFile, writer); } finally { try { writer.close(); } catch(IOException e) { } } return writer.toString(); } /** * */ public static String write(Object object, Mapping mapping) { StringWriter writer = new StringWriter(); try { write(object, mapping, writer); } finally { try { writer.close(); } catch(IOException e) { } } return writer.toString(); } /** * */ public static String write(Object object) { StringWriter writer = new StringWriter(); try { write(object, getMappingFileName(object.getClass()), writer); } finally { try { writer.close(); } catch(IOException e) { } } return writer.toString(); } /** * */ private static String getMappingFileName(Class<?> clazz) { return clazz.getName().replace(".", "/") + ".xml"; } }
mit
codenameflip/ChatChannels
src/main/java/com/codenameflip/chatchannels/commands/ChatChannelsCommand.java
543
package com.codenameflip.chatchannels.commands; import com.codenameflip.chatchannels.ChatChannels; import com.codenameflip.chatchannels.structure.IChannelRegistry; import org.bukkit.command.CommandExecutor; /** * ChatChannels * * @author Cameron Fletcher * @since 06/03/2018 */ public interface ChatChannelsCommand extends CommandExecutor { default ChatChannels get() { return ChatChannels.getInstance(); } default IChannelRegistry getRegistry() { return ChatChannels.getInstance().getRegistry(); } }
mit
antalpeti/Java-Tutorial
src/com/tutorialspoint/multithreading/package-info.java
9567
/** * Contains some examples about Multithreading topic. * * <head> <link rel="stylesheet" type="text/css" href="../../../../files/mystyle.css"></head> * <p> * Java is a<i>multithreaded programming language</i> which means we can develop multithreaded * program using Java. A multithreaded program contains two or more parts that can run concurrently * and each part can handle different task at the same time making optimal use of the available * resources specially when your computer has multiple CPUs. * </p> * <p> * By definition multitasking is when multiple processes share common processing resources such as a * CPU. Multithreading extends the idea of multitasking into applications where you can subdivide * specific operations within a single application into individual threads. Each of the threads can * run in parallel. The OS divides processing time not only among different applications, but also * among each thread within an application. * </p> * <p> * Multithreading enables you to write in a way where multiple activities can proceed concurrently * in the same program. * </p> * * <h2>Life Cycle of a Thread:</h2> * <p> * A thread goes through various stages in its life cycle. For example, a thread is born, started, * runs, and then dies. Following diagram shows complete life cycle of a thread. * </p> * * <img src="java_thread.jpg" alt="Java Thread" width="100%"> </center> * <p> * Above-mentioned stages are explained here: * </p> * <ul> * <li> * <p> * <b>New:</b> A new thread begins its life cycle in the new state. It remains in this state until * the program starts the thread. It is also referred to as a born thread. * </p> * </li> * <li> * <p> * <b>Runnable:</b> After a newly born thread is started, the thread becomes runnable. A thread in * this state is considered to be executing its task. * </p> * </li> * <li> * <p> * <b>Waiting:</b> Sometimes, a thread transitions to the waiting state while the thread waits for * another thread to perform a task.A thread transitions back to the runnable state only when * another thread signals the waiting thread to continue executing. * </p> * </li> * <li> * <p> * <b>Timed waiting:</b> A runnable thread can enter the timed waiting state for a specified * interval of time. A thread in this state transitions back to the runnable state when that time * interval expires or when the event it is waiting for occurs. * </p> * </li> * <li> * <p> * <b>Terminated: </b> A runnable thread enters the terminated state when it completes its task or * otherwise terminates. * </p> * </li> * </ul> * * <h2>Thread Priorities:</h2> * <p> * Every Java thread has a priority that helps the operating system determine the order in which * threads are scheduled. * </p> * <p> * Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY * (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). * </p> * <p> * Threads with higher priority are more important to a program and should be allocated processor * time before lower-priority threads. However, thread priorities cannot guarantee the order in * which threads execute and very much platform dependentant. * </p> * * <h2>Create Thread by Implementing Runnable Interface:</h2> * <p> * If your class is intended to be executed as a thread then you can achieve this by implementing * <b>Runnable</b> interface. You will need to follow three basic steps: * </p> * * <h3>Step 1:</h3> * <p> * As a first step you need to implement a run() method provided by <b>Runnable</b> interface. This * method provides entry point for the thread and you will put you complete business logic inside * this method. Following is simple syntax of run() method: * </p> * * <pre> * <span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">(</span><span class="pln"> </span><span class="pun">)</span> * </pre> * * <h3>Step 2:</h3> * <p> * At second step you will instantiate a <b>Thread</b> object using the following constructor: * </p> * * <pre> * <span class="typ">Thread</span><span class="pun">(</span><span class="typ">Runnable</span><span class="pln"> threadObj</span><span class="pun">,</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> threadName</span><span class="pun">);</span> * </pre> * <p> * Where, <i>threadObj</i> is an instance of a class that implements the <b>Runnable</b> interface * and <b>threadName</b> is the name given to the new thread. * </p> * <h3>Step 3</h3> * <p> * Once Thread object is created, you can start it by calling <b>start( )</b> method, which executes * a call to run( ) method. Following is simple syntax of start() method: * </p> * * <h2>Create Thread by Extending Thread Class:</h2> * <p> * The second way to create a thread is to create a new class that extends <b>Thread</b> class using * the following two simple steps. This approach provides more flexibility in handling multiple * threads created using available methods in Thread class. * </p> * <h3>Step 1</h3> * <p> * You will need to override <b>run( )</b> method available in Thread class. This method provides * entry point for the thread and you will put you complete business logic inside this method. * Following is simple syntax of run() method: * </p> * * <pre> * <span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">(</span><span class="pln"> </span><span class="pun">)</span> * </pre> * * <h3>Step 2</h3> * <p> * Once Thread object is created, you can start it by calling <b>start( )</b> method, which executes * a call to run( ) method. Following is simple syntax of start() method: * </p> * * <h2>Thread Methods:</h2> * <p> * Following is the list of important methods available in the Thread class. * </p> * <table> * <tbody> * <tr> * <th>SN</th> * <th>Methods with Description</th> * </tr> * <tr> * <td>1</td> * <td><b>public void start()</b> * <p> * Starts the thread in a separate path of execution, then invokes the run() method on this Thread * object. * </p> * </td> * </tr> * <tr> * <td>2</td> * <td><b>public void run()</b> * <p> * If this Thread object was instantiated using a separate Runnable target, the run() method is * invoked on that Runnable * </p> * object.</td> * </tr> * <tr> * <td>3</td> * <td><b>public final void setName(String name)</b> * <p> * Changes the name of the Thread object. There is also a getName() method for retrieving the name. * </p> * </td> * </tr> * <tr> * <td>4</td> * <td><b>public final void setPriority(int priority)</b> * <p> * Sets the priority of this Thread object. The possible values are between 1 and 10. * </p> * </td> * </tr> * <tr> * <td>5</td> * <td><b>public final void setDaemon(boolean on)</b> * <p> * A parameter of true denotes this Thread as a daemon thread. * </p> * </td> * </tr> * <tr> * <td>6</td> * <td><b>public final void join(long millisec)</b> * <p> * The current thread invokes this method on a second thread, causing the current thread to block * until the second thread terminates or the specified number of milliseconds passes. * </p> * </td> * </tr> * <tr> * <td>7</td> * <td><b>public void interrupt()</b> * <p> * Interrupts this thread, causing it to continue execution if it was blocked for any reason. * </p> * </td> * </tr> * <tr> * <td>8</td> * <td><b>public final boolean isAlive()</b> * <p> * Returns true if the thread is alive, which is any time after the thread has been started but * before it runs to completion. * </p> * </td> * </tr> * </tbody> * </table> * * <p> * The previous methods are invoked on a particular Thread object. The following methods in the * Thread class are static. Invoking one of the static methods performs the operation on the * currently running thread. * </p> * <table> * <tbody> * <tr> * <th>SN</th> * <th>Methods with Description</th> * </tr> * <tr> * <td>1</td> * <td><b>public static void yield()</b> * <p> * Causes the currently running thread to yield to any other threads of the same priority that are * waiting to be scheduled. * </p> * </td> * </tr> * <tr> * <td>2</td> * <td><b>public static void sleep(long millisec)</b> * <p> * Causes the currently running thread to block for at least the specified number of milliseconds. * </p> * </td> * </tr> * <tr> * <td>3</td> * <td><b>public static boolean holdsLock(Object x)</b> * <p> * Returns true if the current thread holds the lock on the given Object. * </p> * </td> * </tr> * <tr> * <td>4</td> * <td><b>public static Thread currentThread()</b> * <p> * Returns a reference to the currently running thread, which is the thread that invokes this * method. * </p> * </td> * </tr> * <tr> * <td>5</td> * <td><b>public static void dumpStack()</b> * <p> * Prints the stack trace for the currently running thread, which is useful when debugging a * multithreaded application. * </p> * </td> * </tr> * </tbody> * </table> */ package com.tutorialspoint.multithreading;
mit
chorsystem/middleware
messages/src/main/java/org/apache/ode/pmapi/RecoverActivityResponse.java
1691
package org.apache.ode.pmapi; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.ode.pmapi.types._2006._08._02.TInstanceInfo; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="instance-info" type="{http://www.apache.org/ode/pmapi/types/2006/08/02/}tInstanceInfo" form="unqualified"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "instanceInfo" }) @XmlRootElement(name = "recoverActivityResponse") public class RecoverActivityResponse { @XmlElement(name = "instance-info", required = true) protected TInstanceInfo instanceInfo; /** * Gets the value of the instanceInfo property. * * @return * possible object is * {@link TInstanceInfo } * */ public TInstanceInfo getInstanceInfo() { return instanceInfo; } /** * Sets the value of the instanceInfo property. * * @param value * allowed object is * {@link TInstanceInfo } * */ public void setInstanceInfo(TInstanceInfo value) { this.instanceInfo = value; } }
mit
ailyenko/JavaRush
src/com/javarush/test/level26/lesson15/big01/exception/InterruptOperationException.java
212
package com.javarush.test.level26.lesson15.big01.exception; /** * Created by Alex on 28.04.2014. */ public class InterruptOperationException extends Exception { public InterruptOperationException() { } }
mit
RestrictedZone/2016_OOP_study
Jongwon/Java-bucket/src/main/coupon/CouponList.java
653
package main.coupon; import java.util.ArrayList; import java.util.List; /** * Created by lasto on 2016-12-09. * 좀 더 나은 방법이 없을까(Grouping) */ public class CouponList { private Coupon c1 = new C1(); private Coupon c1_1 = new C1_1(); private Coupon c2 = new C2(); private Coupon c3 = new C3(); public List<Coupon> getList(){ return getAllList(); } private List<Coupon> getAllList(){ List<Coupon> couponList = new ArrayList<Coupon>(); couponList.add(c1); couponList.add(c1_1); couponList.add(c2); couponList.add(c3); return couponList; } }
mit
tedliang/osworkflow
src/test/com/opensymphony/workflow/JoinTestCase.java
1018
/* * Copyright (c) 2002-2003 by OpenSymphony * All rights reserved. */ package com.opensymphony.workflow; import com.opensymphony.workflow.basic.BasicWorkflow; import junit.framework.TestCase; /** * @author hani Date: Feb 17, 2005 Time: 4:24:20 PM */ public class JoinTestCase extends TestCase { //~ Instance fields //////////////////////////////////////////////////////// private Workflow workflow; //~ Methods //////////////////////////////////////////////////////////////// public void testWithReject() throws Exception { checkRoute(new int[] {2, 3, 2, 4, 6, 7}); } protected void setUp() throws Exception { workflow = new BasicWorkflow("testuser"); } private void checkRoute(int[] actions) throws Exception { long workflowId = workflow.initialize(getClass().getResource("/samples/join.xml").toString(), 1, null); for (int i = 0; i < actions.length; i++) { workflow.doAction(workflowId, actions[i], null); } } }
mit
girinoboy/lojacasamento
lojacasamento-core/src/main/java/br/com/mb/GenericMB.java
4435
package br.com.mb; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.Date; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.servlet.http.HttpSession; import org.joda.time.LocalDate; import br.com.dao.GenericDAO; import br.com.dto.GenericDTO; @SuppressWarnings("unchecked") public class GenericMB<T> implements Serializable{ protected static final Logger LOGGER = Logger.getLogger( GenericMB.class.getName() ); /** * */ private static final long serialVersionUID = 1L; protected ResourceBundle rb; // private Class<T> oclass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; //@Inject protected GenericDAO<T, Serializable> abstractDAO; // @EJB // protected GenericService<T, Serializable> abstractService; protected T abstractDTO; protected List<T> abstractList; private Date currentDate = LocalDate.now().toDate(); protected Boolean visualizar; protected Boolean alterar; protected Boolean novo; public void inicio() throws Exception{ abstractList = abstractDAO.list(abstractDTO); if(!abstractList.isEmpty()){ abstractDTO = abstractList.iterator().next(); } } public GenericMB() { FacesContext fc = FacesContext.getCurrentInstance(); if(fc.getViewRoot() != null) rb = ResourceBundle.getBundle("messages",fc.getViewRoot().getLocale()); Class<T> oclass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; if(abstractDAO == null){ abstractDAO = new GenericDAO<T, Serializable>(oclass); } try { abstractDTO = oclass.newInstance(); abstractList = abstractDAO.list();// } catch (Exception e) { e.printStackTrace(); String msg = e.getMessage(); Exception thrown = e; Level level = Level.SEVERE; LOGGER.log(level, msg, thrown); } } public void editar(){ } public String redirecionar(String url) throws IOException{ FacesContext.getCurrentInstance().getExternalContext().redirect(url); System.out.println(abstractDTO); return url; } public GenericDTO getUserSession(){ HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); return ((GenericDTO) session.getAttribute("usuarioAutenticado")); } public List<GenericDTO> getMenuSession(){ HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); return (List<GenericDTO>) session.getAttribute("listMenuAutenticado"); } public List<GenericDTO> getPerfilSession(){ HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); return (List<GenericDTO>) session.getAttribute("listPerfilAutenticado"); } //metodo generico que envia mesagens para a tela public void addMessage(FacesMessage message) { FacesContext.getCurrentInstance().addMessage(null, message); } public void addMessage(String summary) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null); FacesContext.getCurrentInstance().addMessage(null, message); } public void addMessage(String summary,String detail) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, detail); FacesContext.getCurrentInstance().addMessage(null, message); } public List<T> getAbstractList() { return abstractList; } public void setAbstractList(List<T> abstractList) { this.abstractList = abstractList; } public T getAbstractDTO() { return abstractDTO; } public void setAbstractDTO(T abstractDTO) { this.abstractDTO = abstractDTO; } public Boolean getVisualizar() { return visualizar; } public void setVisualizar(Boolean visualizar) { this.visualizar = visualizar; } public Boolean getAlterar() { return alterar; } public void setAlterar(Boolean alterar) { this.alterar = alterar; } public Boolean getNovo() { return novo; } public void setNovo(Boolean novo) { this.novo = novo; } public Date getCurrentDate() { return currentDate; } public void setCurrentDate(Date currentDate) { this.currentDate = currentDate; } }
mit
RaghavPro/bookstore
src/main/java/com/raghavpro/bookhive/models/service/BookService.java
3607
package com.raghavpro.bookhive.models.service; import com.raghavpro.bookhive.Constants; import com.raghavpro.bookhive.models.Book; import com.raghavpro.bookhive.models.Review; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; /** * Gets the book details and stores it in {@code Book} bean and then returns an {@code ArrayList}. * * First, the query gets executed and the we get the {@code ResultSet} object. Then we iterate on the {@code ResultSet} * and get the desired columns store it in a bean and then add it to an {@code ArrayList}. * We also execute a query to get review data from the reviews table for each result. * * @author Raghav (Email: Raghav.Sharma@Outlook.in) */ public class BookService extends Service<Book> { /** * Constructs a new {@code Service} * * @param conn The connection object. */ public BookService(Connection conn) { super(conn); } @Override public List<Book> get(Object[] args, String query, Object... queryParams) { List<Book> books = null; ResultSet rs = null; try { /* Executes the query */ rs = execute(query, queryParams); if (rs == null) return null; // idk? books = new ArrayList<>(); ReviewService service = new ReviewService(conn); while (rs.next()) { String isbn = rs.getString("isbn"); String title = rs.getString("title"); String author = rs.getString("author"); int price = rs.getInt("price"); int mrp = rs.getInt("mrp"); String pages = rs.getString("pages"); String language = rs.getString("lang"); String dimensions = rs.getString("dimensions"); String publisher = rs.getString("publisher"); String summary = rs.getString("summary"); String aboutAuthor = rs.getString("about_author"); String review = rs.getString("review"); Book book = new Book(); book.setIsbn(isbn); book.setTitle(title); book.setAuthor(author); book.setPrice(price); book.setMrp(mrp); book.setPages(pages); book.setLanguage(language); book.setDimensions(dimensions); book.setPublisher(publisher); book.setSummary(summary); book.setAboutAuthor(aboutAuthor); book.setReview(review); query = "SELECT * FROM review WHERE isbn = ?"; List<Review> user_reviews = service.get(null, query, isbn); book.setUserReviews(user_reviews); book.setNoOfReviews(user_reviews.size()); for (Review user_review : user_reviews) book.setTotalStars(book.getTotalStars() + user_review.getStars()); books.add(book); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return books; } @Override public boolean dataManipulation(String query, Object... queryParams) { return false; } }
mit
willem-vanheemstrasystems/java-headstart
bucky/src/bucky/GUIFiftySix.java
1412
package bucky; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class GUIFiftySix extends JFrame { // Variables private JTextField addressBar; private JEditorPane display; // Constructor public GUIFiftySix(){ super("the Title"); // Create address bar addressBar = new JTextField("Enter a URL"); // Capture on press enter event addressBar.addActionListener( // Anonymous inner class new ActionListener(){ // Overwrite method public void actionPerformed(ActionEvent event){ // Pass URL to loadPage method loadPage(event.getActionCommand()); } } ); add(addressBar, BorderLayout.NORTH); // Create display display = new JEditorPane(); display.setEditable(false); // Make links respond to click display.addHyperlinkListener( // Anonymous inner class new HyperlinkListener(){ // Overwrite method public void hyperlinkUpdate(HyperlinkEvent event){ // Act on clicks only if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED) loadPage(event.getURL().toString()); } } ); add(new JScrollPane(display), BorderLayout.CENTER); setSize(500, 300); setVisible(true); } // Method private void loadPage(String link){ try{ display.setPage(link); addressBar.setText(link); }catch(Exception ex){ System.out.println("An exception was caught."); } } }
mit
alvarolobato/pipeline-maven-plugin
maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/JarJarExecutionHandler.java
2126
/* * The MIT License * * Copyright (c) 2016, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.pipeline.maven.eventspy.handler; import org.apache.maven.execution.ExecutionEvent; import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; /** * @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a> */ public class JarJarExecutionHandler extends AbstractExecutionHandler { public JarJarExecutionHandler(MavenEventReporter reporter) { super(reporter); } @Override protected ExecutionEvent.Type getSupportedType() { return ExecutionEvent.Type.MojoSucceeded; } @Nullable @Override protected String getSupportedPluginGoal() { return "org.apache.maven.plugins:maven-jar-plugin:jar"; } @Override protected List<String> getConfigurationParametersToReport(ExecutionEvent executionEvent) { return Arrays.asList("finalName", "outputDirectory"); } }
mit
MatthijsKamstra/haxejava
02Surface/code/bin/java/src/haxe/lang/HxObject.java
4642
// Generated by Haxe 3.3.0 package haxe.lang; import haxe.root.*; @SuppressWarnings(value={"rawtypes", "unchecked"}) public class HxObject implements haxe.lang.IHxObject { public HxObject(haxe.lang.EmptyObject empty) { } public HxObject() { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" haxe.lang.HxObject.__hx_ctor_haxe_lang_HxObject(this); } public static void __hx_ctor_haxe_lang_HxObject(haxe.lang.HxObject __temp_me9) { } public static java.lang.Object __hx_createEmpty() { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return new haxe.lang.HxObject(haxe.lang.EmptyObject.EMPTY); } public static java.lang.Object __hx_create(haxe.root.Array arr) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return new haxe.lang.HxObject(); } public boolean __hx_deleteField(java.lang.String field) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return false; } public java.lang.Object __hx_lookupField(java.lang.String field, boolean throwErrors, boolean isCheck) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" if (isCheck) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return haxe.lang.Runtime.undefined; } else { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" if (throwErrors) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" throw haxe.lang.HaxeException.wrap("Field not found."); } else { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return null; } } } public double __hx_lookupField_f(java.lang.String field, boolean throwErrors) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" if (throwErrors) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" throw haxe.lang.HaxeException.wrap("Field not found or incompatible field type."); } else { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return 0.0; } } public java.lang.Object __hx_lookupSetField(java.lang.String field, java.lang.Object value) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" throw haxe.lang.HaxeException.wrap("Cannot access field for writing."); } public double __hx_lookupSetField_f(java.lang.String field, double value) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" throw haxe.lang.HaxeException.wrap("Cannot access field for writing or incompatible type."); } public double __hx_setField_f(java.lang.String field, double value, boolean handleProperties) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return this.__hx_lookupSetField_f(field, value); } } } public java.lang.Object __hx_setField(java.lang.String field, java.lang.Object value, boolean handleProperties) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return this.__hx_lookupSetField(field, value); } } } public java.lang.Object __hx_getField(java.lang.String field, boolean throwErrors, boolean isCheck, boolean handleProperties) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return this.__hx_lookupField(field, throwErrors, isCheck); } } } public double __hx_getField_f(java.lang.String field, boolean throwErrors, boolean handleProperties) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return this.__hx_lookupField_f(field, throwErrors); } } } public java.lang.Object __hx_invokeField(java.lang.String field, haxe.root.Array dynargs) { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" { //line 30 "/usr/local/lib/haxe/std/java/internal/HxObject.hx" return ((haxe.lang.Function) (this.__hx_getField(field, true, false, false)) ).__hx_invokeDynamic(dynargs); } } } public void __hx_getFields(haxe.root.Array<java.lang.String> baseArr) { } }
mit
aleen42/SimpChat
src/com/java/ui/componentc/JCSeparator.java
416
package com.java.ui.componentc; import javax.swing.*; public class JCSeparator extends JSeparator { private static final long serialVersionUID = -2404686601191054374L; public JCSeparator() { this(0); } public JCSeparator(int orientation) { super(orientation); setUI(new CSeparatorUI()); setOpaque(false); } @Deprecated public void updateUI() { } }
mit
MikeMirzayanov/pbox
src/site/src/main/java/me/pbox/site/index/IllegalQueryException.java
333
package me.pbox.site.index; /** * @author Mike Mirzayanov (mirzayanovmr@gmail.com) */ public class IllegalQueryException extends Exception { public IllegalQueryException(String message) { super(message); } public IllegalQueryException(String message, Throwable cause) { super(message, cause); } }
mit
FTC7393/EVLib
EVLib/src/main/java/ftc/evlib/vision/processors/BeaconColorResult.java
2523
package ftc.evlib.vision.processors; import org.opencv.core.Scalar; import ftc.electronvolts.util.TeamColor; import ftc.evlib.vision.ImageUtil; /** * This file was made by the electronVolts, FTC team 7393 * Date Created: 8/17/16. * * Storage class for the color of the beacon */ public class BeaconColorResult { /** * Storage class for the color of one beacon */ public enum BeaconColor { RED(ImageUtil.RED, "R"), GREEN(ImageUtil.GREEN, "G"), BLUE(ImageUtil.BLUE, "B"), UNKNOWN(ImageUtil.BLACK, "?"); public final Scalar color; public final String letter; BeaconColor(Scalar scalar, String letter) { this.color = scalar; this.letter = letter; } /** * Converts a TeamColor to a BeaconColor * * @param teamColor the TeamColor to convert * @return the corresponding BeaconColor */ public static BeaconColor fromTeamColor(TeamColor teamColor) { switch (teamColor) { case RED: return RED; case BLUE: return BLUE; default: return UNKNOWN; } } /** * @return the TeamColor corresponding to this BeaconColor */ public BeaconColor toTeamColor() { return toTeamColor(this); } /** * Converts a BeaconColor to a TeamColor * * @param beaconColor the BeaconColor to convert * @return the corresponding TeamColor */ public static BeaconColor toTeamColor(BeaconColor beaconColor) { switch (beaconColor) { case RED: return RED; case BLUE: return BLUE; default: return UNKNOWN; } } } private final BeaconColor leftColor, rightColor; public BeaconColorResult() { this.leftColor = BeaconColor.UNKNOWN; this.rightColor = BeaconColor.UNKNOWN; } public BeaconColorResult(BeaconColor leftColor, BeaconColor rightColor) { this.leftColor = leftColor; this.rightColor = rightColor; } public String toString() { return leftColor + "|" + rightColor; } public BeaconColor getLeftColor() { return leftColor; } public BeaconColor getRightColor() { return rightColor; } }
mit
fredyw/hackerrank
src/main/java/hackerrank/CutTheTree.java
2396
package hackerrank; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; /** * https://www.hackerrank.com/challenges/cut-the-tree */ public class CutTheTree { private static class Vertex { private final int vertex; private final int value; private int totalValue; public Vertex(int vertex, int value) { this.vertex = vertex; this.value = value; } } private static int cutTheTree(Map<Integer, List<Vertex>> adjList, Map<Integer, Vertex> vertices, int totalValue) { int min = Integer.MAX_VALUE; calcTotalValue(adjList, vertices.get(1), new HashSet<>()); // start from the root for (int i = 2; i <= adjList.size(); i++) { int a = vertices.get(i).totalValue; int b = totalValue - a; int diff = Math.abs(a - b); min = Math.min(min, diff); } return min; } private static int calcTotalValue(Map<Integer, List<Vertex>> adjList, Vertex vertex, Set<Integer> marked) { marked.add(vertex.vertex); int totalValue = vertex.value; for (Vertex adj : adjList.get(vertex.vertex)) { if (!marked.contains(adj.vertex)) { totalValue += calcTotalValue(adjList, adj, marked); } } vertex.totalValue = totalValue; return totalValue; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Map<Integer, Vertex> vertices = new HashMap<>(); Map<Integer, List<Vertex>> adjList = new HashMap<>(); int totalValue = 0; for (int i = 1; i <= n; i++) { int val = in.nextInt(); vertices.put(i, new Vertex(i, val)); adjList.put(i, new ArrayList<>()); totalValue += val; } for (int i = 1; i <= n - 1; i++) { int from = in.nextInt(); int to = in.nextInt(); adjList.get(from).add(vertices.get(to)); adjList.get(to).add(vertices.get(from)); } System.out.println(cutTheTree(adjList, vertices, totalValue)); } }
mit
relimited/HearthSim
src/test/java/com/hearthsim/test/minion/TestFlesheatingGhoul.java
7514
package com.hearthsim.test.minion; import com.hearthsim.card.Card; import com.hearthsim.card.Deck; import com.hearthsim.card.basic.minion.BoulderfistOgre; import com.hearthsim.card.basic.minion.RaidLeader; import com.hearthsim.card.basic.minion.StormwindChampion; import com.hearthsim.card.basic.spell.TheCoin; import com.hearthsim.card.classic.minion.common.FlesheatingGhoul; import com.hearthsim.card.classic.minion.common.HarvestGolem; import com.hearthsim.card.classic.minion.common.LootHoarder; import com.hearthsim.card.classic.minion.rare.Abomination; import com.hearthsim.card.minion.Minion; import com.hearthsim.exception.HSException; import com.hearthsim.model.BoardModel; import com.hearthsim.model.PlayerModel; import com.hearthsim.model.PlayerSide; import com.hearthsim.util.tree.HearthTreeNode; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class TestFlesheatingGhoul { private HearthTreeNode board; private PlayerModel currentPlayer; private PlayerModel waitingPlayer; @Before public void setup() throws HSException { Card cards[] = new Card[10]; for (int index = 0; index < 10; ++index) { cards[index] = new TheCoin(); } Deck deck = new Deck(cards); board = new HearthTreeNode(new BoardModel(deck, deck)); currentPlayer = board.data_.getCurrentPlayer(); waitingPlayer = board.data_.getWaitingPlayer(); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new HarvestGolem()); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new RaidLeader()); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new StormwindChampion()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new LootHoarder()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new Abomination()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new RaidLeader()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new BoulderfistOgre()); currentPlayer.setMana((byte) 10); waitingPlayer.setMana((byte) 10); Minion fb = new FlesheatingGhoul(); currentPlayer.placeCardHand(fb); } @Test public void test0() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, 0, board); assertNull(ret); assertEquals(currentPlayer.getHand().size(), 1); assertEquals(currentPlayer.getNumMinions(), 3); assertEquals(waitingPlayer.getNumMinions(), 4); assertEquals(currentPlayer.getMana(), 10); assertEquals(waitingPlayer.getMana(), 10); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(1).getTotalHealth(), 4); assertEquals(currentPlayer.getCharacter(2).getTotalHealth(), 3); assertEquals(currentPlayer.getCharacter(3).getTotalHealth(), 6); assertEquals(waitingPlayer.getCharacter(1).getTotalHealth(), 1); assertEquals(waitingPlayer.getCharacter(2).getTotalHealth(), 4); assertEquals(waitingPlayer.getCharacter(3).getTotalHealth(), 2); assertEquals(waitingPlayer.getCharacter(4).getTotalHealth(), 7); assertEquals(currentPlayer.getCharacter(1).getTotalAttack(), 4); assertEquals(currentPlayer.getCharacter(2).getTotalAttack(), 3); assertEquals(currentPlayer.getCharacter(3).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(1).getTotalAttack(), 3); assertEquals(waitingPlayer.getCharacter(2).getTotalAttack(), 5); assertEquals(waitingPlayer.getCharacter(3).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(4).getTotalAttack(), 7); } @Test public void test1() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, 3, board); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 4); assertEquals(waitingPlayer.getNumMinions(), 4); assertEquals(currentPlayer.getMana(), 7); assertEquals(waitingPlayer.getMana(), 10); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(1).getTotalHealth(), 4); assertEquals(currentPlayer.getCharacter(2).getTotalHealth(), 3); assertEquals(currentPlayer.getCharacter(3).getTotalHealth(), 6); assertEquals(currentPlayer.getCharacter(4).getTotalHealth(), 4); assertEquals(waitingPlayer.getCharacter(1).getTotalHealth(), 1); assertEquals(waitingPlayer.getCharacter(2).getTotalHealth(), 4); assertEquals(waitingPlayer.getCharacter(3).getTotalHealth(), 2); assertEquals(waitingPlayer.getCharacter(4).getTotalHealth(), 7); assertEquals(currentPlayer.getCharacter(1).getAuraHealth(), 1); assertEquals(currentPlayer.getCharacter(2).getAuraHealth(), 1); assertEquals(currentPlayer.getCharacter(3).getAuraHealth(), 0); assertEquals(currentPlayer.getCharacter(4).getAuraHealth(), 1); assertEquals(currentPlayer.getCharacter(1).getTotalAttack(), 4); assertEquals(currentPlayer.getCharacter(2).getTotalAttack(), 3); assertEquals(currentPlayer.getCharacter(3).getTotalAttack(), 7); assertEquals(currentPlayer.getCharacter(4).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(1).getTotalAttack(), 3); assertEquals(waitingPlayer.getCharacter(2).getTotalAttack(), 5); assertEquals(waitingPlayer.getCharacter(3).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(4).getTotalAttack(), 7); //--------------------------------------------------------------- Minion attacker = currentPlayer.getCharacter(3); ret = attacker.attack(PlayerSide.WAITING_PLAYER, 2, board, false); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 3); assertEquals(waitingPlayer.getNumMinions(), 1); assertEquals(currentPlayer.getMana(), 7); assertEquals(waitingPlayer.getMana(), 10); assertEquals(currentPlayer.getHero().getHealth(), 28); //2 damage from Abomination's deathrattle assertEquals(waitingPlayer.getHero().getHealth(), 28); //2 damage from Abomination's deathrattle assertEquals(currentPlayer.getCharacter(1).getTotalHealth(), 2); assertEquals(currentPlayer.getCharacter(2).getTotalHealth(), 1); assertEquals(currentPlayer.getCharacter(3).getTotalHealth(), 2); assertEquals(waitingPlayer.getCharacter(1).getTotalHealth(), 5); assertEquals(currentPlayer.getCharacter(1).getAuraHealth(), 0); assertEquals(currentPlayer.getCharacter(2).getAuraHealth(), 0); assertEquals(currentPlayer.getCharacter(3).getAuraHealth(), 0); assertEquals(currentPlayer.getCharacter(1).getTotalAttack(), 3); assertEquals(currentPlayer.getCharacter(2).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(3).getTotalAttack(), 3 + 4); //4 minions died, including the Stormwind Champion assertEquals(waitingPlayer.getCharacter(1).getTotalAttack(), 6); } }
mit
dotwebstack/dotwebstack-framework
core/src/test/java/org/dotwebstack/framework/core/directives/DirectiveUtilsTest.java
2333
package org.dotwebstack.framework.core.directives; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import graphql.Scalars; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLDirective; import org.dotwebstack.framework.core.InvalidConfigurationException; import org.junit.jupiter.api.Test; class DirectiveUtilsTest { @Test void getStringArgument_returnsString_forPresentArgument() { // Arrange GraphQLDirective directive = GraphQLDirective.newDirective() .name("foo") .argument(GraphQLArgument.newArgument() .name("foo") .type(Scalars.GraphQLString) .valueProgrammatic("bar")) .build(); // Act String value = DirectiveUtils.getArgument(directive, "foo", String.class); // Assert assertThat(value, is(equalTo("bar"))); } @Test void getStringArgument_returnsNull_forAbsentArgument() { // Arrange GraphQLDirective directive = GraphQLDirective.newDirective() .name("foo") .build(); // Act String value = DirectiveUtils.getArgument(directive, "foo", String.class); // Assert assertThat(value, is(nullValue())); } @Test void getStringArgument_returnsNull_forArgumentWithNullValue() { // Arrange GraphQLDirective directive = GraphQLDirective.newDirective() .name("foo") .argument(GraphQLArgument.newArgument() .name("foo") .type(Scalars.GraphQLString)) .build(); // Act String value = DirectiveUtils.getArgument(directive, "foo", String.class); // Assert assertThat(value, is(nullValue())); } @Test void getStringArgument_throwsException_forMistypedArgument() { // Arrange GraphQLDirective directive = GraphQLDirective.newDirective() .name("foo") .argument(GraphQLArgument.newArgument() .name("foo") .type(Scalars.GraphQLBoolean) .valueProgrammatic(true)) .build(); // Act / Assert assertThrows(InvalidConfigurationException.class, () -> DirectiveUtils.getArgument(directive, "foo", String.class)); } }
mit
VadimDev/Spiky-Project
Spiky_Server/src/main/java/com/spiky/server/utils/CircularArrayList.java
896
/* * Copyright (c) 2017, Vadim Petrov - MIT License */ package com.spiky.server.utils; import java.util.ArrayList; public class CircularArrayList<E> extends ArrayList<E> { private ArrayList<E> list; private int maxSize; public CircularArrayList(int size) { list = new ArrayList<E> (size); maxSize = size; } @Override public int size() { return list.size(); } @Override public boolean add (E objectToAdd) { if (list.size () > maxSize) { list.remove(0); list.add(objectToAdd); } else { list.add(objectToAdd); } return true; } @Override public E get(int i) { return list.get(i); } @Override public String toString() { String str = ""; for (E element : list) str+= "[" + element + "]"; return str; } }
mit
AncientMariner/jax
src/main/java/rest/standalone/JacksonTreeNodeExample.java
1954
package rest.standalone; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; import java.io.*; import java.nio.charset.Charset; import java.util.Iterator; public class JacksonTreeNodeExample { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(); final String FILE_PATH = "/home/xander/IdeaProjects/jax/user.json"; try { InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(FILE_PATH), Charset.defaultCharset()); // BufferedReader fileReader = new BufferedReader(new FileReader(FILE_PATH)); // JsonNode rootNode = mapper.readTree(fileReader); JsonNode rootNode = mapper.readTree(inputStreamReader); /*** read ***/ JsonNode nameNode = rootNode.path("name"); System.out.println(nameNode.getTextValue()); JsonNode ageNode = rootNode.path("age"); System.out.println(ageNode.getIntValue()); JsonNode msgNode = rootNode.path("messages"); Iterator<JsonNode> ite = msgNode.getElements(); while (ite.hasNext()) { JsonNode temp = ite.next(); System.out.println(temp.getTextValue()); } /*** update ***/ ((ObjectNode) rootNode).put("nickname", "new nickname"); ((ObjectNode) rootNode).put("name", "updated name"); ((ObjectNode) rootNode).remove("age"); mapper.writeValue(new File(FILE_PATH), rootNode); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
mit
Mayo-WE01051879/mayosapp
Build/src/main/org/apache/tools/ant/types/TarFileSet.java
7560
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.tools.ant.types; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; /** * A TarFileSet is a FileSet with extra attributes useful in the context of * Tar/Jar tasks. * * A TarFileSet extends FileSets with the ability to extract a subset of the * entries of a Tar file for inclusion in another Tar file. It also includes * a prefix attribute which is prepended to each entry in the output Tar file. * */ public class TarFileSet extends ArchiveFileSet { private boolean userNameSet; private boolean groupNameSet; private boolean userIdSet; private boolean groupIdSet; private String userName = ""; private String groupName = ""; private int uid; private int gid; /** Constructor for TarFileSet */ public TarFileSet() { super(); } /** * Constructor using a fileset argument. * @param fileset the fileset to use */ protected TarFileSet(FileSet fileset) { super(fileset); } /** * Constructor using a tarfileset argument. * @param fileset the tarfileset to use */ protected TarFileSet(TarFileSet fileset) { super(fileset); } /** * The username for the tar entry * This is not the same as the UID. * @param userName the user name for the tar entry. */ public void setUserName(String userName) { checkTarFileSetAttributesAllowed(); userNameSet = true; this.userName = userName; } /** * @return the user name for the tar entry */ public String getUserName() { if (isReference()) { return ((TarFileSet) getCheckedRef()).getUserName(); } return userName; } /** * @return whether the user name has been explicitly set. */ public boolean hasUserNameBeenSet() { return userNameSet; } /** * The uid for the tar entry * This is not the same as the User name. * @param uid the id of the user for the tar entry. */ public void setUid(int uid) { checkTarFileSetAttributesAllowed(); userIdSet = true; this.uid = uid; } /** * @return the uid for the tar entry */ public int getUid() { if (isReference()) { return ((TarFileSet) getCheckedRef()).getUid(); } return uid; } /** * @return whether the user id has been explicitly set. */ public boolean hasUserIdBeenSet() { return userIdSet; } /** * The groupname for the tar entry; optional, default="" * This is not the same as the GID. * @param groupName the group name string. */ public void setGroup(String groupName) { checkTarFileSetAttributesAllowed(); groupNameSet = true; this.groupName = groupName; } /** * @return the group name string. */ public String getGroup() { if (isReference()) { return ((TarFileSet) getCheckedRef()).getGroup(); } return groupName; } /** * @return whether the group name has been explicitly set. */ public boolean hasGroupBeenSet() { return groupNameSet; } /** * The GID for the tar entry; optional, default="0" * This is not the same as the group name. * @param gid the group id. */ public void setGid(int gid) { checkTarFileSetAttributesAllowed(); groupIdSet = true; this.gid = gid; } /** * @return the group identifier. */ public int getGid() { if (isReference()) { return ((TarFileSet) getCheckedRef()).getGid(); } return gid; } /** * @return whether the group id has been explicitly set. */ public boolean hasGroupIdBeenSet() { return groupIdSet; } /** * Create a new scanner. * @return the created scanner. */ protected ArchiveScanner newArchiveScanner() { TarScanner zs = new TarScanner(); return zs; } /** * Makes this instance in effect a reference to another instance. * * <p>You must not set another attribute or nest elements inside * this element if you make it a reference.</p> * @param r the <code>Reference</code> to use. * @throws BuildException on error */ public void setRefid(Reference r) throws BuildException { if (userNameSet || userIdSet || groupNameSet || groupIdSet) { throw tooManyAttributes(); } super.setRefid(r); } /** * A TarFileset accepts another TarFileSet or a FileSet as reference * FileSets are often used by the war task for the lib attribute * @param p the project to use * @return the abstract fileset instance */ protected AbstractFileSet getRef(Project p) { dieOnCircularReference(p); Object o = getRefid().getReferencedObject(p); if (o instanceof TarFileSet) { return (AbstractFileSet) o; } else if (o instanceof FileSet) { TarFileSet zfs = new TarFileSet((FileSet) o); configureFileSet(zfs); return zfs; } else { String msg = getRefid().getRefId() + " doesn\'t denote a tarfileset or a fileset"; throw new BuildException(msg); } } /** * Configure a fileset based on this fileset. * If the fileset is a TarFileSet copy in the tarfileset * specific attributes. * @param zfs the archive fileset to configure. */ protected void configureFileSet(ArchiveFileSet zfs) { super.configureFileSet(zfs); if (zfs instanceof TarFileSet) { TarFileSet tfs = (TarFileSet) zfs; tfs.setUserName(userName); tfs.setGroup(groupName); tfs.setUid(uid); tfs.setGid(gid); } } /** * Return a TarFileSet that has the same properties * as this one. * @return the cloned tarFileSet */ public Object clone() { if (isReference()) { return ((TarFileSet) getRef(getProject())).clone(); } else { return super.clone(); } } /** * A check attributes for TarFileSet. * If there is a reference, and * it is a TarFileSet, the tar fileset attributes * cannot be used. */ private void checkTarFileSetAttributesAllowed() { if (getProject() == null || (isReference() && (getRefid().getReferencedObject( getProject()) instanceof TarFileSet))) { checkAttributesAllowed(); } } }
mit
medowd/example_roulette
src/roulette/Bet.java
994
package roulette; import util.ConsoleReader; /** * Represents player's attempt to bet on outcome of the roulette wheel's spin. * * @author Robert C. Duvall */ public abstract class Bet { private String myDescription; private int myOdds; /** * Constructs a bet with the given name and odds. * * @param description name of this kind of bet * @param odds odds given by the house for this kind of bet */ public Bet (String description, int odds) { myDescription = description; myOdds = odds; } /** * @return odds given by the house for this kind of bet */ public int getOdds () { return myOdds; } /** * @return name of this kind of bet */ public String getDescription () { return myDescription; } /** * prompts for bet */ public abstract String prompt(); public abstract boolean checkWinOrLose(Wheel myWheel, String betChoice); }
mit
TPL-Group/TPL-Compiler
src/parser/nodes/FormalsNode.java
562
package src.parser.nodes; import src.parser.*; public class FormalsNode extends SemanticNode{ @Override public void setChildren(){ if(TableDrivenParser.semanticStack.peek() instanceof NonEmptyFormalsNode){ this.takeChildren((NonEmptyFormalsNode)TableDrivenParser.semanticStack.pop(), this); } } /* @Override public void typeCheck(){ for(SemanticNode childNode : this.getChildren()){ childNode.typeCheck(); //check if children have assigned types } }*/ @Override public String toString(){ return "FormalsNode"; } }
mit
olivergondza/dumpling
cli/src/main/java/com/github/olivergondza/dumpling/cli/ThreaddumpCommand.java
2159
/* * The MIT License * * Copyright (c) 2015 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.olivergondza.dumpling.cli; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.Option; import com.github.olivergondza.dumpling.model.ModelObject.Mode; import com.github.olivergondza.dumpling.model.ProcessRuntime; /** * Print threaddump as string. * * @author ogondza */ public class ThreaddumpCommand implements CliCommand { @Option(name = "-i", aliases = {"--in"}, usage = "Input for process runtime") private ProcessRuntime<?, ?, ?> runtime; @Option(name = "-p", aliases = {"--porcelain"}, usage = "Show in a format designed for machine consumption") private boolean porcelain = false; @Override public String getName() { return "threaddump"; } @Override public String getDescription() { return "Print runtime as string"; } @Override public int run(ProcessStream process) throws CmdLineException { runtime.toString(process.out(), porcelain ? Mode.MACHINE : Mode.HUMAN); return 0; } }
mit
RaynLegends/AdventOfCodePuzzleSolver
src/com/gmail/raynlegends/adventofcode/puzzles/_01_2_Puzzle.java
558
package com.gmail.raynlegends.adventofcode.puzzles; import com.gmail.raynlegends.adventofcode.Puzzle; public class _01_2_Puzzle implements Puzzle { @Override public String calculate(String input) { int current = 0; int position = 1; for (char character : input.toCharArray()) { if (character == '(') { current++; } else if (character == ')') { current--; } if (current == -1) { break; } position++; } return position + ""; } @Override public String toString() { return "Day 1, Part 2"; } }
mit
FAForever/downlords-faf-client
src/test/java/com/faforever/client/fx/contextmenu/WatchGameMenuItemTest.java
2400
package com.faforever.client.fx.contextmenu; import com.faforever.client.builders.GameBeanBuilder; import com.faforever.client.builders.PlayerBeanBuilder; import com.faforever.client.domain.PlayerBean; import com.faforever.client.i18n.I18n; import com.faforever.client.notification.NotificationService; import com.faforever.client.replay.LiveReplayService; import com.faforever.client.test.UITest; import com.faforever.commons.lobby.GameStatus; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; public class WatchGameMenuItemTest extends UITest { @Mock private I18n i18n; @Mock private NotificationService notificationService; @Mock private LiveReplayService liveReplayService; @InjectMocks private WatchGameMenuItem instance; @Test public void testWatchGame() { PlayerBean player = PlayerBeanBuilder.create().defaultValues() .game(GameBeanBuilder.create().status(GameStatus.PLAYING).get()).get(); instance.setObject(player); instance.onClicked(); verify(liveReplayService).runLiveReplay(player.getGame().getId()); } @Test public void testRunReplayWithError() { PlayerBean player = PlayerBeanBuilder.create().defaultValues() .game(GameBeanBuilder.create().defaultValues().status(GameStatus.PLAYING).get()).get(); Exception e = new RuntimeException(); doThrow(e).when(liveReplayService).runLiveReplay(player.getGame().getId()); instance.setObject(player); instance.onClicked(); verify(notificationService).addImmediateErrorNotification(e, "replays.live.loadFailure.message"); } @Test public void testVisibleItemIfPlayerIsPlaying() { instance.setObject(PlayerBeanBuilder.create().defaultValues() .game(GameBeanBuilder.create().defaultValues().status(GameStatus.PLAYING).get()).get()); assertTrue(instance.isVisible()); } @Test public void testInvisibleItemIfPlayerIsIdle() { instance.setObject(PlayerBeanBuilder.create().defaultValues().game(null).get()); assertFalse(instance.isVisible()); } @Test public void testInvisibleItemIfNoPlayer() { instance.setObject(null); assertFalse(instance.isVisible()); } }
mit
bing-ads-sdk/BingAds-Java-SDK
proxies/com/microsoft/bingads/v12/adinsight/GetAuctionInsightDataResponse.java
1811
package com.microsoft.bingads.v12.adinsight; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Result" type="{http://schemas.datacontract.org/2004/07/Microsoft.BingAds.Advertiser.AdInsight.Api.DataContract.V12.Entity}AuctionInsightResult" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "result" }) @XmlRootElement(name = "GetAuctionInsightDataResponse", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12") public class GetAuctionInsightDataResponse { @XmlElement(name = "Result", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12", nillable = true) protected AuctionInsightResult result; /** * Gets the value of the result property. * * @return * possible object is * {@link AuctionInsightResult } * */ public AuctionInsightResult getResult() { return result; } /** * Sets the value of the result property. * * @param value * allowed object is * {@link AuctionInsightResult } * */ public void setResult(AuctionInsightResult value) { this.result = value; } }
mit
fvasquezjatar/fermat-unused
fermat-api/src/main/java/com/bitdubai/fermat_api/layer/all_definition/exceptions/InvalidParameterException.java
1026
package com.bitdubai.fermat_api.layer.all_definition.exceptions; import com.bitdubai.fermat_api.FermatException; /** * Created by eze on 2015.06.18.. */ public class InvalidParameterException extends FermatException { private static String defaultMsg = "Wrong Parameter Found: "; public static final String DEFAULT_MESSAGE = "INVALID PARAMETER"; public InvalidParameterException(final String message, final Exception cause, final String context, final String possibleReason) { super(message, cause, context, possibleReason); } public InvalidParameterException(final String message, final Exception cause) { this(message, cause, "", ""); } public InvalidParameterException(final String message) { this(message, null); } public InvalidParameterException(final Exception exception) { this(exception.getMessage()); setStackTrace(exception.getStackTrace()); } public InvalidParameterException() { this(DEFAULT_MESSAGE); } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/EnrollmentConfigurationAssignmentRequestBuilder.java
2566
// Template Source: BaseEntityRequestBuilder.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.EnrollmentConfigurationAssignment; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Enrollment Configuration Assignment Request Builder. */ public class EnrollmentConfigurationAssignmentRequestBuilder extends BaseRequestBuilder<EnrollmentConfigurationAssignment> { /** * The request builder for the EnrollmentConfigurationAssignment * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public EnrollmentConfigurationAssignmentRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the EnrollmentConfigurationAssignmentRequest instance */ @Nonnull public EnrollmentConfigurationAssignmentRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for this request * @return the EnrollmentConfigurationAssignmentRequest instance */ @Nonnull public EnrollmentConfigurationAssignmentRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new com.microsoft.graph.requests.EnrollmentConfigurationAssignmentRequest(getRequestUrl(), getClient(), requestOptions); } }
mit
amolenaar/fitnesse-jbehave-test-system
stepsrc/org/fitnesse/jbehave/ExampleSteps.java
805
package org.fitnesse.jbehave; import org.jbehave.core.annotations.*; import org.jbehave.core.steps.Steps; public class ExampleSteps extends Steps { int x; @Given("a variable x with value $value") @Alias("a variable x with value <value>") // examples table public void givenXValue(@Named("value") int value) { x = value; } @When("I multiply x by $value") @Alias("I multiply x by <value>") // examples table public void whenImultiplyXBy(@Named("value") int value) { x = x * value; } @Then("x should equal $outcome") @Alias("x should equal <outcome>") // examples table public void thenXshouldBe(@Named("outcome") int value) { if (value != x) throw new AssertionError("x is " + x + ", but should be " + value); } }
mit
sibojia/ihomepage
infohub-yt/src/com/renren/api/json/HTTPTokener.java
2432
package com.renren.api.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * The HTTPTokener extends the JSONTokener to provide additional methods * for the parsing of HTTP headers. * @author JSON.org * @version 2012-11-13 */ public class HTTPTokener extends JSONTokener { /** * Construct an HTTPTokener from a string. * @param string A source string. */ public HTTPTokener(String string) { super(string); } /** * Get the next token or string. This is used in parsing HTTP headers. * @throws JSONException * @return A String. */ public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } } }
mit
ischool-tw/FireflyLite
FireflyLite/src/main/java/tw/com/ischool/fireflylite/util/Converter.java
8617
package tw.com.ischool.fireflylite.util; import android.util.Base64; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Array; import java.security.MessageDigest; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class Converter { public static final String DEFAULT_DATETIME_FORMAT = "yyyy/MM/dd HH:mm:ss"; public static final String DEFAULT_DATE_FORMAT = "yyyy/MM/dd"; public static boolean toBoolean(String str) { return toBoolean(str, false); } public static boolean toBoolean(String str, boolean defaultValue) { if (str == null) return defaultValue; if (str.equals("")) return defaultValue; try { return Boolean.parseBoolean(str); } catch (Exception ex) { return defaultValue; } } public static int toInteger(String intStr, int defaultInt) { try { return Integer.parseInt(intStr); } catch (Exception ex) { return defaultInt; } } public static int toInteger(String intStr) { return toInteger(intStr, -1); } public static Date toDate(String dateString) { String formatString = DEFAULT_DATETIME_FORMAT; if (dateString.contains("-")) formatString = formatString.replace("/", "-"); return toDate(dateString, formatString); } public static Date toDate(String dateString, String formatString) { SimpleDateFormat format = new SimpleDateFormat(formatString); try { return format.parse(dateString); } catch (Exception ex) { return null; } } public static Date toShortDate(String dateString) { return toShortDate(dateString, "1970/01/01"); } public static Date toShortDate(String dateString, String defaultDate) { String formatString = DEFAULT_DATE_FORMAT; if (dateString == null) dateString = defaultDate; else if (dateString.isEmpty()) dateString = defaultDate; if (dateString.contains("-")) formatString = formatString.replace("/", "-"); return toDate(dateString, formatString); } public static String toBase64String(byte[] bytes) { // return Base64.encode(bytes); return Base64.encodeToString(bytes, Base64.DEFAULT); } public static byte[] fromBase64String(String base64String) { try { // return Base64.decode(base64String); return Base64.decode(base64String, Base64.DEFAULT); } catch (Exception ex) { throw new RuntimeException(ex); } } public static String toBase64String(Object obj) { try { ByteArrayOutputStream s = new ByteArrayOutputStream(); java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(s); out.writeObject(obj); out.close(); byte[] pubBytes = s.toByteArray(); String str = Converter.toBase64String(pubBytes); return str; } catch (IOException e) { throw new RuntimeException(e); } } public static <T> T fromBase64String(String base64String, Class<T> c) { try { byte[] b = Converter.fromBase64String(base64String); ByteArrayInputStream keyStream = new ByteArrayInputStream(b); java.io.ObjectInputStream in = new java.io.ObjectInputStream( keyStream); Object object = in.readObject(); in.close(); return c.cast(object); } catch (Exception ex) { throw new RuntimeException(ex); } } public static String toShortDateString(Date date) { return toShortDateString(date, ""); } public static String toShortDateString(Date date, String defaultString) { return toDateString(date, DEFAULT_DATE_FORMAT, defaultString); } public static String toDateString(Date date) { return toDateString(date, DEFAULT_DATETIME_FORMAT, ""); } public static String toDateString(Date date, String formatString, String defaultString) { if (date == null) return defaultString; try { SimpleDateFormat format = new SimpleDateFormat(formatString); return format.format(date); } catch (Exception ex) { return defaultString; } } public static String compressString(String source) { try { ByteArrayOutputStream fos = new ByteArrayOutputStream(); GZIPOutputStream gz = new GZIPOutputStream(fos); OutputStreamWriter oos = new OutputStreamWriter(gz); oos.write(source); oos.flush(); oos.close(); fos.close(); byte[] bs = fos.toByteArray(); return Converter.toBase64String(bs); } catch (IOException ex) { throw new RuntimeException(ex); } } public static String decompressString(String compressed) { byte[] bs1 = Converter.fromBase64String(compressed); try { ByteArrayInputStream fis = new ByteArrayInputStream(bs1); GZIPInputStream gs = new GZIPInputStream(fis); InputStreamReader reader = new InputStreamReader(gs); StringBuilder sb = new StringBuilder(); char[] cs = new char[1024]; int d; while ((d = reader.read(cs)) != -1) { sb.append(cs, 0, d); } reader.close(); return sb.toString(); } catch (IOException ex) { throw new RuntimeException(ex); } } public static java.sql.Date toSqlDate(Date d) { if (d == null) return null; Calendar cal = Calendar.getInstance(); cal.setTime(d); java.sql.Date sqlDate = new java.sql.Date(cal.getTimeInMillis()); return sqlDate; } public static Timestamp toSqlTimestamp(String dateString) { return toSqlTimestamp(dateString, DEFAULT_DATETIME_FORMAT); } public static Timestamp toSqlTimestamp(String dateString, String format) { Date d = toDate(dateString, format); return new Timestamp(d.getTime()); } public static java.sql.Date toSqlDate(String dateString) { return toSqlDate(dateString, DEFAULT_DATETIME_FORMAT); } public static java.sql.Date toSqlDate(String dateString, String formatString) { Date d = toDate(dateString, formatString); return toSqlDate(d); } public static Date toDate(java.sql.Date d) { if (d == null) return null; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(d.getTime()); return cal.getTime(); } public static String toSHA1String(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] result = md.digest(source.getBytes("utf-8")); return Converter.toBase64String(result); } catch (Exception ex) { throw new RuntimeException(ex); } } public static String toMD5String(String source) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] result = md.digest(source.getBytes("utf-8")); StringBuilder sb = new StringBuilder(); for (int i = 0; i < result.length; i++) { sb.append(Integer.toHexString(0xFF & result[i])); } return sb.toString(); } catch (Exception ex) { throw new RuntimeException(ex); } } public static double toDouble(String valueString) { return toDouble(valueString, 0); } public static double toDouble(String valueString, double defaultValue) { try { return Double.parseDouble(valueString); } catch (Exception e) { return defaultValue; } } public static String toString(InputStream in) { if (in != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } return writer.toString(); } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { in.close(); } catch (Exception ex) { } } } else { return ""; } } @SuppressWarnings("unchecked") public static <T> T[] toArray(Class<T> c, List<T> events) { if (events == null) return null; T[] array = (T[]) Array.newInstance(c, events.size()); return events.toArray(array); } // public static <T> T[] toArray(List<T> list){ // // T[] ls = (T[]) list.toArray(); // return ls; // } // // public static void main(String[] args) { // ArrayList<String> str = new ArrayList<String>(); // str.add("abc"); // str.add("1234"); // String[] s = Converter.toArray(str); // System.out.println(s[1]); // } }
mit
blackbbc/Tucao
takephoto_library/src/main/java/com/jph/takephoto/model/TContextWrap.java
985
package com.jph.takephoto.model; import android.app.Activity; import androidx.fragment.app.Fragment; /** * Author: JPH * Date: 2016/8/11 17:01 */ public class TContextWrap { private Activity activity; private Fragment fragment; public static TContextWrap of(Activity activity){ return new TContextWrap(activity); } public static TContextWrap of(Fragment fragment){ return new TContextWrap(fragment); } private TContextWrap(Activity activity) { this.activity = activity; } private TContextWrap(Fragment fragment) { this.fragment = fragment; this.activity=fragment.getActivity(); } public Activity getActivity() { return activity; } public void setActivity(Activity activity) { this.activity = activity; } public Fragment getFragment() { return fragment; } public void setFragment(Fragment fragment) { this.fragment = fragment; } }
mit
fmarchioni/mastertheboss
quarkus/testing/src/main/java/org/acme/CustomerResource.java
2076
package org.acme; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.ws.rs.*; import javax.ws.rs.core.Response; @Path("/customer") @Produces("application/json") @Consumes("application/json") public class CustomerResource { @Inject EntityManager entityManager; @GET public Customer[] get() { return entityManager.createNamedQuery("Customers.findAll", Customer.class) .getResultList().toArray(new Customer[0]); } @POST @Transactional public Response create(Customer customer) { if (customer.getId() != null) { throw new WebApplicationException("Id was invalidly set on request.", 422); } entityManager.persist(customer); System.out.println("--------------------Creating "+customer); return Response.ok(customer).status(201).build(); } @PUT @Transactional public Customer update(Customer customer) { if (customer.getId() == null) { throw new WebApplicationException("Customer Id was not set on request.", 422); } Customer entity = entityManager.find(Customer.class, customer.getId()); if (entity == null) { throw new WebApplicationException("Customer with id of " + customer.getId() + " does not exist.", 404); } entity.setName(customer.getName()); return entity; } @DELETE @Transactional public Response delete(Customer customer) { Customer entity = entityManager.find(Customer.class, customer.getId()); if (entity == null) { throw new WebApplicationException("Customer with id of " + customer.getId() + " does not exist.", 404); } entityManager.remove(entity); return Response.status(204).build(); } @Inject @ConfigProperty(name="message") String message; @GET @Path("/hello") public String hello() { return message; } }
mit
blueinblue/tbase
tbase/src/main/java/org/bib/tbase/config/web/WebFlowConfig.java
5419
package org.bib.tbase.config.web; import java.util.Arrays; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.collections4.CollectionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.binding.convert.service.DefaultConversionService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.format.Formatter; import org.springframework.format.datetime.DateFormatter; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.ViewResolver; import org.springframework.webflow.config.AbstractFlowConfiguration; import org.springframework.webflow.definition.registry.FlowDefinitionRegistry; import org.springframework.webflow.engine.builder.support.FlowBuilderServices; import org.springframework.webflow.executor.FlowExecutor; import org.springframework.webflow.mvc.builder.MvcViewFactoryCreator; import org.springframework.webflow.security.SecurityFlowExecutionListener; @Configuration public class WebFlowConfig extends AbstractFlowConfiguration { // Constructors // Public Methods /** * FlowBuilderServices allows you to customize how WebFlow behaves. For example, in this method, we set the ViewFactoryCreator to use a * Thymeleaf view resolver, rather than the standard JSP resolver. We also setup JSR-303 bean validation by setting a validator. * * The FlowExecutor loads flow definitions using the flowRegistry. The FlowRegistry finds flow definitions and builds flow objects * using the FlowBuilderServices to configure each flow object. */ @Bean public FlowBuilderServices flowBuilderServices() { return getFlowBuilderServicesBuilder() .setViewFactoryCreator(mvcViewFactoryCreator()) .setValidator(localValidatorFactoryBean) .setDevelopmentMode(true) .setConversionService(webFlowConversionService()) .build(); } /** * FlowDefinitionRegistry tells Spring WebFlow where to look for flow xml files. */ @Bean public FlowDefinitionRegistry flowRegistry() { return getFlowDefinitionRegistryBuilder(flowBuilderServices()) .setBasePath("/WEB-INF/flows") .addFlowLocationPattern("/**/*-flow.xml").build(); } /** * A FlowExecutor handles the actual execution of the web flows - such as starting and resuming conversations. In this method, * we add a FlowExecutionListener to integrate WebFlow with Spring Security. * * It takes as a config param the flowRegistry, which tells the FlowExecutor where to find flow definitions. */ @Bean public FlowExecutor flowExecutor() { return getFlowExecutorBuilder(flowRegistry()) .addFlowExecutionListener(new SecurityFlowExecutionListener(), "*") .build(); } /** * An MvcViewFactoryCreator allows us to customize the view resolvers that Spring WebFlow uses to resolve logical view names and * render those views. In this method, we use a ThymeLeaf View Resolver configured in the WebConfig configuration class. * * Out of the box, WebFlow uses an InternalViewResolver to resolve view names to JSPs. We replace this default with the * Thymeleaf View Resolver, since we are using Thymeleaf to render views. */ @Bean public MvcViewFactoryCreator mvcViewFactoryCreator() { MvcViewFactoryCreator factoryCreator = new MvcViewFactoryCreator(); factoryCreator.setViewResolvers(Arrays.<ViewResolver>asList(this.webConfig.thymeleafViewResolver())); return factoryCreator; } /** * Replace WebFlow's automatically created DefaultConversionService with one that delegates formatting/conversion to the Spring MVC conversion service. Configured above in the * flowBuilderServices() bean method. */ @Bean public DefaultConversionService webFlowConversionService() { // Add Formatters - There's a bit of a circular reference between WebConfig and WebFlowConfig. Typically formatters are added in the addFormatters() method of WebConfig, but // we have to do it this was because we're sharing the Conversion Service between MVC and WebFlow. if(CollectionUtils.isNotEmpty(formatters)) { for(Formatter<?> f : formatters) { mvcConversionService.addFormatter(f); } } mvcConversionService.addFormatter(new DateFormatter("yyyy-MM-dd")); // DefaultConversionService serves as a pass through to the MVC Conversion Service return new DefaultConversionService(mvcConversionService); } // Getters & Setters // Attributes /** * Logger */ private static final Logger logger = LogManager.getLogger(WebFlowConfig.class); /** * Web Config */ @Autowired private WebConfig webConfig; /** * The Spring MVC conversion service (create automatically by EnableWebMvc) that will serve as the delegate to WebFlow's conversion/formatting needs. */ @Inject @Named("mvcConversionService") private FormattingConversionService mvcConversionService; @Inject @Named("beanValidator") private LocalValidatorFactoryBean localValidatorFactoryBean; /** * All Formatters defined in the application to provide type conversion in the web tier */ @Autowired(required=false) private Collection<Formatter<?>> formatters; }
mit
PhilippMundhenk/FIBEX-Import-Export
FIBEX/src/fibex/utilities/SupportedVersion.java
4085
package fibex.utilities; import java.io.File; import java.util.Collection; import java.util.LinkedHashSet; import support.FIBEXConfiguration; import support.Log; /** * This class extracts and represents all supported versions from the library folder * * @author TUM CREATE - RP3 - Philipp Mundhenk */ public class SupportedVersion { static Collection<SupportedVersion> versions = new LinkedHashSet<SupportedVersion>(); private String version; private String className; private String packageName; private String fileName; private static final String module = "Fibex"; /** * This constructor creates an instance without initializing any fields */ public SupportedVersion() { } /** * This method returns the version string of the instance * * @return * version string */ public String getVersion() { return version; } /** * This method returns the version string of the instance * * @param version * version string */ public void setVersion(String version) { this.version = version; } /** * This method returns the name of the class inheriting from FibexDocument * * @return * name of class */ public String getClassName() { return className; } /** * This method sets the name of the class inheriting from FibexDocument * * @param className * name of class */ public void setClassName(String className) { this.className = className; } /** * This method returns the name of the package where the initiating classes are located * * @return * name of package */ public String getPackageName() { return packageName; } /** * This method sets the name of the package where the initiating classes are located * * @param packageName * name of package */ public void setPackageName(String packageName) { this.packageName = packageName; } /** * This method returns the filename of the library for this version * * @return * filename */ public String getFileName() { return fileName; } /** * This method sets the filename of the library for this version * * @param fileName * filename */ public void setFileName(String fileName) { this.fileName = fileName; } /** * This method returns a collection of all support versions * * @return * collection of all supported version */ public static Collection<SupportedVersion> getVersions() { return versions; } /** * This method sets all supported versions * * @param versions * collection of all supported versions */ public static void setVersions(Collection<SupportedVersion> versions) { SupportedVersion.versions = versions; } /** * This method adds a version to the list of supported versions * * @param version * version to add */ public static void addVersion(SupportedVersion version) { versions.add(version); } /** * This method checks the library folder defined in the config and saves all libraries found as supported versions */ public static void loadLibs() { String file; File folder = new File(FIBEXConfiguration.LIB_FOLDER); File[] listOfFiles = folder.listFiles(); if(listOfFiles != null) { for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { file = listOfFiles[i].getName(); Log.logLowln("found library: " + file, module); if(file.startsWith(FIBEXConfiguration.LIB_PREFIX)) { if (file.endsWith(".jar") || file.endsWith(".JAR") || file.endsWith(".Jar") || file.endsWith(".jAr") || file.endsWith(".jaR") || file.endsWith(".JAr") || file.endsWith(".jAR") || file.endsWith(".Jar")) { SupportedVersion ver = new SupportedVersion(); ver.setFileName(file); String[] str = file.split(FIBEXConfiguration.LIB_PREFIX); str[1] = str[1].split(".jar")[0]; ver.setClassName("FIBEXDocument"+str[1]); ver.setPackageName("fibex"+str[1]); str[1] = str[1].replace('_', '.'); ver.setVersion(str[1]); versions.add(ver); } } } } } } }
mit
TomiTakussaari/phaas
src/main/java/com/github/tomitakussaari/phaas/model/PasswordVerifyRequest.java
746
package com.github.tomitakussaari.phaas.model; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import static com.github.tomitakussaari.phaas.model.DataProtectionScheme.ESCAPED_TOKEN_VALUE_SEPARATOR; @RequiredArgsConstructor @Getter public class PasswordVerifyRequest { @NonNull private final String passwordCandidate; @NonNull private final String hash; public int schemeId() { return Integer.valueOf(hash.split(ESCAPED_TOKEN_VALUE_SEPARATOR)[0]); } public String encryptionSalt() { return hash.split(ESCAPED_TOKEN_VALUE_SEPARATOR)[1]; } public String encryptedPasswordHash() { return getHash().split(ESCAPED_TOKEN_VALUE_SEPARATOR)[2]; } }
mit
horrorho/InflatableDonkey
src/main/java/com/github/horrorho/inflatabledonkey/args/filter/ArgsSelector.java
3359
/* * The MIT License * * Copyright 2016 Ahseya. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.horrorho.inflatabledonkey.args.filter; import com.github.horrorho.inflatabledonkey.data.backup.Device; import com.github.horrorho.inflatabledonkey.data.backup.Snapshot; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import javax.annotation.concurrent.Immutable; import static java.util.stream.Collectors.toMap; /** * * @author Ahseya */ @Immutable public final class ArgsSelector implements UnaryOperator<Map<Device, List<Snapshot>>> { private final Set<String> uuids; private final IndexFilter<Snapshot> snapshotFilter; public ArgsSelector(Collection<String> deviceUUIDs, IndexFilter<Snapshot> snapshotFilter) { this.uuids = deviceUUIDs.isEmpty() ? new HashSet<>(Arrays.asList("")) : deviceUUIDs.stream().map(u -> u.toLowerCase(Locale.US)).collect(Collectors.toSet()); this.snapshotFilter = Objects.requireNonNull(snapshotFilter); } public ArgsSelector(Collection<String> deviceUUIDs, Collection<Integer> snapshotIndices) { this(deviceUUIDs, new IndexFilter(snapshotIndices)); } @Override public Map<Device, List<Snapshot>> apply(Map<Device, List<Snapshot>> deviceSnapshots) { return deviceSnapshots .entrySet() .stream() .map(e -> new SimpleImmutableEntry<>(e.getKey(), snapshots(e.getValue()))) .filter(this::device) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); } List<Snapshot> snapshots(Collection<Snapshot> snapshots) { return snapshotFilter.apply(new ArrayList<>(snapshots)); } boolean device(Map.Entry<Device, ? extends Collection<Snapshot>> entry) { if (entry.getValue().isEmpty()) { return false; } String hash = entry.getKey().deviceID().hash().toLowerCase(Locale.US); return uuids.stream().anyMatch(hash::contains); } }
mit
lare96/luna
src/main/java/io/luna/game/model/StationaryEntity.java
7329
package io.luna.game.model; import com.google.common.collect.ImmutableList; import io.luna.LunaContext; import io.luna.game.model.chunk.Chunk; import io.luna.game.model.mob.Player; import io.luna.net.msg.GameMessageWriter; import io.luna.net.msg.out.ChunkPlacementMessageWriter; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; /** * An abstraction model representing non-moving {@link Entity}. * * @author lare96 <http://github.com/lare96> */ public abstract class StationaryEntity extends Entity { /** * An enumerated type whose elements represent either a show or hide update. */ public enum UpdateType { SHOW, HIDE } /** * The player to update for. If empty, updates for all players. */ private final Optional<Player> owner; /** * The position used for placement. */ private final Position placement; /** * The surrounding players. Initialized lazily, use {@link #getSurroundingPlayers()}. */ private ImmutableList<Set<Player>> surroundingPlayers; /** * If this entity is hidden. */ private boolean hidden = true; /** * Creates a new local {@link StationaryEntity}. * * @param context The context instance. * @param position The position. * @param type The entity type. * @param owner The player to update for. If empty, updates for all players. */ public StationaryEntity(LunaContext context, Position position, EntityType type, Optional<Player> owner) { super(context, position, type); this.owner = owner; placement = position;//new Position(getChunkPosition().getAbsX(), getChunkPosition().getAbsY()); } /** * Stationary entities rely solely on identity when compared because entities in chunks are held in a HashSet * datatype. * <br><br> * Weird issues can occur with a equals/hashcode implementation that is too strict, and there isn't much use in * having an implementation that is lenient. */ @Override public int hashCode() { return System.identityHashCode(this); } /** * Stationary entities rely solely on identity when compared because entities in chunks are held in a HashSet * datatype. * <br><br> * Weird issues can occur with a equals/hashcode implementation that is too strict. */ @Override public boolean equals(Object obj) { return this == obj; } /** * Creates a {@link GameMessageWriter} that shows this entity. * * @param offset The chunk offset. * @return The message. */ protected abstract GameMessageWriter showMessage(int offset); /** * Creates a {@link GameMessageWriter} that hides this entity. * * @param offset The chunk offset. * @return The message. */ protected abstract GameMessageWriter hideMessage(int offset); /** * Sends a packet to all applicable players to display this entity. * <strong>This does NOT register the entity, so it cannot be interacted with by a Player.</strong> * Use functions in {@link World} to register entities. */ public final void show() { if (hidden) { applyUpdate(UpdateType.SHOW); } } /** * Sends a packet to all applicable players to hide this entity. * <strong>This does NOT unregister the entity, it just makes it invisible to players.</strong> * Use functions in {@link World} to unregister entities. */ public final void hide() { if (!hidden) { applyUpdate(UpdateType.HIDE); } } /** * Updates this entity, either locally or globally. * * @param updateType The update type to apply. */ private void applyUpdate(UpdateType updateType) { if (owner.isPresent() && owner.get().isViewableFrom(this)) { // We have a player to update for. sendUpdateMessage(owner.get(), updateType); } else { // We don't, so update for all viewable surrounding players. for (Set<Player> chunkPlayers : getSurroundingPlayers()) { for (Player inside : chunkPlayers) { if (isViewableFrom(inside)) { sendUpdateMessage(inside, updateType); } } } } } /** * Sends an update message to {@code player}. * * @param player The player. * @param updateType The update type to apply. */ public void sendUpdateMessage(Player player, UpdateType updateType) { player.queue(new ChunkPlacementMessageWriter(placement)); int offset = getChunkPosition().offset(position); if (updateType == UpdateType.SHOW) { player.queue(showMessage(offset)); hidden = false; } else if (updateType == UpdateType.HIDE) { player.queue(hideMessage(offset)); hidden = true; } } /** * Determines if this item is visible to {@code player}. * * @param player The player. * @return {@code true} if this item is visible to the player. */ public boolean isVisibleTo(Player player) { if (!player.isViewableFrom(this)) { return false; } return isGlobal() || owner.filter(plrOwner -> plrOwner.equals(player)).isPresent(); } /** * @return The player to update for. */ public final Optional<Player> getOwner() { return owner; } /** * @return The player to update for, or {@code null}. */ public final Player getOwnerInstance() { return owner.orElse(null); } /** * @return {@code true} if this entity is visible for everyone. */ public final boolean isGlobal() { return owner.isEmpty(); } /** * @return {@code true} if this entity is visible for just one player. */ public final boolean isLocal() { return owner.isPresent(); } /** * @return {@code true} if this entity is invisible, {@code false} otherwise. */ public boolean isHidden() { return hidden; } /** * Returns an {@link ImmutableList} representing surrounding players. Each set represents players within a viewable * chunk. * <p> * We retain references to the original sets instead of flattening them, so that they implicitly stay updated as * players move in and out of view of this entity. This means we only have to build the returned list once. */ public final ImmutableList<Set<Player>> getSurroundingPlayers() { if (surroundingPlayers == null) { ImmutableList.Builder<Set<Player>> builder = ImmutableList.builder(); // Retrieve viewable chunks. List<Chunk> viewableChunks = world.getChunks().getViewableChunks(position); for (Chunk chunk : viewableChunks) { // Wrap players in immutable view, add it. Set<Player> players = Collections.unmodifiableSet(chunk.getAll(EntityType.PLAYER)); builder.add(players); } surroundingPlayers = builder.build(); } return surroundingPlayers; } }
mit
punyal/BlackHole
src/main/java/com/punyal/blackhole/core/control/Analyzer.java
6973
/* * The MIT License * * Copyright 2015 Pablo Puñal Pereira <pablo.punal@ltu.se>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.punyal.blackhole.core.control; import static com.punyal.blackhole.constants.ConstantsNet.*; import com.punyal.blackhole.core.data.EventDataBase; import com.punyal.blackhole.core.data.IncomingData; import com.punyal.blackhole.core.data.IncomingDataBase; import com.punyal.blackhole.core.data.RMSdata; import com.punyal.blackhole.core.data.RMSdataBase; import com.punyal.blackhole.core.data.StrainData; import com.punyal.blackhole.core.data.StrainDataBase; import com.punyal.blackhole.core.net.lwm2m.LWM2Mlist; import com.punyal.blackhole.tentacle.Ticket; import com.punyal.blackhole.utils.Parsers; import org.json.simple.JSONObject; /** * * @author Pablo Puñal Pereira <pablo.punal@ltu.se> */ public class Analyzer extends Thread { private final EventDataBase eventDB; private final IncomingDataBase incomingDB; private final StrainDataBase strainDB; private final RMSdataBase rmsDB; private final Alarmer alarmer; private final LWM2Mlist devicesList; public Analyzer(Ticket myTicket, EventDataBase eventDB, IncomingDataBase incomingDB, StrainDataBase strainDB, RMSdataBase rmsDB, LWM2Mlist devicesList) { this.incomingDB = incomingDB; this.eventDB = eventDB; this.strainDB = strainDB; this.rmsDB = rmsDB; this.devicesList = devicesList; alarmer = new Alarmer(myTicket, devicesList, eventDB); alarmer.startThread(); this.setDaemon(true); } public void startThread() { start(); } @Override public void run() { IncomingData incomingData; JSONObject json; int alarm=0; long timestamp=0; String name="", resource=""; try { while (true) { while ((incomingData = incomingDB.getFirst()) != null) { resource = incomingData.resource; //System.out.println(incomingData.name+"]resource:"+resource+" Data:"+incomingData.response); if (incomingData.response != null) { switch (resource) { case COAP_RESOURCE_STRAIN: //System.out.println(incomingData.response); // Parse data try { json = Parsers.senml2json(incomingData.response); name = incomingData.name; timestamp = incomingData.timestamp; alarm = Integer.parseInt(json.get("alarm").toString()); if (alarm > 0) devicesList.getDeviceByName(name).increaseAlarmsStrain(); if (alarm > 1) eventDB.setCriticalMessage(name+" is broken!"); strainDB.addData(new StrainData( name, timestamp, alarm, Integer.parseInt(json.get("strain").toString()) )); } catch (NullPointerException ex) { System.out.println("NullPointerException: "+incomingData.response); } break; case COAP_RESOURCE_RMS: //System.out.println(incomingData.response); // Parse data try { json = Parsers.senml2json(incomingData.response); name = incomingData.name; timestamp = incomingData.timestamp; alarm = Integer.parseInt(json.get("a").toString()); if (alarm > 0) devicesList.getDeviceByName(name).increaseAlarmsVibration(); rmsDB.addData(new RMSdata( name, timestamp, alarm, Float.parseFloat(json.get("X").toString()), Float.parseFloat(json.get("Y").toString()), Float.parseFloat(json.get("Z").toString()) )); } catch (NullPointerException ex) { System.out.println("NullPointerException: "+incomingData.response); } break; default: //System.out.println("Unknown data"); System.out.println("BOLT: "+incomingData.response); alarm = 0; break; } if (alarm > 0) { //System.out.println("["+(new Date(timestamp))+"] ALARM level"+alarm+" from "+name+" at sensor "+resource); alarmer.newAlarm(resource, name, alarm, timestamp); } } } try { Thread.sleep(50); // Sleep 100ms } catch (InterruptedException ex) { Thread.currentThread().interrupt(); // This should kill it propertly } } } finally { System.out.println("Killing Analizer"); } } }
mit
sonnvph03164/DatPhongKhachSan
app/src/main/java/me/sabareesh/trippie/ui/CityActivity.java
10251
package me.sabareesh.trippie.ui; import android.app.ActivityOptions; import android.content.Intent; import android.content.res.Resources; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import me.sabareesh.trippie.util.Log; import android.util.TypedValue; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.places.Places; import java.util.ArrayList; import java.util.List; import me.sabareesh.trippie.R; import me.sabareesh.trippie.adapter.CategoryAdapter; import me.sabareesh.trippie.model.Category; import me.sabareesh.trippie.tasks.PhotoTask; import me.sabareesh.trippie.util.Constants; import me.sabareesh.trippie.util.RecyclerItemClickListener; import me.sabareesh.trippie.util.Utils; import static me.sabareesh.trippie.R.id.recycler_view_city; public class CityActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { public static final String TAG = "CityActivity"; String mCityId, mCityName, mCityLat, mCityLng, mStaticMapURL; GoogleApiClient mGoogleApiClient; ImageView mImageView; ProgressBar progressBar; private RecyclerView recyclerView; private CategoryAdapter adapter; private List<Category> categoryList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_city); mGoogleApiClient = new GoogleApiClient .Builder(this) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); progressBar = (ProgressBar) findViewById(R.id.progressBar); mImageView = (ImageView) findViewById(R.id.widePoster); if (getIntent().getExtras() != null) { mCityId = getIntent().getStringExtra("cityId"); mCityName = getIntent().getStringExtra("cityName"); mCityLat = getIntent().getStringExtra("cityLat"); mCityLng = getIntent().getStringExtra("cityLng"); mStaticMapURL = getIntent().getStringExtra("mStaticMapURL"); if (mCityId != null) { //placePhotosAsync(mCityId); fetchPlacePhotos(mCityId); } else { Utils.loadStaticMap(this, mImageView, mCityLat, mCityLng , Constants.SIZE_VALUE_M, Constants.ZOOM_VALUE_HIGH); progressBar.setVisibility(View.GONE); } } //Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout); collapsingToolbarLayout.setTitle(mCityName); //mImageView.setImageResource(R.drawable.poster_placeholder); //Recyclerview recyclerView = (RecyclerView) findViewById(recycler_view_city); categoryList = new ArrayList<>(); adapter = new CategoryAdapter(this, categoryList); RecyclerView.LayoutManager mLayoutManager = new StaggeredGridLayoutManager(2, 1); recyclerView.setLayoutManager(mLayoutManager); recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); recyclerView.setNestedScrollingEnabled(false); loadCategories(); recyclerView.addOnItemTouchListener( new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { int itemPosition = recyclerView.getChildLayoutPosition(view); ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail); Log.d(TAG, "City Item clicked: " + String.valueOf(itemPosition)); Intent intent = new Intent(view.getContext(), PlaceListActivity.class); intent.putExtra("cityLatLng", mCityLat + "," + mCityLng); intent.putExtra("itemPosition", itemPosition); //ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(CityActivity.this, thumbnail, getString(R.string.transition_image)); if (Build.VERSION.SDK_INT >= 23) { ActivityOptions options=ActivityOptions.makeClipRevealAnimation(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight()); startActivity(intent, options.toBundle()); }else{ ActivityOptions options = ActivityOptions.makeScaleUpAnimation(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight()); startActivity(intent, options.toBundle()); } } @Override public void onLongItemClick(View view, int position) { //// TODO: 03-Jan-17 On item long click code } }) ); } private void fetchPlacePhotos(String placeId) { new PhotoTask(Constants.WIDTH_CITY_GPHOTO, Constants.HEIGHT_CITY_GPHOTO, mGoogleApiClient) { @Override protected void onPreExecute() { // Display a temporary image to show while bitmap is loading. //mImageView.setImageResource(R.drawable.poster_placeholder); } @Override protected void onPostExecute(AttributedPhoto attributedPhoto) { if (attributedPhoto != null) { mImageView.setImageBitmap(attributedPhoto.bitmap); } progressBar.setVisibility(View.GONE); } }.execute(placeId); } private int dpToPx(int dp) { Resources r = getResources(); return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics())); } private void loadCategories() { int[] thumbnails = new int[]{ R.drawable.hotel, R.drawable.restaurant, R.drawable.top_places, R.drawable.building_illustration, R.drawable.hotel, R.drawable.hotel }; Category a = new Category(getString(R.string.title_hotel), thumbnails[0]); categoryList.add(a); a = new Category(getString(R.string.title_restaurant), thumbnails[1]); categoryList.add(a); a = new Category(getString(R.string.title_top_spots), thumbnails[2]); categoryList.add(a); a = new Category(getString(R.string.title_shopping), thumbnails[3]); categoryList.add(a); adapter.notifyDataSetChanged(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; } return true; } @Override public void onResume() { mGoogleApiClient.connect(); super.onResume(); } @Override public void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } @Override public void onConnected(@Nullable Bundle bundle) { Log.i(TAG, "API services connected."); } @Override public void onConnectionSuspended(int i) { Log.i(TAG, "Location services suspended. Please reconnect."); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.i(TAG, "API services connection failed. Please reconnect."); } public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration { private int spanCount; private int spacing; private boolean includeEdge; public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) { this.spanCount = spanCount; this.spacing = spacing; this.includeEdge = includeEdge; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = parent.getChildAdapterPosition(view); // item position int column = position % spanCount; // item column if (includeEdge) { outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing) outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing) if (position < spanCount) { // top edge outRect.top = spacing; } outRect.bottom = spacing; // item bottom } else { outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing) outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing) if (position >= spanCount) { outRect.top = spacing; // item top } } } } }
mit
DouglasOrr/SharedCollections
src/main/java/com/github/douglasorr/shared/SharedSet.java
947
package com.github.douglasorr.shared; import java.util.Set; /** * A set that supports shared updates in place of mutable ones. * Apart from this, it behaves as a normal Java immutable Set. * <p>Instead of using <code>Set.add</code>, use {@link #with(Object)}, and * instead of using <code>Set.remove</code>, use {@link #without(Object)}.</p> */ public interface SharedSet<T> extends Set<T> { /** * Return a new set, with the given value present. * @param value the value to add * @return a new set with the value present (the original set is unchanged), * so <code>set.contains(key) == true</code>. */ SharedSet<T> with(T value); /** * Return a new set, without the given value. * @param value the value to remove * @return a new set without the given value (the original set is unchanged), * so <code>set.contains(key) == false</code>. */ SharedSet<T> without(T value); }
mit
atealxt/work-workspaces
PDMS/src/java/pdms/platform/service/A0400TopicService.java
856
package pdms.platform.service; import java.util.List; import pdms.components.dto.A0400TopicDto; import pdms.components.vo.A0400TopicVo; import pdms.platform.core.PdmsException; /** * * @author LUSuo(atealxt@gmail.com) */ public interface A0400TopicService { public String createTopic(A0400TopicDto dto) throws PdmsException; public String editTopic(A0400TopicDto dto, String tId, String rId) throws PdmsException; public String createReply(String loginId, String tId, String tContent) throws PdmsException; /** * 回贴帖信息VO生成 */ public List<A0400TopicVo> MakeVo(String tId, int maxNum, int startNum) throws PdmsException; /** 取得帖子回复数 */ public int getSumCount(String tId) throws PdmsException; public String closeTopic(List<String> list, String loginId) throws PdmsException; }
mit
gaborkolozsy/XChange
xchange-bittrex/src/main/java/org/knowm/xchange/bittrex/dto/marketdata/BittrexTicker.java
4396
package org.knowm.xchange.bittrex.dto.marketdata; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonProperty; public class BittrexTicker { private BigDecimal ask; private BigDecimal baseVolume; private BigDecimal bid; private String created; private String displayMarketName; private BigDecimal high; private BigDecimal last; private BigDecimal low; private String marketName; private int openBuyOrders; private int openSellOrders; private BigDecimal prevDay; private String timeStamp; private BigDecimal volume; public BittrexTicker(@JsonProperty("Ask") BigDecimal ask, @JsonProperty("BaseVolume") BigDecimal baseVolume, @JsonProperty("Bid") BigDecimal bid, @JsonProperty("Created") String created, @JsonProperty("DisplayMarketName") String displayMarketName, @JsonProperty("High") BigDecimal high, @JsonProperty("Last") BigDecimal last, @JsonProperty("Low") BigDecimal low, @JsonProperty("MarketName") String marketName, @JsonProperty("OpenBuyOrders") int openBuyOrders, @JsonProperty("OpenSellOrders") int openSellOrders, @JsonProperty("PrevDay") BigDecimal prevDay, @JsonProperty("TimeStamp") String timeStamp, @JsonProperty("Volume") BigDecimal volume) { this.ask = ask; this.baseVolume = baseVolume; this.bid = bid; this.created = created; this.displayMarketName = displayMarketName; this.high = high; this.last = last; this.low = low; this.marketName = marketName; this.openBuyOrders = openBuyOrders; this.openSellOrders = openSellOrders; this.prevDay = prevDay; this.timeStamp = timeStamp; this.volume = volume; } public BigDecimal getAsk() { return this.ask; } public void setAsk(BigDecimal ask) { this.ask = ask; } public BigDecimal getBaseVolume() { return this.baseVolume; } public void setBaseVolume(BigDecimal baseVolume) { this.baseVolume = baseVolume; } public BigDecimal getBid() { return this.bid; } public void setBid(BigDecimal bid) { this.bid = bid; } public String getCreated() { return this.created; } public void setCreated(String created) { this.created = created; } public String getDisplayMarketName() { return this.displayMarketName; } public void setDisplayMarketName(String displayMarketName) { this.displayMarketName = displayMarketName; } public BigDecimal getHigh() { return this.high; } public void setHigh(BigDecimal high) { this.high = high; } public BigDecimal getLast() { return this.last; } public void setLast(BigDecimal last) { this.last = last; } public BigDecimal getLow() { return this.low; } public void setLow(BigDecimal low) { this.low = low; } public String getMarketName() { return this.marketName; } public void setMarketName(String marketName) { this.marketName = marketName; } public int getOpenBuyOrders() { return this.openBuyOrders; } public void setOpenBuyOrders(int openBuyOrders) { this.openBuyOrders = openBuyOrders; } public int getOpenSellOrders() { return this.openSellOrders; } public void setOpenSellOrders(int openSellOrders) { this.openSellOrders = openSellOrders; } public BigDecimal getPrevDay() { return this.prevDay; } public void setPrevDay(BigDecimal prevDay) { this.prevDay = prevDay; } public String getTimeStamp() { return this.timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public BigDecimal getVolume() { return this.volume; } public void setVolume(BigDecimal volume) { this.volume = volume; } @Override public String toString() { return "BittrexTicker [ask=" + ask + ", baseVolume=" + baseVolume + ", bid=" + bid + ", created=" + created + ", displayMarketName=" + displayMarketName + ", high=" + high + ", last=" + last + ", low=" + low + ", marketName=" + marketName + ", openBuyOrders=" + openBuyOrders + ", openSellOrders=" + openSellOrders + ", prevDay=" + prevDay + ", timeStamp=" + timeStamp + ", volume=" + volume + "]"; } }
mit
tomzig16/ADM
src/main/java/DataManagement/SyncListData.java
364
package DataManagement; public class SyncListData implements java.io.Serializable { private int m_devicePublicID; public int getDevicePublicID() {return m_devicePublicID;} public String m_lastUpdate; public SyncListData(int devicePublicID, String lastUpdate){ m_devicePublicID = devicePublicID; m_lastUpdate = lastUpdate; } }
mit
Microsoft/Microsoft-Cloud-Services-for-Android
src/com/microsoft/intellij/helpers/activityConfiguration/office365CustomWizardParameter/Office365ParameterPane.java
7737
/** * Copyright (c) Microsoft Corporation * <p/> * All rights reserved. * <p/> * MIT License * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * <p/> * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.microsoft.intellij.helpers.activityConfiguration.office365CustomWizardParameter; import com.google.gson.Gson; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.DataKeys; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.microsoft.directoryservices.Application; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Office365ParameterPane extends JPanel { private JCheckBox outlookServicesCheckBox; private JPanel mainPanel; private JCheckBox sharepointListsCheckBox; private JCheckBox fileServicesCheckBox; private JCheckBox oneNoteCheckBox; private JButton configureOneNoteButton; private JButton configureOffice365Button; private PlainDocument document; private Application selectedApplication; private String selectedClientID; public Office365ParameterPane() { super(new BorderLayout()); add(mainPanel, BorderLayout.CENTER); document = new PlainDocument(); oneNoteCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { configureOneNoteButton.setEnabled(oneNoteCheckBox.isSelected()); updateDocument(); } }); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { configureOffice365Button.setEnabled( outlookServicesCheckBox.isSelected() || sharepointListsCheckBox.isSelected() || fileServicesCheckBox.isSelected() ); updateDocument(); } }; outlookServicesCheckBox.addActionListener(actionListener); sharepointListsCheckBox.addActionListener(actionListener); fileServicesCheckBox.addActionListener(actionListener); configureOffice365Button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { DataContext dataContext = DataManager.getInstance().getDataContext(mainPanel); final Project project = DataKeys.PROJECT.getData(dataContext); Office365ConfigForm form = new Office365ConfigForm(project, sharepointListsCheckBox.isSelected(), fileServicesCheckBox.isSelected(), outlookServicesCheckBox.isSelected()); form.show(); if (form.getExitCode() == DialogWrapper.OK_EXIT_CODE) { selectedApplication = form.getApplication(); } updateDocument(); } }); configureOneNoteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { DataContext dataContext = DataManager.getInstance().getDataContext(mainPanel); final Project project = DataKeys.PROJECT.getData(dataContext); OneNoteConfigForm form = new OneNoteConfigForm(project); form.show(); if (form.getExitCode() == DialogWrapper.OK_EXIT_CODE) { selectedClientID = form.getClientId(); } updateDocument(); } }); } public String getValue() { try { return document.getText(0, document.getLength()); } catch (BadLocationException ignored) { return null; } } public void setValue(String newValue) { try { document.replace(0, document.getLength(), newValue, null); } catch (BadLocationException ignored) { } } public PlainDocument getDocument() { return document; } private void updateDocument() { boolean isOffice365Selected = sharepointListsCheckBox.isSelected() || fileServicesCheckBox.isSelected() || outlookServicesCheckBox.isSelected(); if ((isOffice365Selected && oneNoteCheckBox.isSelected() && selectedApplication != null && selectedClientID != null) || (isOffice365Selected && !oneNoteCheckBox.isSelected() && selectedApplication != null) || (!isOffice365Selected && oneNoteCheckBox.isSelected() && selectedClientID != null)) { Gson gson = new Gson(); Office365Parameters office365Parameters = new Office365Parameters( sharepointListsCheckBox.isSelected(), fileServicesCheckBox.isSelected(), outlookServicesCheckBox.isSelected(), oneNoteCheckBox.isSelected(), isOffice365Selected ? selectedApplication.getappId() : null, isOffice365Selected ? selectedApplication.getdisplayName() : null, oneNoteCheckBox.isSelected() ? selectedClientID : null); String stringVal = gson.toJson(office365Parameters); setValue(stringVal); } else { setValue(""); } } private class Office365Parameters { private boolean isSharepointLists; private boolean isFileServices; private boolean isOutlookServices; private boolean isOneNote; private String appId; private String appName; private String clientId; public Office365Parameters(boolean sharepointListsCheckBoxSelected, boolean fileServicesCheckBoxSelected, boolean outlookServicesCheckBoxSelected, boolean oneNoteCheckBoxSelected, String appId, String appName, String clientId) { this.isSharepointLists = sharepointListsCheckBoxSelected; this.isFileServices = fileServicesCheckBoxSelected; this.isOutlookServices = outlookServicesCheckBoxSelected; this.isOneNote = oneNoteCheckBoxSelected; this.appId = appId; this.appName = appName; this.clientId = clientId; } } }
mit
daniellavoie/Kubik
kubik/kubik-server/src/main/java/com/cspinformatique/kubik/server/domain/sales/service/impl/CustomerServiceImpl.java
2515
package com.cspinformatique.kubik.server.domain.sales.service.impl; import java.util.Date; import javax.annotation.Resource; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import com.cspinformatique.kubik.kos.model.account.Account; import com.cspinformatique.kubik.kos.model.kubik.KubikNotification; import com.cspinformatique.kubik.server.domain.kos.rest.KosTemplate; import com.cspinformatique.kubik.server.domain.sales.repository.CustomerRepository; import com.cspinformatique.kubik.server.domain.sales.service.CustomerService; import com.cspinformatique.kubik.server.model.sales.Customer; @Service public class CustomerServiceImpl implements CustomerService { private static final String CUSTOMER_ACCOUNT_PREFIX = "411"; @Resource private CustomerRepository customerRepository; @Resource private KosTemplate kosTemplate; @Override public Iterable<Customer> findAll() { return this.customerRepository.findAll(); } @Override public Page<Customer> findAll(Pageable pageable) { return this.customerRepository.findAll(pageable); } @Override public Customer findOne(int id) { return this.customerRepository.findOne(id); } @Override public String getCustomerAccount(Customer customer) { String customerAccount = CUSTOMER_ACCOUNT_PREFIX + "99999"; if (customer != null) { customerAccount = CUSTOMER_ACCOUNT_PREFIX + String.format("%05d", customer.getId()); } return customerAccount; } @Override public void processNotification(KubikNotification kubikNotification) { Account account = kosTemplate.exchange("/account/" + kubikNotification.getKosId(), HttpMethod.GET, Account.class); Customer customer = customerRepository.findByEmail(account.getUsername()); if (customer == null) { customer = new Customer(); customer.setEmail(account.getUsername()); } if (account.getBillingAddress() != null) { customer.setFirstName(account.getBillingAddress().getFirstName()); customer.setLastName(account.getBillingAddress().getLastName()); } save(customer); } @Override public Customer save(Customer customer) { if (customer.getCreationDate() == null) { customer.setCreationDate(new Date()); } return this.customerRepository.save(customer); } @Override public Page<Customer> search(String query, Pageable pageable) { return this.customerRepository.search("%" + query + "%", pageable); } }
mit
shaotao/Leetcode
algorithm/bulls_and_cows/BullsAndCows.java
2355
import java.io.*; import java.util.*; class BullsAndCows { public static void main(String[] args) { System.out.println("=== Bulls and Cows ==="); Solution solution = new Solution(); String secret = "1807"; String guess = "7810"; String hint = solution.getHint(secret, guess); System.out.println("secret = "+secret); System.out.println("guess = "+guess); System.out.println("hint = "+hint); } } class Solution { public String getHint(String secret, String guess) { int hit = 0; int miss = 0; HashMap<Integer, Integer> map1 = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> map2 = new HashMap<Integer, Integer>(); if(secret == null || guess == null || secret.length() == 0 || guess.length() == 0 || secret.length() != guess.length()) { hit = 0; miss = 0; } else { for(int i = 0; i < secret.length(); i++) { if(guess.charAt(i) == secret.charAt(i)) { hit++; } // update map1 char ch1 = secret.charAt(i); int num1 = Integer.parseInt(""+ch1); if(!map1.containsKey(num1)) { map1.put(num1, 1); } else { map1.put(num1, map1.get(num1)+1); } // update map2 char ch2 = guess.charAt(i); int num2 = Integer.parseInt(""+ch2); if(!map2.containsKey(num2)) { map2.put(num2, 1); } else { map2.put(num2, map2.get(num2)+1); } } System.out.println("map1.size() = "+map1.size()); System.out.println("map2.size() = "+map2.size()); // compute the total number of digits that match int total = 0; for(int i = 0; i <= 9; i++) { if(map1.containsKey(i) && map2.containsKey(i)) { total += (map1.get(i) <= map2.get(i))?map1.get(i):map2.get(i); } } miss = total - hit; } return hit+"A"+miss+"B"; } }
mit
eaglerainbow/docker-plugin
src/main/java/com/nirima/jenkins/plugins/docker/builder/DockerBuilderControlOptionDescriptor.java
520
package com.nirima.jenkins.plugins.docker.builder; import hudson.DescriptorExtensionList; import hudson.model.Descriptor; import jenkins.model.Jenkins; /** * Created by magnayn on 30/01/2014. */ public abstract class DockerBuilderControlOptionDescriptor extends Descriptor<DockerBuilderControlOption> { public static DescriptorExtensionList<DockerBuilderControlOption,DockerBuilderControlOptionDescriptor> all() { return Jenkins.getInstance().getDescriptorList(DockerBuilderControlOption.class); } }
mit
mikeqian/hprose-java
src/main/java/hprose/io/unserialize/ByteArrayUnserializer.java
5180
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * ByteArrayUnserializer.java * * * * byte array unserializer class for Java. * * * * LastModified: Apr 17, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ package hprose.io.unserialize; import static hprose.io.HproseTags.TagBytes; import static hprose.io.HproseTags.TagEmpty; import static hprose.io.HproseTags.TagList; import static hprose.io.HproseTags.TagNull; import static hprose.io.HproseTags.TagOpenbrace; import static hprose.io.HproseTags.TagRef; import static hprose.io.HproseTags.TagString; import static hprose.io.HproseTags.TagUTF8Char; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.lang.reflect.Type; import java.nio.ByteBuffer; final class ByteArrayUnserializer implements Unserializer { public final static ByteArrayUnserializer instance = new ByteArrayUnserializer(); final static byte[] readBytes(Reader reader, ByteBuffer buffer) throws IOException { byte[] b = ValueReader.readBytes(buffer); reader.refer.set(b); return b; } final static byte[] readBytes(Reader reader, InputStream stream) throws IOException { byte[] b = ValueReader.readBytes(stream); reader.refer.set(b); return b; } final static byte[] read(Reader reader, ByteBuffer buffer) throws IOException { int tag = buffer.get(); if (tag == TagBytes) return readBytes(reader, buffer); switch (tag) { case TagNull: return null; case TagEmpty: return new byte[0]; case TagUTF8Char: return ValueReader.readUTF8Char(buffer).getBytes("UTF-8"); case TagString: return StringUnserializer.readString(reader, buffer).getBytes("UTF-8"); case TagList: { int count = ValueReader.readInt(buffer, TagOpenbrace); byte[] a = new byte[count]; reader.refer.set(a); for (int i = 0; i < count; ++i) { a[i] = ByteUnserializer.read(reader, buffer); } buffer.get(); return a; } case TagRef: { Object obj = reader.readRef(buffer); if (obj instanceof byte[]) { return (byte[])obj; } if (obj instanceof String) { return ((String)obj).getBytes("UTF-8"); } throw ValueReader.castError(obj, Array.class); } default: throw ValueReader.castError(reader.tagToString(tag), Array.class); } } final static byte[] read(Reader reader, InputStream stream) throws IOException { int tag = stream.read(); if (tag == TagBytes) return readBytes(reader, stream); switch (tag) { case TagNull: return null; case TagEmpty: return new byte[0]; case TagUTF8Char: return ValueReader.readUTF8Char(stream).getBytes("UTF-8"); case TagString: return StringUnserializer.readString(reader, stream).getBytes("UTF-8"); case TagList: { int count = ValueReader.readInt(stream, TagOpenbrace); byte[] a = new byte[count]; reader.refer.set(a); for (int i = 0; i < count; ++i) { a[i] = ByteUnserializer.read(reader, stream); } stream.read(); return a; } case TagRef: { Object obj = reader.readRef(stream); if (obj instanceof byte[]) { return (byte[])obj; } if (obj instanceof String) { return ((String)obj).getBytes("UTF-8"); } throw ValueReader.castError(obj, Array.class); } default: throw ValueReader.castError(reader.tagToString(tag), Array.class); } } public final Object read(Reader reader, ByteBuffer buffer, Class<?> cls, Type type) throws IOException { return read(reader, buffer); } public final Object read(Reader reader, InputStream stream, Class<?> cls, Type type) throws IOException { return read(reader, stream); } }
mit
LattEngineer/LattEngineerAPI
src/main/java/io/lattengineer/LattEngineerAPI/gson/TypeAdapter.java
11082
/* * Copyright (C) 2011 Google 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 io.lattengineer.LattEngineerAPI.gson; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import io.lattengineer.LattEngineerAPI.gson.internal.bind.JsonTreeReader; import io.lattengineer.LattEngineerAPI.gson.internal.bind.JsonTreeWriter; import io.lattengineer.LattEngineerAPI.gson.stream.JsonReader; import io.lattengineer.LattEngineerAPI.gson.stream.JsonToken; import io.lattengineer.LattEngineerAPI.gson.stream.JsonWriter; /** * Converts Java objects to and from JSON. * * <h3>Defining a type's JSON form</h3> * By default Gson converts application classes to JSON using its built-in type * adapters. If Gson's default JSON conversion isn't appropriate for a type, * extend this class to customize the conversion. Here's an example of a type * adapter for an (X,Y) coordinate point: <pre> {@code * * public class PointAdapter extends TypeAdapter<Point> { * public Point read(JsonReader reader) throws IOException { * if (reader.peek() == JsonToken.NULL) { * reader.nextNull(); * return null; * } * String xy = reader.nextString(); * String[] parts = xy.split(","); * int x = Integer.parseInt(parts[0]); * int y = Integer.parseInt(parts[1]); * return new Point(x, y); * } * public void write(JsonWriter writer, Point value) throws IOException { * if (value == null) { * writer.nullValue(); * return; * } * String xy = value.getX() + "," + value.getY(); * writer.value(xy); * } * }}</pre> * With this type adapter installed, Gson will convert {@code Points} to JSON as * strings like {@code "5,8"} rather than objects like {@code {"x":5,"y":8}}. In * this case the type adapter binds a rich Java class to a compact JSON value. * * <p>The {@link #read(JsonReader) read()} method must read exactly one value * and {@link #write(JsonWriter,Object) write()} must write exactly one value. * For primitive types this is means readers should make exactly one call to * {@code nextBoolean()}, {@code nextDouble()}, {@code nextInt()}, {@code * nextLong()}, {@code nextString()} or {@code nextNull()}. Writers should make * exactly one call to one of <code>value()</code> or <code>nullValue()</code>. * For arrays, type adapters should start with a call to {@code beginArray()}, * convert all elements, and finish with a call to {@code endArray()}. For * objects, they should start with {@code beginObject()}, convert the object, * and finish with {@code endObject()}. Failing to convert a value or converting * too many values may cause the application to crash. * * <p>Type adapters should be prepared to read null from the stream and write it * to the stream. Alternatively, they should use {@link #nullSafe()} method while * registering the type adapter with Gson. If your {@code Gson} instance * has been configured to {@link GsonBuilder#serializeNulls()}, these nulls will be * written to the final document. Otherwise the value (and the corresponding name * when writing to a JSON object) will be omitted automatically. In either case * your type adapter must handle null. * * <p>To use a custom type adapter with Gson, you must <i>register</i> it with a * {@link GsonBuilder}: <pre> {@code * * GsonBuilder builder = new GsonBuilder(); * builder.registerTypeAdapter(Point.class, new PointAdapter()); * // if PointAdapter didn't check for nulls in its read/write methods, you should instead use * // builder.registerTypeAdapter(Point.class, new PointAdapter().nullSafe()); * ... * Gson gson = builder.create(); * }</pre> * * @since 2.1 */ // non-Javadoc: // // <h3>JSON Conversion</h3> // <p>A type adapter registered with Gson is automatically invoked while serializing // or deserializing JSON. However, you can also use type adapters directly to serialize // and deserialize JSON. Here is an example for deserialization: <pre> {@code // // String json = "{'origin':'0,0','points':['1,2','3,4']}"; // TypeAdapter<Graph> graphAdapter = gson.getAdapter(Graph.class); // Graph graph = graphAdapter.fromJson(json); // }</pre> // And an example for serialization: <pre> {@code // // Graph graph = new Graph(...); // TypeAdapter<Graph> graphAdapter = gson.getAdapter(Graph.class); // String json = graphAdapter.toJson(graph); // }</pre> // // <p>Type adapters are <strong>type-specific</strong>. For example, a {@code // TypeAdapter<Date>} can convert {@code Date} instances to JSON and JSON to // instances of {@code Date}, but cannot convert any other types. // public abstract class TypeAdapter<T> { /** * Writes one JSON value (an array, object, string, number, boolean or null) * for {@code value}. * * @param value the Java object to write. May be null. */ public abstract void write(JsonWriter out, T value) throws IOException; /** * Converts {@code value} to a JSON document and writes it to {@code out}. * Unlike Gson's similar {@link Gson#toJson(JsonElement, Appendable) toJson} * method, this write is strict. Create a {@link * JsonWriter#setLenient(boolean) lenient} {@code JsonWriter} and call * {@link #write(io.lattengineer.LattEngineerAPI.gson.stream.massivecraft.net.skaidream.SkaiDreamCore.gson.reflect.JsonWriter, Object)} for lenient * writing. * * @param value the Java object to convert. May be null. * @since 2.2 */ public final void toJson(Writer out, T value) throws IOException { JsonWriter writer = new JsonWriter(out); write(writer, value); } /** * This wrapper method is used to make a type adapter null tolerant. In general, a * type adapter is required to handle nulls in write and read methods. Here is how this * is typically done:<br> * <pre> {@code * * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, * new TypeAdapter<Foo>() { * public Foo read(JsonReader in) throws IOException { * if (in.peek() == JsonToken.NULL) { * in.nextNull(); * return null; * } * // read a Foo from in and return it * } * public void write(JsonWriter out, Foo src) throws IOException { * if (src == null) { * out.nullValue(); * return; * } * // write src as JSON to out * } * }).create(); * }</pre> * You can avoid this boilerplate handling of nulls by wrapping your type adapter with * this method. Here is how we will rewrite the above example: * <pre> {@code * * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, * new TypeAdapter<Foo>() { * public Foo read(JsonReader in) throws IOException { * // read a Foo from in and return it * } * public void write(JsonWriter out, Foo src) throws IOException { * // write src as JSON to out * } * }.nullSafe()).create(); * }</pre> * Note that we didn't need to check for nulls in our type adapter after we used nullSafe. */ public final TypeAdapter<T> nullSafe() { return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { TypeAdapter.this.write(out, value); } } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } return TypeAdapter.this.read(reader); } }; } /** * Converts {@code value} to a JSON document. Unlike Gson's similar {@link * Gson#toJson(Object) toJson} method, this write is strict. Create a {@link * JsonWriter#setLenient(boolean) lenient} {@code JsonWriter} and call * {@link #write(io.lattengineer.LattEngineerAPI.gson.stream.massivecraft.net.skaidream.SkaiDreamCore.gson.reflect.JsonWriter, Object)} for lenient * writing. * * @param value the Java object to convert. May be null. * @since 2.2 */ public final String toJson(T value) throws IOException { StringWriter stringWriter = new StringWriter(); toJson(stringWriter, value); return stringWriter.toString(); } /** * Converts {@code value} to a JSON tree. * * @param value the Java object to convert. May be null. * @return the converted JSON tree. May be {@link JsonNull}. * @since 2.2 */ public final JsonElement toJsonTree(T value) { try { JsonTreeWriter jsonWriter = new JsonTreeWriter(); write(jsonWriter, value); return jsonWriter.get(); } catch (IOException e) { throw new JsonIOException(e); } } /** * Reads one JSON value (an array, object, string, number, boolean or null) * and converts it to a Java object. Returns the converted object. * * @return the converted Java object. May be null. */ public abstract T read(JsonReader in) throws IOException; /** * Converts the JSON document in {@code in} to a Java object. Unlike Gson's * similar {@link Gson#fromJson(java.io.Reader, Class) fromJson} method, this * read is strict. Create a {@link JsonReader#setLenient(boolean) lenient} * {@code JsonReader} and call {@link #read(JsonReader)} for lenient reading. * * @return the converted Java object. May be null. * @since 2.2 */ public final T fromJson(Reader in) throws IOException { JsonReader reader = new JsonReader(in); return read(reader); } /** * Converts the JSON document in {@code json} to a Java object. Unlike Gson's * similar {@link Gson#fromJson(String, Class) fromJson} method, this read is * strict. Create a {@link JsonReader#setLenient(boolean) lenient} {@code * JsonReader} and call {@link #read(JsonReader)} for lenient reading. * * @return the converted Java object. May be null. * @since 2.2 */ public final T fromJson(String json) throws IOException { return fromJson(new StringReader(json)); } /** * Converts {@code jsonTree} to a Java object. * * @param jsonTree the Java object to convert. May be {@link JsonNull}. * @since 2.2 */ public final T fromJsonTree(JsonElement jsonTree) { try { JsonReader jsonReader = new JsonTreeReader(jsonTree); return read(jsonReader); } catch (IOException e) { throw new JsonIOException(e); } } }
mit
byhieg/easyweather
app/src/main/java/com/weather/byhieg/easyweather/home/HomeFragment.java
20446
package com.weather.byhieg.easyweather.home; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Debug; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.orhanobut.logger.Logger; import com.weather.byhieg.easyweather.MyApplication; import com.weather.byhieg.easyweather.base.BaseFragment; import com.weather.byhieg.easyweather.data.bean.WeekWeather; import com.weather.byhieg.easyweather.data.source.CityDataSource; import com.weather.byhieg.easyweather.data.source.local.entity.LoveCityEntity; import com.weather.byhieg.easyweather.tools.DateUtil; import com.weather.byhieg.easyweather.tools.DisplayUtil; import com.weather.byhieg.easyweather.tools.ImageUtils; import com.weather.byhieg.easyweather.tools.LogUtils; import com.weather.byhieg.easyweather.home.adapter.PopupWindowAdapter; import com.weather.byhieg.easyweather.data.bean.HoursWeather; import com.weather.byhieg.easyweather.R; import com.weather.byhieg.easyweather.customview.WeekWeatherView; import com.weather.byhieg.easyweather.data.bean.HWeather; import com.weather.byhieg.easyweather.tools.MessageEvent; import com.weather.byhieg.easyweather.tools.ScreenUtil; import com.weather.byhieg.easyweather.tools.WeatherIcon; import com.weather.byhieg.easyweather.tools.WeatherJsonConverter; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import static com.weather.byhieg.easyweather.tools.Constants.UPDATE_SHOW_CITY; import static com.weather.byhieg.easyweather.tools.Constants.UPDATE_WEATHER; import static com.weather.byhieg.easyweather.tools.DisplayUtil.getViewHeight; import static com.weather.byhieg.easyweather.tools.ImageUtils.BRIEF; import static com.weather.byhieg.easyweather.tools.Knife.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; /** * A simple {@link Fragment} subclass. */ public class HomeFragment extends BaseFragment implements HomeContract.View, SwipeRefreshLayout .OnRefreshListener { // @BindView(R.id.arrow) // public ImageView arrow; @BindView(R.id.arrow_detail) public ImageView arrowDetail; @BindView(R.id.expand_view) public LinearLayout expandView; @BindView(R.id.detail) public LinearLayout detail; @BindView(R.id.date) public TextView date; @BindView(R.id.temp) public TextView temp; @BindView(R.id.tempImage) public ImageView tempImage; @BindView(R.id.tempHigh) public TextView tempHigh; @BindView(R.id.tempLow) public TextView tempLow; @BindView(R.id.cloth) public TextView cloth; @BindView(R.id.pm) public TextView pm; @BindView(R.id.hum) public TextView hum; @BindView(R.id.wind) public TextView wind; @BindView(R.id.wind_dir) public TextView windDir; @BindView(R.id.to_detail) public TextView toDetail; @BindView(R.id.qlty) public TextView qlty; @BindView(R.id.vis) public TextView vis; @BindView(R.id.pres) public TextView pres; @BindView(R.id.uv) public TextView uv; @BindView(R.id.sunrise) public TextView sunrise; @BindView(R.id.sunset) public TextView sunset; @BindView(R.id.condition) public TextView condition; @BindView(R.id.scrollView) public ScrollView scrollView; @BindView(R.id.refresh) public ImageView refresh; @BindView(R.id.swipe_refresh) public SwipeRefreshLayout mSwipeLayout; @BindView(R.id.updateTime) public TextView updateTime; @BindView(R.id.cloth_brf) public TextView clothBrf; @BindView(R.id.cloth_txt) public TextView clothTxt; @BindView(R.id.sport_brf) public TextView sportBrf; @BindView(R.id.sport_txt) public TextView sportTxt; @BindView(R.id.action_bar) public LinearLayout action_bar; @BindView(R.id.cold_brf) public TextView codeBrf; @BindView(R.id.cold_txt) public TextView coldTxt; @BindView(R.id.week_Weather_view) public WeekWeatherView weekWeatherView; @BindView(R.id.weather_cond) public TextView weatherCond; @BindView(R.id.update_time_hours) public TextView updateHours; @BindView(R.id.wind_hours) public TextView windHours; @BindView(R.id.weather_tmp) public TextView weatherTmp; @BindView(R.id.item_future) public LinearLayout itemFuture; @BindView(R.id.more) public TextView more; @BindView(R.id.root_layout) public LinearLayout rootLayout; private NetworkChangeReceiver networkChangeReceiver; private HomeContract.Presenter mPresenter; private Callback mCallback; private int[] rotateCount = {0, 0}; private List<HoursWeather> hoursWeathers = new ArrayList<>(); @Override public void onAttach(Context context) { super.onAttach(context); setCallBack((MainActivity) context); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); EventBus.getDefault().post(new MessageEvent(UPDATE_WEATHER)); } void setCallBack(Callback callBack) { mCallback = callBack; } public HomeFragment() { // Required empty public constructor } public static HomeFragment newInstance() { HomeFragment fragment = new HomeFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); ButterKnife.bind(this, view); generateTextView(view); initView(); return view; } private void initView() { mSwipeLayout.setOnRefreshListener(this); mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light); registerBroadCast(); initEvent(); } private void initEvent() { detail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDetail(); } }); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showNoData(); mPresenter.doRefreshInNoData(); } }); more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Logger.d("被点击"); mPresenter.generateDataInPopView(); } }); } @Override public void setPresenter(HomeContract.Presenter presenter) { mPresenter = presenter; } @SuppressLint("SimpleDateFormat") @Override public void updateView(HWeather weather) { mSwipeLayout.setVisibility(View.VISIBLE); mSwipeLayout.setRefreshing(false); refresh.clearAnimation(); refresh.setVisibility(View.GONE); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); date.setText("今天" + simpleDateFormat.format(new Date())); Date sqlDate = convertDate(WeatherJsonConverter.getWeather(weather).getBasic() .getUpdate().getLoc()); long time = DateUtil.getDifferenceofDate(new Date(), sqlDate) / (1000 * 60); if (time > 1000 * 60 * 60 || time < 0) { updateTime.setText("最近更新:" + new SimpleDateFormat("MM-dd HH:mm:ss").format(sqlDate)); } else { updateTime.setText("最近更新:" + time + "分钟之前"); } tempImage.setImageResource(WeatherIcon.getWeatherImage(WeatherJsonConverter.getWeather(weather).getNow().getCond().getCode())); mCallback.updateToolBar(WeatherJsonConverter.getWeather(weather).getBasic().getCity()); //主卡片 temp.setText(WeatherJsonConverter.getWeather(weather).getNow().getTmp() + "°"); tempHigh.setText("高 " + WeatherJsonConverter.getWeather(weather).getDaily_forecast().get(0).getTmp().getMax() + "°"); tempLow.setText("低 " + WeatherJsonConverter.getWeather(weather).getDaily_forecast().get(0).getTmp().getMin() + "°"); cloth.setText(WeatherJsonConverter.getWeather(weather).getSuggestion().getDrsg().getBrf()); condition.setText(WeatherJsonConverter.getWeather(weather).getNow().getCond().getTxt()); if (WeatherJsonConverter.getWeather(weather).getAqi() != null){ pm.setText(WeatherJsonConverter.getWeather(weather).getAqi().getCity().getPm25()); qlty.setText(WeatherJsonConverter.getWeather(weather).getAqi().getCity().getQlty()); } hum.setText(WeatherJsonConverter.getWeather(weather).getNow().getHum() + "%"); wind.setText(WeatherJsonConverter.getWeather(weather).getNow().getWind().getSpd() + "km/h"); windDir.setText(WeatherJsonConverter.getWeather(weather).getNow().getWind().getDir()); vis.setText(WeatherJsonConverter.getWeather(weather).getNow().getVis() + "km"); pres.setText(WeatherJsonConverter.getWeather(weather).getNow().getPres() + "帕"); uv.setText(WeatherJsonConverter.getWeather(weather).getSuggestion().getUv().getBrf()); sunrise.setText(WeatherJsonConverter.getWeather(weather).getDaily_forecast().get(0).getAstro().getSr()); sunset.setText(WeatherJsonConverter.getWeather(weather).getDaily_forecast().get(0).getAstro().getSs()); //穿衣指数 clothBrf.setText(WeatherJsonConverter.getWeather(weather).getSuggestion().getDrsg().getBrf()); clothTxt.setText(WeatherJsonConverter.getWeather(weather).getSuggestion().getDrsg().getTxt()); //运动指数 sportBrf.setText(WeatherJsonConverter.getWeather(weather).getSuggestion().getSport().getBrf()); sportTxt.setText(WeatherJsonConverter.getWeather(weather).getSuggestion().getSport().getTxt()); //感冒指数 codeBrf.setText(WeatherJsonConverter.getWeather(weather).getSuggestion().getFlu().getBrf()); coldTxt.setText(WeatherJsonConverter.getWeather(weather).getSuggestion().getFlu().getTxt()); //未来三小时天气 if (WeatherJsonConverter.getWeather(weather).getHourly_forecast().size() != 0) { weatherCond.setText(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(0).getPop() + "%"); updateHours.setText(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(0).getDate()); windHours.setText(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(0).getWind().getDir() + " " + WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(0).getWind().getSc()); weatherTmp.setText(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(0).getTmp() + "°"); } else { itemFuture.setVisibility(View.GONE); } hoursWeathers.clear(); for (int i = 0; i < WeatherJsonConverter.getWeather(weather).getHourly_forecast().size(); i++) { HoursWeather hw = new HoursWeather(); hw.setTmp(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(i).getTmp() + "°"); hw.setHum(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(i).getHum() + "%"); hw.setWind_class(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(i).getWind().getSc()); hw.setWind_deg(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(i).getWind().getDeg()); hw.setWind_speed(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(i).getWind().getSpd()); hw.setWind_dir(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(i).getWind().getDir()); hw.setPop(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(i).getPop() + "%"); hw.setUpdate(WeatherJsonConverter.getWeather(weather).getHourly_forecast().get(i).getDate()); hoursWeathers.add(hw); } } @Override public void showNoData() { mSwipeLayout.setVisibility(View.GONE); refresh.setVisibility(View.VISIBLE); Animation animation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setDuration(1000); animation.setRepeatCount(-1); animation.setInterpolator(new LinearInterpolator()); refresh.startAnimation(animation); mPresenter.doRefreshInNoData(); } @Override public void showDetail() { if (rotateCount[1] % 2 == 0) { expandView.setVisibility(View.VISIBLE); toDetail.setText("简略"); Animation animation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setDuration(10); animation.setFillAfter(true); arrowDetail.startAnimation(animation); action_bar.setVisibility(View.GONE); } else { expandView.setVisibility(View.GONE); toDetail.setText("详情"); Animation animation = new RotateAnimation(180, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setDuration(10); animation.setFillAfter(true); arrowDetail.startAnimation(animation); action_bar.setVisibility(View.VISIBLE); } rotateCount[1]++; } @Override public void showPopupWindow() { View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.item_popupwindow, null); LinearLayout del = (LinearLayout) contentView.findViewById(R.id.del); ListView listView = (ListView) contentView.findViewById(R.id.popup_listview); PopupWindowAdapter adapter = new PopupWindowAdapter(hoursWeathers, getActivity()); listView.setAdapter(adapter); adapter.notifyDataSetChanged(); final PopupWindow popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true); popupWindow.setTouchable(true); popupWindow.setTouchInterceptor(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; } }); popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(getActivity(), R.color.transparent)); popupWindow.showAtLocation(rootLayout,Gravity.CENTER ,0, 0); del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); } }); } @Override public void onResume() { super.onResume(); if (scrollView != null) { scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (mSwipeLayout != null) { mSwipeLayout.setEnabled(scrollView.getScrollY() == 0); } } }); } } @Override public void setNetWork() { Snackbar.make(rootLayout, "还是没有网络 QAQ", Snackbar.LENGTH_LONG). setAction("点我设置网络", new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS); startActivity(intent); } }).show(); } @Override public void registerBroadCast() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); networkChangeReceiver = new NetworkChangeReceiver(); getActivity().registerReceiver(networkChangeReceiver, intentFilter); } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); getActivity().unregisterReceiver(networkChangeReceiver); } public void generateTextView(View v) { TextView textView = new TextView(getActivity()); textView.setText("天气易变,注意天气变化"); View[] view = {v.findViewById(R.id.toolbar), v.findViewById(R.id.view), v.findViewById(R.id .item_cloths), v.findViewById(R.id.item_sports)}; int totalHeight = 0; for (View aView : view) { totalHeight += getViewHeight(aView, true) + DisplayUtil.dip2px(getActivity(), 10); } int pxHeight = ScreenUtil.getScreenHW2(getActivity())[1] - totalHeight; LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, pxHeight / 2); textView.setGravity(Gravity.CENTER); textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.white)); textView.setLayoutParams(lp); action_bar.addView(textView); } @Override public void updateWeeksView(List<WeekWeather> weathers, String[] weeks,List<Integer> lists) { weekWeatherView.setData(weathers,weeks,lists); Debug.startMethodTracing(); weekWeatherView.notifyDateChanged(); } @Override public void onRefresh() { mPresenter.refreshData(); } @Subscribe(threadMode = ThreadMode.MAIN) public void onHandleMessageEvent(MessageEvent event){ if (event.getMessage() == UPDATE_SHOW_CITY){ mPresenter.getNewShowWeather(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onHandleCityName(CityNameMessage message) { String cityName = message.getCityName(); mPresenter.showDialog(cityName,getActivity()); } @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onHandleBackground(MessageEvent event){ if (event.getMessage() == UPDATE_WEATHER){ ImageUtils.drawImage(MyApplication.getAppContext(),ImageUtils.BRIEF); } } class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) MyApplication .getAppContext() .getSystemService (Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable()) { mPresenter.refreshData(); } } } interface Callback { void updateToolBar(String cityName); } }
mit
yrsegal/ModTweaker2
src/main/java/modtweaker2/mods/forestry/handlers/Carpenter.java
5543
package modtweaker2.mods.forestry.handlers; import static modtweaker2.helpers.InputHelper.toFluid; import static modtweaker2.helpers.InputHelper.toIItemStack; import static modtweaker2.helpers.InputHelper.toILiquidStack; import static modtweaker2.helpers.InputHelper.toStack; import static modtweaker2.helpers.InputHelper.toStacks; import static modtweaker2.helpers.InputHelper.toShapedObjects; import static modtweaker2.helpers.StackHelper.matches; import java.util.LinkedList; import java.util.List; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; import minetweaker.api.liquid.ILiquidStack; import modtweaker2.helpers.LogHelper; import modtweaker2.mods.forestry.ForestryListAddition; import modtweaker2.mods.forestry.ForestryListRemoval; import modtweaker2.mods.forestry.recipes.CarpenterRecipe; import net.minecraft.item.ItemStack; import modtweaker2.mods.forestry.recipes.DescriptiveRecipe; import stanhebben.zenscript.annotations.Optional; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import forestry.api.recipes.ICarpenterManager; import forestry.api.recipes.ICarpenterRecipe; import forestry.api.recipes.IDescriptiveRecipe; import forestry.api.recipes.RecipeManagers; @ZenClass("mods.forestry.Carpenter") public class Carpenter { public static final String name = "Forestry Carpenter"; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Adds a shaped recipe for the Carpenter * * @param output recipe output * @param ingredients recipe ingredients * @param packagingTime time per crafting operation * @optionalParam box recipes casting item (optional) */ @ZenMethod public static void addRecipe(IItemStack output, IIngredient[][] ingredients, int packagingTime, @Optional IItemStack box) { IDescriptiveRecipe craftRecipe = new DescriptiveRecipe(3, 3, toShapedObjects(ingredients), toStack(output), false); MineTweakerAPI.apply(new Add(new CarpenterRecipe(packagingTime, null, toStack(box), craftRecipe))); } /** * Adds a shaped recipe for the Carpenter * * @param output recipe output * @param ingredients recipe ingredients * @param fluidInput recipe fluid amount * @param packagingTime time per crafting operation * @optionalParam box recipes casting item (optional) */ @ZenMethod public static void addRecipe(IItemStack output, IIngredient[][] ingredients, ILiquidStack fluidInput, int packagingTime, @Optional IItemStack box) { IDescriptiveRecipe craftRecipe = new DescriptiveRecipe(3, 3, toShapedObjects(ingredients), toStack(output), false); MineTweakerAPI.apply(new Add(new CarpenterRecipe(packagingTime, toFluid(fluidInput), toStack(box), craftRecipe))); } @Deprecated @ZenMethod public static void addRecipe(int packagingTime, ILiquidStack fluidInput, IItemStack[] ingredients, IItemStack box, IItemStack output) { IDescriptiveRecipe craftRecipe = new DescriptiveRecipe(3, 3, toShapedObjects(transform(ingredients, 3)), toStack(output), false); MineTweakerAPI.apply(new Add(new CarpenterRecipe(packagingTime, toFluid(fluidInput), toStack(box), craftRecipe))); } private static IItemStack[][] transform(IItemStack[] arr, int N) { int M = (arr.length + N - 1) / N; IItemStack[][] mat = new IItemStack[M][]; int start = 0; for (int r = 0; r < M; r++) { int L = Math.min(N, arr.length - start); mat[r] = java.util.Arrays.copyOfRange(arr, start, start + L); start += L; } return mat; } private static class Add extends ForestryListAddition<ICarpenterRecipe, ICarpenterManager> { public Add(ICarpenterRecipe recipe) { super(Carpenter.name, RecipeManagers.carpenterManager); recipes.add(recipe); } @Override protected String getRecipeInfo(ICarpenterRecipe recipe) { return LogHelper.getStackDescription(recipe.getCraftingGridRecipe().getRecipeOutput()); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Removes a recipe for the Carpenter * * @param output = item output * @optionalParam liquid = liquid input */ @ZenMethod public static void removeRecipe(IIngredient output, @Optional IIngredient liquid) { List<ICarpenterRecipe> recipes = new LinkedList<ICarpenterRecipe>(); for(ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { if (recipe != null) { ItemStack recipeResult = recipe.getCraftingGridRecipe().getRecipeOutput(); if (recipeResult != null && matches(output, toIItemStack(recipeResult))) { if (liquid != null) { if (matches(liquid, toILiquidStack(recipe.getFluidResource()))) recipes.add(recipe); } else { recipes.add(recipe); } } } } if(!recipes.isEmpty()) { MineTweakerAPI.apply(new Remove(recipes)); } else { LogHelper.logWarning(String.format("No %s Recipe found for %s. Command ignored!", Carpenter.name, output.toString())); } } private static class Remove extends ForestryListRemoval<ICarpenterRecipe, ICarpenterManager> { public Remove(List<ICarpenterRecipe> recipes) { super(Carpenter.name, RecipeManagers.carpenterManager, recipes); } @Override protected String getRecipeInfo(ICarpenterRecipe recipe) { return LogHelper.getStackDescription(recipe.getCraftingGridRecipe().getRecipeOutput()); } } }
mit
Daniel-Tilley/SimpleAndroidApps
VolleyApp/app/src/test/java/com/example/danieltilley/volleyapp/ExampleUnitTest.java
412
package com.example.danieltilley.volleyapp; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/network/v2020_04_01/implementation/ApplicationGatewaySslPredefinedPolicyImpl.java
1584
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_04_01.implementation; import com.microsoft.azure.management.network.v2020_04_01.ApplicationGatewaySslPredefinedPolicy; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import java.util.List; import com.microsoft.azure.management.network.v2020_04_01.ApplicationGatewaySslCipherSuite; import com.microsoft.azure.management.network.v2020_04_01.ApplicationGatewaySslProtocol; class ApplicationGatewaySslPredefinedPolicyImpl extends WrapperImpl<ApplicationGatewaySslPredefinedPolicyInner> implements ApplicationGatewaySslPredefinedPolicy { private final NetworkManager manager; ApplicationGatewaySslPredefinedPolicyImpl(ApplicationGatewaySslPredefinedPolicyInner inner, NetworkManager manager) { super(inner); this.manager = manager; } @Override public NetworkManager manager() { return this.manager; } @Override public List<ApplicationGatewaySslCipherSuite> cipherSuites() { return this.inner().cipherSuites(); } @Override public String id() { return this.inner().id(); } @Override public ApplicationGatewaySslProtocol minProtocolVersion() { return this.inner().minProtocolVersion(); } @Override public String name() { return this.inner().name(); } }
mit
Mazdallier/AgriCraft
src/main/java/com/InfinityRaider/AgriCraft/handler/BonemealEventHandler.java
1127
package com.InfinityRaider.AgriCraft.handler; import com.InfinityRaider.AgriCraft.blocks.BlockCrop; import com.InfinityRaider.AgriCraft.tileentity.TileEntityCrop; import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.event.entity.player.BonemealEvent; import java.util.Random; //a class to handle bonemeal events public class BonemealEventHandler { @SubscribeEvent public void onBonemealEvent(BonemealEvent event) { if (event.block instanceof BlockCrop) { TileEntityCrop crop = (TileEntityCrop) event.world.getTileEntity(event.x, event.y, event.z); if((crop.hasPlant() && crop.getBlockMetadata()<7) || (crop.crossCrop && ConfigurationHandler.bonemealMutation)) { ((BlockCrop) event.world.getBlock(event.x, event.y, event.z)).func_149853_b(event.world, new Random(), event.x, event.y, event.z); event.setResult(Event.Result.ALLOW); } else { event.setCanceled(true); event.setResult(Event.Result.DENY); } } } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/GroupDeltaCollectionRequest.java
5194
// Template Source: BaseMethodCollectionRequest.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.Group; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.requests.GroupDeltaCollectionRequestBuilder; import com.microsoft.graph.requests.GroupDeltaCollectionResponse; import com.microsoft.graph.models.Group; import com.microsoft.graph.options.QueryOption; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseDeltaCollectionRequest; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Group Delta Collection Request. */ public class GroupDeltaCollectionRequest extends BaseDeltaCollectionRequest<Group, GroupDeltaCollectionResponse, GroupDeltaCollectionPage> { /** * The request for this GroupDelta * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public GroupDeltaCollectionRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions, GroupDeltaCollectionResponse.class, GroupDeltaCollectionPage.class, GroupDeltaCollectionRequestBuilder.class); } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest select(@Nonnull final String value) { addSelectOption(value); return this; } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest expand(@Nonnull final String value) { addExpandOption(value); return this; } /** * Sets the filter clause for the request * * @param value the filter clause * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest filter(@Nonnull final String value) { addFilterOption(value); return this; } /** * Sets the order by clause for the request * * @param value the order by clause * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest orderBy(@Nonnull final String value) { addOrderByOption(value); return this; } /** * Sets the count value for the request * * @param value whether or not to return the count of objects with the request * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest count(final boolean value) { addCountOption(value); return this; } /** * Sets the count value to true for the request * * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest count() { addCountOption(true); return this; } /** * Sets the top value for the request * * @param value the max number of items to return * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest top(final int value) { addTopOption(value); return this; } /** * Sets the skip value for the request * * @param value of the number of items to skip * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest skip(final int value) { addSkipOption(value); return this; } /** * Add Skip token for pagination * @param skipToken - Token for pagination * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest skipToken(@Nonnull final String skipToken) { addSkipTokenOption(skipToken); return this; } /** * Add Delta token for request * @param deltaToken - Token to resume sync * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest deltaToken(@Nonnull final String deltaToken) { addDeltaTokenOption(deltaToken, "$deltatoken"); return this; } /** * Parses the Delta token from the Delta Link and adds it for request * @param deltaLink - Delta Link provided by previous response to resume sync * @return the updated request */ @Nonnull public GroupDeltaCollectionRequest deltaLink(@Nonnull final String deltaLink) { addDeltaTokenOption(getDeltaTokenFromLink(deltaLink), "$deltatoken"); return this; } }
mit
loafer/spring4-tutorials
spring-redis/src/test/java/com/github/loafer/example/spring/redis/StringCommandTest.java
5516
package com.github.loafer.example.spring.redis; import static org.assertj.core.api.Assertions.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import redis.clients.jedis.Jedis; /** * @author zhaojh. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/spring-redis-jedis.xml"}) //@ContextConfiguration({"/spring-redis-lettuce.xml"}) public class StringCommandTest { private Logger logger = LoggerFactory.getLogger(StringCommandTest.class); @Resource private RedisTemplate redisTemplate; @Resource private StringRedisTemplate stringRedisTemplate; @Before public void flushdb(){ redisTemplate.execute(new RedisCallback<Object>() { public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); return null; } }); } @Test public void testSet(){ redisTemplate.opsForValue().set("key", "value"); String value = stringRedisTemplate.opsForValue().get("key"); assertThat(value).isEqualToIgnoringCase("value"); redisTemplate.opsForValue().set("key", "new value"); String newValue = stringRedisTemplate.opsForValue().get("key"); assertThat(newValue).isEqualToIgnoringCase("new value"); } @Test public void testAppend() throws InterruptedException { // StringRedisSerializer serializer = new StringRedisSerializer(); // template.setKeySerializer(serializer); // template.setValueSerializer(serializer); final String KEY = "hello"; final String S1 = "Good"; final String S2 = " Morning!"; redisTemplate.opsForValue().set(KEY, S1); String value = (String) redisTemplate.opsForValue().get(KEY); assertThat(value).isEqualToIgnoringCase(S1); redisTemplate.opsForValue().append(KEY, S2); String newValue = (String) redisTemplate.opsForValue().get(KEY); logger.info("new value: {}", newValue); } @Test public void testAppend2(){ final String KEY = "hello"; final String S1 = "Good"; final String S2 = " Morning!"; stringRedisTemplate.opsForValue().set(KEY, S1); String value = stringRedisTemplate.opsForValue().get(KEY); assertThat(value).isEqualToIgnoringCase(S1); stringRedisTemplate.opsForValue().append(KEY, S2); String newValue = stringRedisTemplate.opsForValue().get(KEY); assertThat(newValue).isEqualToIgnoringCase(S1 + S2); } @Test public void testAppend3(){ final String KEY = "hello"; final String S1 = "Good"; final String S2 = " Morning!"; Jedis jedis = createJedis(); jedis.set(KEY.getBytes(), S1.getBytes()); byte[] bytes = jedis.get(KEY.getBytes()); logger.info("value: {}", new String(bytes)); assertThat(new String(bytes)).isEqualToIgnoringCase(S1); jedis.append(KEY.getBytes(), S2.getBytes()); byte[] newbytes = jedis.get(KEY.getBytes()); logger.info("new value: {}", new String(newbytes)); assertThat(new String(newbytes)).isEqualToIgnoringCase(S1+S2); } @Test public void testGetAndSet(){ final String KEY = "key"; final String S1 = "value"; final String S2 = "newValue"; redisTemplate.opsForValue().set(KEY, S1); String value = (String) redisTemplate.opsForValue().getAndSet(KEY, S2); String newValue = (String) redisTemplate.opsForValue().get(KEY); assertThat(value).isEqualToIgnoringCase(S1); assertThat(newValue).isEqualToIgnoringCase(S2); } @Test public void testIncrement(){ final String KEY = "count"; // redisTemplate.opsForValue().set(KEY, "100"); // Long value = redisTemplate.opsForValue().increment(KEY, 50L); // assertThat(value).isEqualTo(150); stringRedisTemplate.opsForValue().set(KEY, "100"); Long value = stringRedisTemplate.opsForValue().increment(KEY, 50); assertThat(value).isEqualTo(150); } @Test public void testIncrByFloat(){ final String KEY = "mykey"; stringRedisTemplate.opsForValue().set(KEY, "10.5"); Double value = stringRedisTemplate.opsForValue().increment(KEY, 0.1d); assertThat(value).isEqualTo(10.6); } @Test public void testMultiSet(){ Map<String, Object> map = new HashMap<String, Object>(){ { put("redis", "redis.com"); put("mongodb", "mongodb.org"); put("website", 2); put("money", "1000"); } }; redisTemplate.opsForValue().multiSet(map); Set<String> keys = new HashSet<String>(Arrays.asList(new String[]{"redis", "mongodb", "website","money"})); List values = redisTemplate.opsForValue().multiGet(keys); logger.info("values: {}", values); assertThat(values).contains("redis.com", "mongodb.org", 2, "1000"); } private Jedis createJedis(){ Jedis j = new Jedis("localhost", 6379); j.connect(); j.select(1); // j.flushAll(); return j; } }
mit
sweetcode/TextAdventure
src/de/SweetCode/TextAdventure/Dungeon/Dungeons/ScienceDungeon.java
581
package de.SweetCode.TextAdventure.Dungeon.Dungeons; import de.SweetCode.TextAdventure.Dungeon.Dungeon; import de.SweetCode.TextAdventure.Entity.Entities.Player; import sun.reflect.generics.reflectiveObjects.NotImplementedException; /** * Created by Yonas on 07.09.2015. */ public class ScienceDungeon extends Dungeon { public ScienceDungeon(String name, Player player) { super(name, player); } @Override public void start() { //Ein Rebensaft der von einem Pilz vorverdaut wurde? - Wein throw new NotImplementedException(); } }
mit
teoreteetik/api-snippets
rest/usage-triggers/list-post-example-1/list-post-example-1.7.x.java
738
// Install the Java helper library from twilio.com/docs/java/install import java.net.URI; import java.net.URISyntaxException; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.usage.Trigger; public class Example { // Find your Account Sid and Token at twilio.com/user/account public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; public static final String AUTH_TOKEN = "your_auth_token"; public static void main(String[] args) throws URISyntaxException { Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Trigger trigger = Trigger .creator(new URI("http://www.example.com/"), "1000", Trigger.UsageCategory.SMS) .create(); System.out.println(trigger.getSid()); } }
mit
arnosthavelka/owcd-cert
src/main/java/com/github/aha/cert/exception/MyRuntimeException.java
220
package com.github.aha.cert.exception; public class MyRuntimeException extends RuntimeException { private static final long serialVersionUID = 1L; public MyRuntimeException(String message) { super(message); } }
mit
kercos/TreeGrammars
TreeGrammars/src/tsg/utils/CheckTreebankWordsConsistency.java
1266
package tsg.utils; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import tsg.TSNodeLabel; public class CheckTreebankWordsConsistency { public static void main(String[] args) throws Exception { File treebankFile1 = new File(args[0]); File treebankFile2 = new File(args[0]); ArrayList<TSNodeLabel> treebank1 = TSNodeLabel.getTreebank(treebankFile1); ArrayList<TSNodeLabel> treebank2 = TSNodeLabel.getTreebank(treebankFile2); if (treebank1.size() != treebank2.size()) { System.err.println("Sizes differ:"); System.err.println(treebankFile1 + " -> " + treebank1.size()); System.err.println(treebankFile2 + " -> " + treebank2.size()); return; } Iterator<TSNodeLabel> iter1 = treebank1.iterator(); Iterator<TSNodeLabel> iter2 = treebank2.iterator(); int index = 0; boolean mistake = false; while(iter1.hasNext()) { index++; TSNodeLabel t1 = iter1.next(); TSNodeLabel t2 = iter2.next(); if (!t1.toFlatSentence().equals(t2.toFlatSentence())) { System.out.println("Inconsistent at index: " + index); System.out.println(t1.toFlatSentence()); System.out.println(t2.toFlatSentence()); mistake = true; break; } } if (!mistake) System.out.println("OK!"); } }
mit
NickEckert/thunder
application/src/main/java/com/sanction/thunder/ThunderConfiguration.java
672
package com.sanction.thunder; import com.fasterxml.jackson.annotation.JsonProperty; import com.sanction.thunder.authentication.Key; import io.dropwizard.Configuration; import java.util.List; import javax.validation.Valid; import javax.validation.constraints.NotNull; public class ThunderConfiguration extends Configuration { @NotNull @Valid @JsonProperty("dynamo-endpoint") private final String dynamoEndpoint = null; public String getDynamoEndpoint() { return dynamoEndpoint; } @NotNull @Valid @JsonProperty("approved-keys") private final List<Key> approvedKeys = null; public List<Key> getApprovedKeys() { return approvedKeys; } }
mit
jsuarezb/paw-2016-4
persistence/src/main/java/ar/edu/itba/paw/persistence/hibernate/UserHibernateDao.java
2045
package ar.edu.itba.paw.persistence.hibernate; import ar.edu.itba.paw.models.Patient; import ar.edu.itba.paw.models.User; import ar.edu.itba.paw.persistence.UserDao; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.Query; /** * Created by agophurmuz on 5/18/16. */ @Repository public class UserHibernateDao implements UserDao { @PersistenceContext private EntityManager em; @Transactional public User create(String email, String password, String firstName, String lastName, String phone) { final Patient patient = new Patient(); em.persist(patient); final User user = new User(firstName, lastName, email, password, phone, patient, null); em.persist(user); return user; } public User findByEmail(String email) { final TypedQuery<User> query = em.createQuery("from User as u where u.email = :email", User.class); query.setParameter("email", email); try { return query.getSingleResult(); } catch (NoResultException e) { return null; } } public User getById(final Integer id) { final TypedQuery<User> query = em.createQuery("from User as u where u.id = :id", User.class); query.setParameter("id", id); try { return query.getSingleResult(); } catch (NoResultException e) { return null; } } @Transactional public User setPassword(final User user, final String password) { final Query query = em.createQuery("UPDATE User u SET u.password = :password WHERE u.id = :id"); query.setParameter("password", password); query.setParameter("id", user.getId()); query.executeUpdate(); user.setPassword(password); return user; } }
mit
swaplicado/siie32
src/erp/mod/log/form/SFormShipmentDelivery.java
20991
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mod.log.form; import erp.lib.SLibConstants; import erp.mod.SModConsts; import erp.mod.SModSysConsts; import erp.mod.log.db.SDbShipment; import erp.mod.log.db.SDbShipmentDestiny; import sa.lib.SLibConsts; import sa.lib.SLibUtils; import sa.lib.db.SDbRegistry; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiParams; import sa.lib.gui.SGuiUtils; import sa.lib.gui.SGuiValidation; /** * * @author Juan Barajas */ public class SFormShipmentDelivery extends sa.lib.gui.bean.SBeanForm { private SDbShipmentDestiny moRegistry; /** * Creates new form SFormShipmentDelivery */ public SFormShipmentDelivery(SGuiClient client, String title) { setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.LOGX_SHIP_DLY, SLibConstants.UNDEFINED, title); initComponents(); initComponentsCustom(); } /** * 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() { jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jPanel23 = new javax.swing.JPanel(); jPanel25 = new javax.swing.JPanel(); jlCompanyBranch = new javax.swing.JLabel(); moKeyCompanyBranch = new sa.lib.gui.bean.SBeanFieldKey(); jPanel26 = new javax.swing.JPanel(); jlShipmentType = new javax.swing.JLabel(); moKeyShipmentType = new sa.lib.gui.bean.SBeanFieldKey(); jPanel27 = new javax.swing.JPanel(); jlDeliveryType = new javax.swing.JLabel(); moKeyDeliveryType = new sa.lib.gui.bean.SBeanFieldKey(); jPanel28 = new javax.swing.JPanel(); jlNumber = new javax.swing.JLabel(); moTextNumber = new sa.lib.gui.bean.SBeanFieldText(); jPanel30 = new javax.swing.JPanel(); jlDate = new javax.swing.JLabel(); moDateDate = new sa.lib.gui.bean.SBeanFieldDate(); jPanel5 = new javax.swing.JPanel(); jPanel24 = new javax.swing.JPanel(); jPanel33 = new javax.swing.JPanel(); jlSpot = new javax.swing.JLabel(); moKeySpot = new sa.lib.gui.bean.SBeanFieldKey(); jPanel32 = new javax.swing.JPanel(); jlCustomer = new javax.swing.JLabel(); moKeyCustomer = new sa.lib.gui.bean.SBeanFieldKey(); jPanel35 = new javax.swing.JPanel(); jlCustomerBranch = new javax.swing.JLabel(); moKeyCustomerBranch = new sa.lib.gui.bean.SBeanFieldKey(); jPanel36 = new javax.swing.JPanel(); jlCustomerBranchAddress = new javax.swing.JLabel(); moKeyCustomerBranchAddress = new sa.lib.gui.bean.SBeanFieldKey(); jPanel37 = new javax.swing.JPanel(); jlWarehouseCompanyBranch = new javax.swing.JLabel(); moKeyWarehouseCompanyBranch = new sa.lib.gui.bean.SBeanFieldKey(); jPanel38 = new javax.swing.JPanel(); jlWarehouseEntity = new javax.swing.JLabel(); moKeyWarehouseEntity = new sa.lib.gui.bean.SBeanFieldKey(); jPanel22 = new javax.swing.JPanel(); jlDateDelivery = new javax.swing.JLabel(); moDateDateDelivery = new sa.lib.gui.bean.SBeanFieldDate(); jPanel34 = new javax.swing.JPanel(); jlDateDeliveryReal = new javax.swing.JLabel(); moDateDateDeliveryReal = new sa.lib.gui.bean.SBeanFieldDate(); setTitle("Asignación fecha de entrega real"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:")); jPanel1.setLayout(new java.awt.BorderLayout(0, 5)); jPanel2.setLayout(new java.awt.BorderLayout()); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del embarque:")); jPanel4.setLayout(new java.awt.BorderLayout()); jPanel23.setLayout(new java.awt.GridLayout(8, 1, 0, 5)); jPanel25.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCompanyBranch.setText("Sucursal:"); jlCompanyBranch.setEnabled(false); jlCompanyBranch.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel25.add(jlCompanyBranch); moKeyCompanyBranch.setEnabled(false); moKeyCompanyBranch.setFocusable(true); moKeyCompanyBranch.setPreferredSize(new java.awt.Dimension(200, 23)); jPanel25.add(moKeyCompanyBranch); jPanel23.add(jPanel25); jPanel26.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlShipmentType.setText("Tipo embarque:"); jlShipmentType.setEnabled(false); jlShipmentType.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel26.add(jlShipmentType); moKeyShipmentType.setEnabled(false); moKeyShipmentType.setFocusable(true); moKeyShipmentType.setPreferredSize(new java.awt.Dimension(200, 23)); jPanel26.add(moKeyShipmentType); jPanel23.add(jPanel26); jPanel27.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDeliveryType.setText("Tipo entrega:"); jlDeliveryType.setEnabled(false); jlDeliveryType.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel27.add(jlDeliveryType); moKeyDeliveryType.setEnabled(false); moKeyDeliveryType.setFocusable(true); moKeyDeliveryType.setPreferredSize(new java.awt.Dimension(200, 23)); jPanel27.add(moKeyDeliveryType); jPanel23.add(jPanel27); jPanel28.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlNumber.setText("Folio:"); jlNumber.setEnabled(false); jlNumber.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel28.add(jlNumber); moTextNumber.setEditable(false); moTextNumber.setFocusable(true); jPanel28.add(moTextNumber); jPanel23.add(jPanel28); jPanel30.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDate.setText("Fecha:"); jlDate.setEnabled(false); jlDate.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel30.add(jlDate); moDateDate.setEditable(false); moDateDate.setFocusable(true); jPanel30.add(moDateDate); jPanel23.add(jPanel30); jPanel4.add(jPanel23, java.awt.BorderLayout.NORTH); jPanel2.add(jPanel4, java.awt.BorderLayout.WEST); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del destino:")); jPanel5.setLayout(new java.awt.BorderLayout()); jPanel24.setLayout(new java.awt.GridLayout(9, 1, 0, 5)); jPanel33.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlSpot.setText("Destino:"); jlSpot.setEnabled(false); jlSpot.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel33.add(jlSpot); moKeySpot.setEnabled(false); moKeySpot.setFocusable(true); moKeySpot.setPreferredSize(new java.awt.Dimension(250, 23)); jPanel33.add(moKeySpot); jPanel24.add(jPanel33); jPanel32.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCustomer.setText("Cliente:"); jlCustomer.setEnabled(false); jlCustomer.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel32.add(jlCustomer); moKeyCustomer.setEnabled(false); moKeyCustomer.setFocusable(true); moKeyCustomer.setPreferredSize(new java.awt.Dimension(250, 23)); jPanel32.add(moKeyCustomer); jPanel24.add(jPanel32); jPanel35.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCustomerBranch.setText("Sucursal:"); jlCustomerBranch.setEnabled(false); jlCustomerBranch.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel35.add(jlCustomerBranch); moKeyCustomerBranch.setEnabled(false); moKeyCustomerBranch.setFocusable(true); moKeyCustomerBranch.setPreferredSize(new java.awt.Dimension(250, 23)); jPanel35.add(moKeyCustomerBranch); jPanel24.add(jPanel35); jPanel36.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCustomerBranchAddress.setText("Domicilio entrega:"); jlCustomerBranchAddress.setEnabled(false); jlCustomerBranchAddress.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel36.add(jlCustomerBranchAddress); moKeyCustomerBranchAddress.setEnabled(false); moKeyCustomerBranchAddress.setFocusable(true); moKeyCustomerBranchAddress.setPreferredSize(new java.awt.Dimension(250, 23)); jPanel36.add(moKeyCustomerBranchAddress); jPanel24.add(jPanel36); jPanel37.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlWarehouseCompanyBranch.setText("Sucursal:"); jlWarehouseCompanyBranch.setEnabled(false); jlWarehouseCompanyBranch.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel37.add(jlWarehouseCompanyBranch); moKeyWarehouseCompanyBranch.setEnabled(false); moKeyWarehouseCompanyBranch.setFocusable(true); moKeyWarehouseCompanyBranch.setPreferredSize(new java.awt.Dimension(250, 23)); jPanel37.add(moKeyWarehouseCompanyBranch); jPanel24.add(jPanel37); jPanel38.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlWarehouseEntity.setText("Almacén:"); jlWarehouseEntity.setEnabled(false); jlWarehouseEntity.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel38.add(jlWarehouseEntity); moKeyWarehouseEntity.setEnabled(false); moKeyWarehouseEntity.setFocusable(true); moKeyWarehouseEntity.setPreferredSize(new java.awt.Dimension(250, 23)); jPanel38.add(moKeyWarehouseEntity); jPanel24.add(jPanel38); jPanel22.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDateDelivery.setText("Fecha entrega:"); jlDateDelivery.setEnabled(false); jlDateDelivery.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel22.add(jlDateDelivery); moDateDateDelivery.setEditable(false); moDateDateDelivery.setFocusable(true); jPanel22.add(moDateDateDelivery); jPanel24.add(jPanel22); jPanel34.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDateDeliveryReal.setText("Fecha ent. real: *"); jlDateDeliveryReal.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel34.add(jlDateDeliveryReal); jPanel34.add(moDateDateDeliveryReal); jPanel24.add(jPanel34); jPanel5.add(jPanel24, java.awt.BorderLayout.CENTER); jPanel2.add(jPanel5, java.awt.BorderLayout.CENTER); jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel22; private javax.swing.JPanel jPanel23; private javax.swing.JPanel jPanel24; private javax.swing.JPanel jPanel25; private javax.swing.JPanel jPanel26; private javax.swing.JPanel jPanel27; private javax.swing.JPanel jPanel28; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel30; private javax.swing.JPanel jPanel32; private javax.swing.JPanel jPanel33; private javax.swing.JPanel jPanel34; private javax.swing.JPanel jPanel35; private javax.swing.JPanel jPanel36; private javax.swing.JPanel jPanel37; private javax.swing.JPanel jPanel38; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JLabel jlCompanyBranch; private javax.swing.JLabel jlCustomer; private javax.swing.JLabel jlCustomerBranch; private javax.swing.JLabel jlCustomerBranchAddress; private javax.swing.JLabel jlDate; private javax.swing.JLabel jlDateDelivery; private javax.swing.JLabel jlDateDeliveryReal; private javax.swing.JLabel jlDeliveryType; private javax.swing.JLabel jlNumber; private javax.swing.JLabel jlShipmentType; private javax.swing.JLabel jlSpot; private javax.swing.JLabel jlWarehouseCompanyBranch; private javax.swing.JLabel jlWarehouseEntity; private sa.lib.gui.bean.SBeanFieldDate moDateDate; private sa.lib.gui.bean.SBeanFieldDate moDateDateDelivery; private sa.lib.gui.bean.SBeanFieldDate moDateDateDeliveryReal; private sa.lib.gui.bean.SBeanFieldKey moKeyCompanyBranch; private sa.lib.gui.bean.SBeanFieldKey moKeyCustomer; private sa.lib.gui.bean.SBeanFieldKey moKeyCustomerBranch; private sa.lib.gui.bean.SBeanFieldKey moKeyCustomerBranchAddress; private sa.lib.gui.bean.SBeanFieldKey moKeyDeliveryType; private sa.lib.gui.bean.SBeanFieldKey moKeyShipmentType; private sa.lib.gui.bean.SBeanFieldKey moKeySpot; private sa.lib.gui.bean.SBeanFieldKey moKeyWarehouseCompanyBranch; private sa.lib.gui.bean.SBeanFieldKey moKeyWarehouseEntity; private sa.lib.gui.bean.SBeanFieldText moTextNumber; // End of variables declaration//GEN-END:variables private void initComponentsCustom() { SGuiUtils.setWindowBounds(this, 720, 450); moKeyCompanyBranch.setKeySettings(miClient, SGuiUtils.getLabelName(jlCompanyBranch.getText()), true); moKeyShipmentType.setKeySettings(miClient, SGuiUtils.getLabelName(jlShipmentType.getText()), true); moKeyDeliveryType.setKeySettings(miClient, SGuiUtils.getLabelName(jlDeliveryType.getText()), true); moDateDate.setDateSettings(miClient, SGuiUtils.getLabelName(jlDate.getText()), true); moTextNumber.setTextSettings(SGuiUtils.getLabelName(jlNumber.getText()), 15); moKeySpot.setKeySettings(miClient, SGuiUtils.getLabelName(jlSpot.getText()), true); moKeyCustomer.setKeySettings(miClient, SGuiUtils.getLabelName(jlCustomer.getText()), false); moKeyCustomerBranch.setKeySettings(miClient, SGuiUtils.getLabelName(jlCustomerBranch.getText()), false); moKeyCustomerBranchAddress.setKeySettings(miClient, SGuiUtils.getLabelName(jlCustomerBranchAddress.getText()), false); moKeyWarehouseCompanyBranch.setKeySettings(miClient, SGuiUtils.getLabelName(jlWarehouseCompanyBranch.getText()), false); moKeyWarehouseEntity.setKeySettings(miClient, SGuiUtils.getLabelName(jlWarehouseEntity.getText()), false); moDateDateDelivery.setDateSettings(miClient, SGuiUtils.getLabelName(jlDateDelivery.getText()), true); moDateDateDeliveryReal.setDateSettings(miClient, SGuiUtils.getLabelName(jlDateDeliveryReal.getText()), true); moFields.addField(moKeyCompanyBranch); moFields.addField(moKeyShipmentType); moFields.addField(moKeyDeliveryType); moFields.addField(moDateDate); moFields.addField(moTextNumber); moFields.addField(moKeySpot); moFields.addField(moKeyCustomer); moFields.addField(moKeyCustomerBranch); moFields.addField(moKeyCustomerBranchAddress); moFields.addField(moKeyWarehouseCompanyBranch); moFields.addField(moKeyWarehouseEntity); moFields.addField(moDateDateDelivery); moFields.addField(moDateDateDeliveryReal); moFields.setFormButton(jbSave); } @Override public void addAllListeners() { } @Override public void removeAllListeners() { } @Override public void reloadCatalogues() { SGuiParams params = new SGuiParams(new int[] { SModSysConsts.BPSS_CT_BP_CUS }); miClient.getSession().populateCatalogue(moKeyCompanyBranch, SModConsts.BPSU_BPB, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeyShipmentType, SModConsts.LOGS_TP_SHIP, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeyDeliveryType, SModConsts.LOGS_TP_DLY, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeySpot, SModConsts.LOGU_SPOT, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeyCustomer, SModConsts.BPSU_BP, SLibConsts.UNDEFINED, params); miClient.getSession().populateCatalogue(moKeyCustomerBranch, SModConsts.BPSU_BPB, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeyCustomerBranchAddress, SModConsts.BPSU_BPB_ADD, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeyWarehouseCompanyBranch, SModConsts.BPSU_BPB, SLibConsts.UNDEFINED, null); miClient.getSession().populateCatalogue(moKeyWarehouseEntity, SModConsts.CFGU_COB_ENT, SLibConsts.UNDEFINED, null); } @Override public void setRegistry(SDbRegistry registry) throws Exception { moRegistry = (SDbShipmentDestiny) registry; SDbShipment shipment = null; mnFormResult = SLibConsts.UNDEFINED; mbFirstActivation = true; removeAllListeners(); reloadCatalogues(); if (moRegistry.isRegistryNew()) { moRegistry.initPrimaryKey(); jtfRegistryKey.setText(""); } else { jtfRegistryKey.setText(SLibUtils.textKey(moRegistry.getPrimaryKey())); } shipment = (SDbShipment) miClient.getSession().readRegistry(SModConsts.LOG_SHIP, new int[] { moRegistry.getPkShipmentId() }); moKeySpot.setValue(new int[] { moRegistry.getFkSpotId() }); moKeyCustomer.setValue(new int[] { moRegistry.getFkCustomerId_n() }); moKeyCustomerBranch.setValue(new int[] { moRegistry.getFkCustomerBranchId_n() }); moKeyCustomerBranchAddress.setValue(new int[] { moRegistry.getFkCustomerBranchId_n(), moRegistry.getFkCustomerBranchAddressId_n()}); moKeyWarehouseCompanyBranch.setValue(new int[] { moRegistry.getFkWarehouseCompanyBranchId_n() }); moKeyWarehouseEntity.setValue(new int[] { moRegistry.getFkWarehouseCompanyBranchId_n(), moRegistry.getFkWarehouseEntityId_n() }); moDateDateDelivery.setValue(moRegistry.getDateDelivery()); moDateDateDeliveryReal.setValue(moRegistry.getDateDeliveryReal()); moKeyCompanyBranch.setValue(new int[] { shipment.getFkCompanyBranchId() }); moKeyShipmentType.setValue(new int[] { shipment.getFkShipmentTypeId() }); moKeyDeliveryType.setValue(new int[] { shipment.getFkDeliveryTypeId() }); moDateDate.setValue(shipment.getDate() ); moTextNumber.setValue(shipment.getNumber()); setFormEditable(true); moKeySpot.setEnabled(false); moKeyCustomer.setEnabled(false); moKeyCustomerBranch.setEnabled(false); moKeyCustomerBranchAddress.setEnabled(false); moKeyWarehouseCompanyBranch.setEnabled(false); moKeyWarehouseEntity.setEnabled(false); moDateDateDelivery.setEnabled(false); moDateDateDeliveryReal.setEditable(true); moKeyCompanyBranch.setEnabled(false); moKeyShipmentType.setEnabled(false); moKeyDeliveryType.setEnabled(false); moDateDate.setEditable(false); moTextNumber.setEditable(false); if (moRegistry.isRegistryNew()) { moDateDateDeliveryReal.setValue(miClient.getSession().getCurrentDate()); } addAllListeners(); } @Override public SDbRegistry getRegistry() throws Exception { SDbShipmentDestiny registry = moRegistry.clone(); if (registry.isRegistryNew()) {} registry.getShipmentDestinyEntries().clear(); registry.setDateDeliveryReal(moDateDateDeliveryReal.getValue()); registry.setDelivery(true); return registry; } @Override public SGuiValidation validateForm() { SGuiValidation validation = moFields.validateFields(); if (validation.isValid()) { if (moDateDateDeliveryReal.getValue().before(moDateDateDelivery.getValue())) { validation.setMessage("El valor para el campo '" + SGuiUtils.getLabelName(jlDateDeliveryReal) + "' no puede se anterior al campo '" + SGuiUtils.getLabelName(jlDateDelivery) + "'."); validation.setComponent(moDateDateDeliveryReal); } } return validation; } }
mit
utluiz/java-playground
random-code/src/main/java/RedirectSystemOut.java
1023
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; public class RedirectSystemOut { public static void main(String[] args) { PrintStream original = System.out; StringBuilder sb = new StringBuilder(); System.setOut(new PrintStream(new OutputStream() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void write(int b) throws IOException { baos.write(b); } @Override public void flush() throws IOException { sb.append(baos.toString()); baos.reset(); } @Override public void close() throws IOException { sb.append(baos.toString()); baos.reset(); } }, true)); System.out.print("Capture "); System.out.println("Isto "); System.out.format("Para %s!", "Mim"); System.setOut(original); System.out.format("Resultado capturado:%n%s", sb); } }
mit
akkirilov/SoftUniProject
04_DB Frameworks_Hibernate+Spring Data/03_OOP Principles LAB/src/carShop/Seat.java
590
package carShop; public class Seat extends Sellable{ private String countryProduced; public Seat(String model, String color, Integer horsePower, Double price, String countryProduced) { super(model, color, horsePower, price); this.countryProduced = countryProduced; } @Override public String toString() { return String.format("FOR SELL:%n%s is %s color and have %s horse power%n" + "This is %s produced in %s and have %s tires%n" + "PRICE: %.2f BGN", getModel(), getColor(), getHorsePower(), getModel(), this.countryProduced, TYRES, getPrice()); } }
mit
jordantdavis/CourseIntroToComputerScience
Inheritance/Cheetah.java
330
/** * Write a description of class Cheetah here. * * @author (your name) * @version (a version number or a date) */ //"child class" //"subclass" //"derived class" public class Cheetah extends Animal { public void run() { System.out.println("This cheetah is currently running"); } }
mit
steffen-foerster/mgh
src/ch/giesserei/view/reservation/personwhg/FilterPersonAction.java
1122
package ch.giesserei.view.reservation.personwhg; import ch.giesserei.resource.AppRes; import ch.giesserei.view.AbstractClickListener; import ch.giesserei.view.AbstractViewController; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Notification; /** * Dieses Aktion informiert den Controller, dass nach einer Person gefiltert werden soll. * * @author Steffen Förster */ @SuppressWarnings("serial") public class FilterPersonAction extends AbstractClickListener { public FilterPersonAction(AbstractViewController viewController) { super(viewController); } @Override public void buttonClick(ClickEvent event) { if (getCtrl().getView().getPersonFilter().getValue() == null) { Notification.show(AppRes.getString("notification.caption.no.filter"), Notification.Type.WARNING_MESSAGE); } else { getCtrl().setCurrentFilter(PersonWhgViewController.CurrentFilter.PERSON); getCtrl().updateTableData(); } } private PersonWhgViewController getCtrl() { return (PersonWhgViewController) getViewController(); } }
mit
BenjaminBNielsen/ProjectXray
src/view/buttons/ShiftManualButton.java
930
/* * 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 view.buttons; import javafx.scene.control.Button; import view.popups.shift.ShiftManualPopup; /** * * @author Yousef */ public class ShiftManualButton extends Button{ public static final double PREFERRED_HEIGHT = 50; public static final double PREFERRED_WIDTH = 50; public ShiftManualButton(String text){ super(text); this.setPrefSize(PREFERRED_WIDTH,PREFERRED_HEIGHT); } public ShiftManualButton(){ super(); this.setPrefSize(PREFERRED_WIDTH,PREFERRED_HEIGHT); } public void setOnActionCode(){ ShiftManualPopup shiftManualPopup = new ShiftManualPopup(); shiftManualPopup.display("Opret manuel vagt"); } }
mit
ITSFactory/itsfactory.siri.bindings.v13
src/main/java/eu/datex2/schema/_1_0/_1_0/PrecipitationTypeEnum.java
2063
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.07.27 at 08:11:57 PM EEST // package eu.datex2.schema._1_0._1_0; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PrecipitationTypeEnum. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="PrecipitationTypeEnum"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="drizzle"/> * &lt;enumeration value="hail"/> * &lt;enumeration value="rain"/> * &lt;enumeration value="sleet"/> * &lt;enumeration value="snow"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "PrecipitationTypeEnum") @XmlEnum public enum PrecipitationTypeEnum { /** * Light, fine rain. * */ @XmlEnumValue("drizzle") DRIZZLE("drizzle"), /** * Small balls of ice and compacted snow. * */ @XmlEnumValue("hail") HAIL("hail"), /** * Rain. * */ @XmlEnumValue("rain") RAIN("rain"), /** * Wet snow mixed with rain. * */ @XmlEnumValue("sleet") SLEET("sleet"), /** * Snow. * */ @XmlEnumValue("snow") SNOW("snow"); private final String value; PrecipitationTypeEnum(String v) { value = v; } public String value() { return value; } public static PrecipitationTypeEnum fromValue(String v) { for (PrecipitationTypeEnum c: PrecipitationTypeEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
mit
bartoszgolek/whattodofordinner
app/src/main/java/biz/golek/whattodofordinner/view/messages/DinnerUpdatedMessage.java
409
package biz.golek.whattodofordinner.view.messages; /** * Created by Bartosz Gołek on 2016-02-10. */ public class DinnerUpdatedMessage { private Long id; private String name; public DinnerUpdatedMessage(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public String getName() { return name; } }
mit
yogoloth/jmxtrans
jmxtrans-output/jmxtrans-output-core/src/test/java/com/googlecode/jmxtrans/model/output/GraphiteWriterFactoryIT.java
4048
/** * The MIT License * Copyright (c) 2010 JmxTrans team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.googlecode.jmxtrans.model.output; import com.google.common.collect.ImmutableList; import com.google.common.io.Closer; import com.google.inject.Injector; import com.googlecode.jmxtrans.ConfigurationParser; import com.googlecode.jmxtrans.cli.JmxTransConfiguration; import com.googlecode.jmxtrans.exceptions.LifecycleException; import com.googlecode.jmxtrans.guice.JmxTransModule; import com.googlecode.jmxtrans.model.OutputWriter; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Server; import com.googlecode.jmxtrans.model.output.support.ResultTransformerOutputWriter; import com.googlecode.jmxtrans.test.IntegrationTest; import com.googlecode.jmxtrans.test.RequiresIO; import com.googlecode.jmxtrans.test.ResetableSystemProperty; import com.kaching.platform.testing.AllowDNSResolution; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import static org.assertj.core.api.Assertions.assertThat; @Category({IntegrationTest.class, RequiresIO.class}) @AllowDNSResolution public class GraphiteWriterFactoryIT { private ConfigurationParser configurationParser; private final Closer closer = Closer.create(); @Before public void createConfigurationParser() { JmxTransConfiguration configuration = new JmxTransConfiguration(); Injector injector = JmxTransModule.createInjector(configuration); configurationParser = injector.getInstance(ConfigurationParser.class); } @Before public void setupProperties() { closer.register(ResetableSystemProperty.setSystemProperty("server.port", "1099")); closer.register(ResetableSystemProperty.setSystemProperty("server.attribute", "HeapMemoryUsage")); closer.register(ResetableSystemProperty.setSystemProperty("server.thread", "2")); closer.register(ResetableSystemProperty.setSystemProperty("graphite.host", "example.net")); } @After public void resetProperties() throws IOException { closer.close(); } @Test public void canParseConfigurationFile() throws LifecycleException, URISyntaxException { ImmutableList<Server> servers = configurationParser.parseServers(ImmutableList.of(file("/graphite-writer-factory-example.json")), false); assertThat(servers).hasSize(1); Server server = servers.get(0); assertThat(server.getNumQueryThreads()).isEqualTo(2); assertThat(server.getQueries()).hasSize(1); Query query = server.getQueries().iterator().next(); assertThat(query.getOutputWriterInstances()).hasSize(1); OutputWriter outputWriter = query.getOutputWriterInstances().iterator().next(); assertThat(outputWriter).isInstanceOf(ResultTransformerOutputWriter.class); } private File file(String filename) throws URISyntaxException { return new File(GraphiteWriterFactoryIT.class.getResource(filename).toURI()); } }
mit