text
stringlengths
10
2.72M
package vlad.fp.services.synchronous.api; import vlad.fp.services.model.Account; import vlad.fp.services.model.AccountID; public interface AccountService { Account getAccount(AccountID id); }
package chapter04; import java.util.Scanner; public class Exercise04_23 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Employee’s name (e.g., Smith)"); String name = input.next(); System.out.println("Number of hours worked in a week (e.g., 10)"); int workHours = input.nextInt(); System.out.println("Hourly pay rate (e.g., 9.75)"); double payRate = input.nextDouble(); System.out.println("Federal tax withholding rate (e.g., 20%)"); double federalTaxRate = input.nextDouble(); System.out.println("State tax withholding rate (e.g., 9%)"); double stateTaxRate = input.nextDouble(); System.out.println("Employee Name: " + name); System.out.println("Hours worked: " + workHours); System.out.println("Pay Rate: $" + payRate); System.out.println("Gross Pay: $" + (workHours * payRate)); System.out.println("Deductions: "); System.out.println(" Federal Witholding (20.0%): $" + (federalTaxRate * workHours * payRate)); System.out.println(" State Withholding (9.0%): $" + (stateTaxRate * workHours * payRate)); System.out.println( " Total Deduction: $" + ((federalTaxRate * workHours * payRate) + (stateTaxRate * workHours * payRate))); System.out.println("Net Pay: $" + ((workHours * payRate) - ((federalTaxRate * workHours * payRate) + (stateTaxRate * workHours * payRate)))); } }
package com.tencent.mm.plugin.setting.ui.setting; import android.widget.Button; import android.widget.TextView; import com.tencent.mm.plugin.setting.ui.setting.SettingsSearchAuthUI.a; class SettingsSearchAuthUI$a$a { Button eOQ; TextView hJd; TextView mSB; TextView mSC; final /* synthetic */ a mTL; private SettingsSearchAuthUI$a$a(a aVar) { this.mTL = aVar; } }
/* * Copyright 2016 Andrei Zaiats. * * 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.github.azaiats.androidmvvm.navigation.delegates; import android.app.Activity; import android.databinding.ViewDataBinding; import android.support.annotation.NonNull; import io.github.azaiats.androidmvvm.core.common.BindingConfig; import io.github.azaiats.androidmvvm.core.delegates.ActivityDelegateCallback; /** * @author Andrei Zaiats */ public class TestNavigatingActivityDelegate extends NavigatingActivityDelegate { /** * Create delegate for activity. * * @param callback the ActivityDelegateCallback for this delegate * @param navigatingCallback the NavigatingDelegateCallback for this delegate * @param delegatedActivity the Activity for delegation */ public TestNavigatingActivityDelegate(@NonNull ActivityDelegateCallback callback, @NonNull NavigatingDelegateCallback navigatingCallback, @NonNull Activity delegatedActivity) { super(callback, navigatingCallback, delegatedActivity); } // DataBindingUtils can't be mocked @Override protected ViewDataBinding initBinding(BindingConfig bindingConfig) { return null; } }
package com.kimkha.readability; /** * */ public class PageReadException extends Exception { public PageReadException() { super(); } public PageReadException(String message) { super(message); } public PageReadException(String message, Throwable cause) { super(message, cause); } public PageReadException(Exception e) { super(e); } }
package pwr.chrzescijanek.filip.gifa.controller; import com.sun.javafx.UnmodifiableArrayList; import com.sun.javafx.charts.Legend; import com.sun.javafx.charts.Legend.LegendItem; import javafx.application.Platform; import javafx.beans.Observable; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.chart.XYChart.Series; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ColorPicker; import javafx.scene.control.ComboBox; import javafx.scene.control.DialogPane; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioButton; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.TitledPane; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.web.WebView; import javafx.stage.Stage; import javafx.util.Pair; import org.opencv.core.Core; import org.opencv.core.CvException; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint2f; import org.opencv.imgcodecs.Imgcodecs; import pwr.chrzescijanek.filip.gifa.core.generator.DataGenerator; import pwr.chrzescijanek.filip.gifa.core.generator.DataGeneratorFactory; import pwr.chrzescijanek.filip.gifa.core.util.ImageUtils; import pwr.chrzescijanek.filip.gifa.core.util.Result; import pwr.chrzescijanek.filip.gifa.model.image.ImageData; import pwr.chrzescijanek.filip.gifa.model.image.ImageDataFactory; import pwr.chrzescijanek.filip.gifa.model.image.ImageToAlignData; import pwr.chrzescijanek.filip.gifa.model.image.SamplesImageData; import pwr.chrzescijanek.filip.gifa.model.sample.BasicSample; import pwr.chrzescijanek.filip.gifa.model.sample.BasicSampleFactory; import pwr.chrzescijanek.filip.gifa.model.sample.Sample; import pwr.chrzescijanek.filip.gifa.model.sample.Vertex; import pwr.chrzescijanek.filip.gifa.util.SharedState; import pwr.chrzescijanek.filip.gifa.util.StageUtils; import javax.inject.Inject; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static javafx.collections.FXCollections.observableArrayList; import static org.opencv.imgproc.Imgproc.INTER_CUBIC; import static org.opencv.imgproc.Imgproc.INTER_LINEAR; import static org.opencv.imgproc.Imgproc.INTER_NEAREST; import static pwr.chrzescijanek.filip.gifa.core.util.ImageUtils.createImage; import static pwr.chrzescijanek.filip.gifa.core.util.ImageUtils.getImagesCopy; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.getCSVFile; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.getDirectory; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.getHBoxWithLabelAndProgressIndicator; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.getHelpView; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.getImageFiles; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.getWebColor; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.prepareImage; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.startTask; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.writeImage; /** * Application controller class. */ public class Controller extends BaseController implements Initializable { private static final Logger LOGGER = Logger.getLogger(Controller.class.getName()); private static final String CHART_DEFAULT_STYLE = "-fx-border-color: null;"; private static final String CHART_SELECTED_STYLE = "-fx-border-color: yellow; -fx-border-width: 3px;"; /** * Data generators factory. */ protected final DataGeneratorFactory dataGeneratorFactory; /** * Samples factory. */ protected final BasicSampleFactory basicSampleFactory; /** * Image data factory. */ protected final ImageDataFactory imageDataFactory; private final ObjectProperty<List<Result>> results = new SimpleObjectProperty<>(null); private final List<List<XYChart.Series<String, Number>>> series = new ArrayList<>(); private final List<List<BarChart<String, Number>>> charts = new ArrayList<>(); private final List<LineChart<String, Number>> summaryCharts = new ArrayList<>(); private final List<Map<String, Color>> seriesColors = new ArrayList<>(); private final Map<String, Color> summarySeriesColors = new HashMap<>(); private final List<List<Pair<String, ImageView>>> samples = new ArrayList<>(); private final Map<Object, String> columns = new HashMap<>(); @FXML private AnchorPane samplesImageViewAnchor; @FXML private AnchorPane alignImageViewAnchor; @FXML private BorderPane chartsMainPane; @FXML private BorderPane featuresBorderPane; @FXML private BorderPane samplesBorderPane; @FXML private BorderPane alignBorderPane; @FXML private Button chartsRemoveButton; @FXML private Button chartsMergeButton; @FXML private Button chartsRefreshButton; @FXML private Button chartsExtractButton; @FXML private Button clearImagesButton; @FXML private Button clearSamplesButton; @FXML private Button removeImageButton; @FXML private Button removeSampleButton; @FXML private Button deselectAllButton; @FXML private Button horizontalFlipButton; @FXML private Button loadImagesButton; @FXML private Button calculateResultsButton; @FXML private Button rotateLeftButton; @FXML private Button rotateRightButton; @FXML private Button selectAllButton; @FXML private Button alignButton; @FXML private Button verticalFlipButton; @FXML private ColorPicker sampleBorderColor; @FXML private ColorPicker sampleFillColor; @FXML private ColorPicker sampleStrokeColor; @FXML private ColorPicker triangleFillColor; @FXML private ColorPicker triangleStrokeColor; @FXML private ColorPicker vertexBorderColor; @FXML private ColorPicker vertexFillColor; @FXML private ColorPicker vertexStrokeColor; @FXML private ComboBox<Integer> chartsSampleComboBox; @FXML private ComboBox<String> samplesScaleCombo; @FXML private ComboBox<String> alignScaleCombo; @FXML private GridPane allChartsGrid; @FXML private GridPane chartsBySampleGrid; @FXML private GridPane chartsControls; @FXML private GridPane imagesBySampleGrid; @FXML private GridPane root; @FXML private GridPane sampleColorControls; @FXML private GridPane samplesBottomGrid; @FXML private GridPane samplesImageListGrid; @FXML private GridPane samplesMainPane; @FXML private GridPane samplesToolsGridPane; @FXML private GridPane alignBottomGrid; @FXML private GridPane alignColorControls; @FXML private GridPane alignImageListGrid; @FXML private GridPane alignMainPane; @FXML private GridPane alignToolsGridPane; @FXML private GridPane vertexColorControls; @FXML private Group samplesImageViewGroup; @FXML private Group alignImageViewGroup; @FXML private HBox chartsGraphsHBox; @FXML private HBox chartsGraphsToolbar; @FXML private HBox samplesTopHBox; @FXML private HBox selectionButtonsHBox; @FXML private HBox alignImageListToolbar; @FXML private HBox alignTopHBox; @FXML private ImageView samplesImageView; @FXML private ImageView alignImageView; @FXML private Label chartsColumnsLabel; @FXML private Label chartsGraphsInfo; @FXML private Label chartsSampleLabel; @FXML private Label sampleBorderLabel; @FXML private Label sampleFillLabel; @FXML private Label sampleStrokeLabel; @FXML private Label samplesImageSizeLabel; @FXML private Label samplesInfo; @FXML private Label samplesMousePositionLabel; @FXML private Label alignImageListInfo; @FXML private Label alignImageSizeLabel; @FXML private Label alignInfo; @FXML private Label alignMousePositionLabel; @FXML private Label triangleFillLabel; @FXML private Label triangleStrokeLabel; @FXML private Label vertexBorderLabel; @FXML private Label vertexFillLabel; @FXML private Label vertexStrokeLabel; @FXML private ListView<String> samplesImageList; @FXML private ListView<String> alignImageList; @FXML private Menu chartsMenu; @FXML private Menu editMenu; @FXML private Menu fileMenu; @FXML private Menu helpMenu; @FXML private Menu navMenu; @FXML private Menu optionsMenu; @FXML private Menu optionsMenuTheme; @FXML private Menu runMenu; @FXML private Menu samplesMenu; @FXML private Menu alignMenu; @FXML private MenuBar menuBar; @FXML private MenuItem chartsMenuExtractChart; @FXML private MenuItem chartsMenuMergeCharts; @FXML private MenuItem chartsMenuRemoveCharts; @FXML private MenuItem chartsMenuRestoreCharts; @FXML private MenuItem editMenuZoomIn; @FXML private MenuItem editMenuZoomOut; @FXML private MenuItem fileMenuExit; @FXML private MenuItem fileMenuExportToCsv; @FXML private MenuItem fileMenuExportToPng; @FXML private MenuItem helpMenuAbout; @FXML private MenuItem helpMenuHelp; @FXML private MenuItem navMenuAllCharts; @FXML private MenuItem navMenuCharts; @FXML private MenuItem navMenuChartsBySample; @FXML private MenuItem navMenuImagesBySample; @FXML private MenuItem navMenuSamples; @FXML private MenuItem navMenuAlign; @FXML private MenuItem runMenuCalculateResults; @FXML private MenuItem runMenuAlign; @FXML private MenuItem samplesMenuClearSamples; @FXML private MenuItem samplesMenuCreateMode; @FXML private MenuItem samplesMenuRemoveSample; @FXML private MenuItem samplesMenuDeselectAllFeatures; @FXML private MenuItem samplesMenuRotateMode; @FXML private MenuItem samplesMenuSelectAllFeatures; @FXML private MenuItem samplesMenuSelectMode; @FXML private MenuItem alignMenuClearImages; @FXML private MenuItem alignMenuRemoveImage; @FXML private MenuItem alignMenuHorizontalFlip; @FXML private MenuItem alignMenuLoadImages; @FXML private MenuItem alignMenuMenuRotateLeft; @FXML private MenuItem alignMenuMenuRotateRight; @FXML private MenuItem alignMenuVerticalFlip; @FXML private RadioButton chartsBySampleRadioButton; @FXML private RadioButton createRadioButton; @FXML private RadioButton cubicRadioButton; @FXML private RadioButton imagesBySampleRadioButton; @FXML private RadioButton linearRadioButton; @FXML private RadioButton nearestRadioButton; @FXML private RadioButton rotateRadioButton; @FXML private RadioButton selectRadioButton; @FXML private RadioMenuItem optionsMenuThemeDark; @FXML private RadioMenuItem optionsMenuThemeLight; @FXML private ResourceBundle resources; @FXML private ScrollPane allChartsGridScrollPane; @FXML private ScrollPane chartsBySampleGridScrollPane; @FXML private ScrollPane featuresScrollPane; @FXML private ScrollPane imagesBySampleGridScrollPane; @FXML private ScrollPane samplesScrollPane; @FXML private ScrollPane alignScrollPane; @FXML private Tab allChartsTab; @FXML private Tab bySampleTab; @FXML private Tab chartsTab; @FXML private Tab featuresTab; @FXML private Tab samplesTab; @FXML private Tab imageListTab; @FXML private Tab alignTab; @FXML private TabPane chartsTabPane; @FXML private TabPane mainTabPane; @FXML private TabPane rightVBoxTabPane; @FXML private TextField chartsColumnsTextField; @FXML private TitledPane interpolationTitledPane; @FXML private TitledPane sampleTitledPane; @FXML private TitledPane samplesModeTitledPane; @FXML private TitledPane samplesToolsTitledPane; @FXML private TitledPane toolsTitledPane; @FXML private TitledPane triangleTitledPane; @FXML private TitledPane vertexTitledPane; @FXML private ToggleGroup drawMethod; @FXML private ToggleGroup interpolation; @FXML private ToggleGroup bySampleToggle; @FXML private ToggleGroup themeToggleGroup; @FXML private URL location; @FXML private VBox featuresVBox; @FXML private VBox interpolationVBox; @FXML private VBox rightVBox; @FXML private VBox samplesLeftVBox; @FXML private VBox samplesModeVBox; @FXML private VBox alignLeftVBox; /** * Constructs new Controller with given shared state, data generators factory, samples factory * and image data factory. * * @param state shared state * @param dataGeneratorFactory data generators factory * @param basicSampleFactory samples factory * @param imageDataFactory image data factory */ @Inject public Controller(final SharedState state, final DataGeneratorFactory dataGeneratorFactory, final BasicSampleFactory basicSampleFactory, final ImageDataFactory imageDataFactory) { super(state); this.dataGeneratorFactory = dataGeneratorFactory; this.basicSampleFactory = basicSampleFactory; this.imageDataFactory = imageDataFactory; } /** * @return samples view image view anchor */ public AnchorPane getSamplesImageViewAnchor() { return samplesImageViewAnchor; } /** * @return align view image view anchor */ public AnchorPane getAlignImageViewAnchor() { return alignImageViewAnchor; } /** * @return charts view border pane */ public BorderPane getChartsMainPane() { return chartsMainPane; } /** * @return features tab border pane */ public BorderPane getFeaturesBorderPane() { return featuresBorderPane; } /** * @return samples view border pane */ public BorderPane getSamplesBorderPane() { return samplesBorderPane; } /** * @return align view border pane */ public BorderPane getAlignBorderPane() { return alignBorderPane; } /** * @return remove charts button */ public Button getChartsRemoveButton() { return chartsRemoveButton; } /** * @return merge charts button */ public Button getChartsMergeButton() { return chartsMergeButton; } /** * @return refresh charts button */ public Button getChartsRefreshButton() { return chartsRefreshButton; } /** * @return charts extract button */ public Button getChartsExtractButton() { return chartsExtractButton; } /** * @return clear images button */ public Button getClearImagesButton() { return clearImagesButton; } /** * @return clear samples button */ public Button getClearSamplesButton() { return clearSamplesButton; } /** * @return remove image button */ public Button getRemoveImageButton() { return removeImageButton; } /** * @return remove sample button */ public Button getRemoveSampleButton() { return removeSampleButton; } /** * @return deselect all button */ public Button getDeselectAllButton() { return deselectAllButton; } /** * @return horizontal flip button */ public Button getHorizontalFlipButton() { return horizontalFlipButton; } /** * @return load images button */ public Button getLoadImagesButton() { return loadImagesButton; } /** * @return calculate results button */ public Button getCalculateResultsButton() { return calculateResultsButton; } /** * @return rotate left button */ public Button getRotateLeftButton() { return rotateLeftButton; } /** * @return rotate right button */ public Button getRotateRightButton() { return rotateRightButton; } /** * @return select all button */ public Button getSelectAllButton() { return selectAllButton; } /** * @return align button */ public Button getAlignButton() { return alignButton; } /** * @return vertical flip button */ public Button getVerticalFlipButton() { return verticalFlipButton; } /** * @return sample border color picker */ public ColorPicker getSampleBorderColor() { return sampleBorderColor; } /** * @return sample fill color picker */ public ColorPicker getSampleFillColor() { return sampleFillColor; } /** * @return sample stroke color picker */ public ColorPicker getSampleStrokeColor() { return sampleStrokeColor; } /** * @return triangle fill color picker */ public ColorPicker getTriangleFillColor() { return triangleFillColor; } /** * @return triangle stroke color picker */ public ColorPicker getTriangleStrokeColor() { return triangleStrokeColor; } /** * @return vertex border color picker */ public ColorPicker getVertexBorderColor() { return vertexBorderColor; } /** * @return vertex fill color picker */ public ColorPicker getVertexFillColor() { return vertexFillColor; } /** * @return vertex stroke color picker */ public ColorPicker getVertexStrokeColor() { return vertexStrokeColor; } /** * @return charts view sample combo box */ public ComboBox<Integer> getChartsSampleComboBox() { return chartsSampleComboBox; } /** * @return samples view scale combo box */ public ComboBox<String> getSamplesScaleCombo() { return samplesScaleCombo; } /** * @return align view scale combo box */ public ComboBox<String> getAlignScaleCombo() { return alignScaleCombo; } /** * @return all charts view grid pane */ public GridPane getAllChartsGrid() { return allChartsGrid; } /** * @return charts by sample view grid pane */ public GridPane getChartsBySampleGrid() { return chartsBySampleGrid; } /** * @return charts view controls grid pane */ public GridPane getChartsControls() { return chartsControls; } /** * @return images by sample view grid pane */ public GridPane getImagesBySampleGrid() { return imagesBySampleGrid; } /** * @return root grid pane */ public GridPane getRoot() { return root; } /** * @return samples view color controls grid pane */ public GridPane getSampleColorControls() { return sampleColorControls; } /** * @return samples view bottom grid pane */ public GridPane getSamplesBottomGrid() { return samplesBottomGrid; } /** * @return samples view image list grid pane */ public GridPane getSamplesImageListGrid() { return samplesImageListGrid; } /** * @return samples view grid pane */ public GridPane getSamplesMainPane() { return samplesMainPane; } /** * @return samples view tools grid pane */ public GridPane getSamplesToolsGridPane() { return samplesToolsGridPane; } /** * @return align view bottom grid pane */ public GridPane getAlignBottomGrid() { return alignBottomGrid; } /** * @return align view color controls grid pane */ public GridPane getAlignColorControls() { return alignColorControls; } /** * @return align view image list grid pane */ public GridPane getAlignImageListGrid() { return alignImageListGrid; } /** * @return align view grid pane */ public GridPane getAlignMainPane() { return alignMainPane; } /** * @return align view tools grid pane */ public GridPane getAlignToolsGridPane() { return alignToolsGridPane; } /** * @return align view vertex color controls grid pane */ public GridPane getVertexColorControls() { return vertexColorControls; } /** * @return samples view image view group */ public Group getSamplesImageViewGroup() { return samplesImageViewGroup; } /** * @return align view image view group */ public Group getAlignImageViewGroup() { return alignImageViewGroup; } /** * @return charts view graphs horizontal box */ public HBox getChartsGraphsHBox() { return chartsGraphsHBox; } /** * @return charts view graphs toolbar horizontal box */ public HBox getChartsGraphsToolbar() { return chartsGraphsToolbar; } /** * @return samples view top horizontal box */ public HBox getSamplesTopHBox() { return samplesTopHBox; } /** * @return selection buttons horizontal box */ public HBox getSelectionButtonsHBox() { return selectionButtonsHBox; } /** * @return align view image list toolbar horizontal box */ public HBox getAlignImageListToolbar() { return alignImageListToolbar; } /** * @return align view top horizontal box */ public HBox getAlignTopHBox() { return alignTopHBox; } /** * @return samples view image view */ public ImageView getSamplesImageView() { return samplesImageView; } /** * @return align view image view */ public ImageView getAlignImageView() { return alignImageView; } /** * @return charts view max. column label */ public Label getChartsColumnsLabel() { return chartsColumnsLabel; } /** * @return charts view graphs info label */ public Label getChartsGraphsInfo() { return chartsGraphsInfo; } /** * @return charts view sample label */ public Label getChartsSampleLabel() { return chartsSampleLabel; } /** * @return sample border color label */ public Label getSampleBorderLabel() { return sampleBorderLabel; } /** * @return sample fill color label */ public Label getSampleFillLabel() { return sampleFillLabel; } /** * @return sample stroke color label */ public Label getSampleStrokeLabel() { return sampleStrokeLabel; } /** * @return samples view image size label */ public Label getSamplesImageSizeLabel() { return samplesImageSizeLabel; } /** * @return samples view info label */ public Label getSamplesInfo() { return samplesInfo; } /** * @return samples view mouse position label */ public Label getSamplesMousePositionLabel() { return samplesMousePositionLabel; } /** * @return align view image list info label */ public Label getAlignImageListInfo() { return alignImageListInfo; } /** * @return align view image size label */ public Label getAlignImageSizeLabel() { return alignImageSizeLabel; } /** * @return align view info label */ public Label getAlignInfo() { return alignInfo; } /** * @return align view mouse position label */ public Label getAlignMousePositionLabel() { return alignMousePositionLabel; } /** * @return triangle fill label */ public Label getTriangleFillLabel() { return triangleFillLabel; } /** * @return triangle stroke label */ public Label getTriangleStrokeLabel() { return triangleStrokeLabel; } /** * @return vertex border label */ public Label getVertexBorderLabel() { return vertexBorderLabel; } /** * @return vertex fill label */ public Label getVertexFillLabel() { return vertexFillLabel; } /** * @return vertex stroke label */ public Label getVertexStrokeLabel() { return vertexStrokeLabel; } /** * @return samples view image list */ public ListView<String> getSamplesImageList() { return samplesImageList; } /** * @return align view image list */ public ListView<String> getAlignImageList() { return alignImageList; } /** * @return charts menu */ public Menu getChartsMenu() { return chartsMenu; } /** * @return edit menu */ public Menu getEditMenu() { return editMenu; } /** * @return file menu */ public Menu getFileMenu() { return fileMenu; } /** * @return help menu */ public Menu getHelpMenu() { return helpMenu; } /** * @return navigation menu */ public Menu getNavMenu() { return navMenu; } /** * @return options menu */ public Menu getOptionsMenu() { return optionsMenu; } /** * @return options theme menu */ public Menu getOptionsMenuTheme() { return optionsMenuTheme; } /** * @return run menu */ public Menu getRunMenu() { return runMenu; } /** * @return samples menu */ public Menu getSamplesMenu() { return samplesMenu; } /** * @return align menu */ public Menu getAlignMenu() { return alignMenu; } /** * @return menu bar */ public MenuBar getMenuBar() { return menuBar; } /** * @return charts menu extract chart menu item */ public MenuItem getChartsMenuExtractChart() { return chartsMenuExtractChart; } /** * @return charts menu merge charts menu item */ public MenuItem getChartsMenuMergeCharts() { return chartsMenuMergeCharts; } /** * @return charts menu remove charts menu item */ public MenuItem getChartsMenuRemoveCharts() { return chartsMenuRemoveCharts; } /** * @return charts menu restore charts menu item */ public MenuItem getChartsMenuRestoreCharts() { return chartsMenuRestoreCharts; } /** * @return edit menu zoom in menu item */ public MenuItem getEditMenuZoomIn() { return editMenuZoomIn; } /** * @return edit menu zoom out menu item */ public MenuItem getEditMenuZoomOut() { return editMenuZoomOut; } /** * @return file menu exit menu item */ public MenuItem getFileMenuExit() { return fileMenuExit; } /** * @return file menu export to CSV menu item */ public MenuItem getFileMenuExportToCsv() { return fileMenuExportToCsv; } /** * @return file menu export to PNG menu item */ public MenuItem getFileMenuExportToPng() { return fileMenuExportToPng; } /** * @return help menu about menu item */ public MenuItem getHelpMenuAbout() { return helpMenuAbout; } /** * @return help menu help menu item */ public MenuItem getHelpMenuHelp() { return helpMenuHelp; } /** * @return navigation menu all charts menu item */ public MenuItem getNavMenuAllCharts() { return navMenuAllCharts; } /** * @return navigation menu charts menu item */ public MenuItem getNavMenuCharts() { return navMenuCharts; } /** * @return navigation menu charts by sample menu item */ public MenuItem getNavMenuChartsBySample() { return navMenuChartsBySample; } /** * @return navigation menu images by sample menu item */ public MenuItem getNavMenuImagesBySample() { return navMenuImagesBySample; } /** * @return navigation menu samples menu item */ public MenuItem getNavMenuSamples() { return navMenuSamples; } /** * @return navigation menu align menu item */ public MenuItem getNavMenuAlign() { return navMenuAlign; } /** * @return run menu calculate results menu item */ public MenuItem getRunMenuCalculateResults() { return runMenuCalculateResults; } /** * @return run menu align menu item */ public MenuItem getRunMenuAlign() { return runMenuAlign; } /** * @return samples menu clear samples menu item */ public MenuItem getSamplesMenuClearSamples() { return samplesMenuClearSamples; } /** * @return samples menu create mode menu item */ public MenuItem getSamplesMenuCreateMode() { return samplesMenuCreateMode; } /** * @return samples menu remove sample menu item */ public MenuItem getSamplesMenuRemoveSample() { return samplesMenuRemoveSample; } /** * @return samples menu deselect all features menu item */ public MenuItem getSamplesMenuDeselectAllFeatures() { return samplesMenuDeselectAllFeatures; } /** * @return samples menu rotate mode menu item */ public MenuItem getSamplesMenuRotateMode() { return samplesMenuRotateMode; } /** * @return samples menu select all features menu item */ public MenuItem getSamplesMenuSelectAllFeatures() { return samplesMenuSelectAllFeatures; } /** * @return samples menu select mode menu item */ public MenuItem getSamplesMenuSelectMode() { return samplesMenuSelectMode; } /** * @return align menu clear images menu item */ public MenuItem getAlignMenuClearImages() { return alignMenuClearImages; } /** * @return align menu remove image menu item */ public MenuItem getAlignMenuRemoveImage() { return alignMenuRemoveImage; } /** * @return align menu horizontal flip menu item */ public MenuItem getAlignMenuHorizontalFlip() { return alignMenuHorizontalFlip; } /** * @return align menu load images menu item */ public MenuItem getAlignMenuLoadImages() { return alignMenuLoadImages; } /** * @return align menu rotate left menu item */ public MenuItem getAlignMenuMenuRotateLeft() { return alignMenuMenuRotateLeft; } /** * @return align menu rotate right menu item */ public MenuItem getAlignMenuMenuRotateRight() { return alignMenuMenuRotateRight; } /** * @return align menu vertical flip menu item */ public MenuItem getAlignMenuVerticalFlip() { return alignMenuVerticalFlip; } /** * @return charts by sample radio button */ public RadioButton getChartsBySampleRadioButton() { return chartsBySampleRadioButton; } /** * @return create radio button */ public RadioButton getCreateRadioButton() { return createRadioButton; } /** * @return cubic interpolation radio button */ public RadioButton getCubicRadioButton() { return cubicRadioButton; } /** * @return images by sample radio button */ public RadioButton getImagesBySampleRadioButton() { return imagesBySampleRadioButton; } /** * @return linear interpolation radio button */ public RadioButton getLinearRadioButton() { return linearRadioButton; } /** * @return nearest neighbour interpolation radio button */ public RadioButton getNearestRadioButton() { return nearestRadioButton; } /** * @return rotate radio button */ public RadioButton getRotateRadioButton() { return rotateRadioButton; } /** * @return select radio button */ public RadioButton getSelectRadioButton() { return selectRadioButton; } /** * @return options menu dark theme radio menu item */ public RadioMenuItem getOptionsMenuThemeDark() { return optionsMenuThemeDark; } /** * @return options menu light theme radio menu item */ public RadioMenuItem getOptionsMenuThemeLight() { return optionsMenuThemeLight; } /** * @return resources */ public ResourceBundle getResources() { return resources; } /** * @return all charts view's scroll pane containing grid pane */ public ScrollPane getAllChartsGridScrollPane() { return allChartsGridScrollPane; } /** * @return charts by sample view's scroll pane containing grid pane */ public ScrollPane getChartsBySampleGridScrollPane() { return chartsBySampleGridScrollPane; } /** * @return features scroll pane */ public ScrollPane getFeaturesScrollPane() { return featuresScrollPane; } /** * @return images by sample view's scroll pane containing grid pane */ public ScrollPane getImagesBySampleGridScrollPane() { return imagesBySampleGridScrollPane; } /** * @return samples view scroll pane */ public ScrollPane getSamplesScrollPane() { return samplesScrollPane; } /** * @return align view scroll pane */ public ScrollPane getAlignScrollPane() { return alignScrollPane; } /** * @return all charts tab */ public Tab getAllChartsTab() { return allChartsTab; } /** * @return by sample tab */ public Tab getBySampleTab() { return bySampleTab; } /** * @return charts tab */ public Tab getChartsTab() { return chartsTab; } /** * @return features tab */ public Tab getFeaturesTab() { return featuresTab; } /** * @return samples tab */ public Tab getSamplesTab() { return samplesTab; } /** * @return image list tab */ public Tab getImageListTab() { return imageListTab; } /** * @return align tab */ public Tab getAlignTab() { return alignTab; } /** * @return charts tab pane */ public TabPane getChartsTabPane() { return chartsTabPane; } /** * @return main tab pane */ public TabPane getMainTabPane() { return mainTabPane; } /** * @return samples view right tab pane */ public TabPane getRightVBoxTabPane() { return rightVBoxTabPane; } /** * @return max. columns text field */ public TextField getChartsColumnsTextField() { return chartsColumnsTextField; } /** * @return interpolation group titled pane */ public TitledPane getInterpolationTitledPane() { return interpolationTitledPane; } /** * @return sample group titled pane */ public TitledPane getSampleTitledPane() { return sampleTitledPane; } /** * @return samples view mode group titled pane */ public TitledPane getSamplesModeTitledPane() { return samplesModeTitledPane; } /** * @return samples view tools group titled pane */ public TitledPane getSamplesToolsTitledPane() { return samplesToolsTitledPane; } /** * @return align view tools group titled pane */ public TitledPane getToolsTitledPane() { return toolsTitledPane; } /** * @return triangle group titled pane */ public TitledPane getTriangleTitledPane() { return triangleTitledPane; } /** * @return vertex group titled pane */ public TitledPane getVertexTitledPane() { return vertexTitledPane; } /** * @return draw method toggle group */ public ToggleGroup getDrawMethod() { return drawMethod; } /** * @return interpolation toggle group */ public ToggleGroup getInterpolation() { return interpolation; } /** * @return by sample toggle group */ public ToggleGroup getBySampleToggle() { return bySampleToggle; } /** * @return theme toggle group */ public ToggleGroup getThemeToggleGroup() { return themeToggleGroup; } /** * @return location */ public URL getLocation() { return location; } /** * @return features vertical box */ public VBox getFeaturesVBox() { return featuresVBox; } /** * @return interpolation vertical box */ public VBox getInterpolationVBox() { return interpolationVBox; } /** * @return samples view right vertical box */ public VBox getRightVBox() { return rightVBox; } /** * @return samples view left vertical box */ public VBox getSamplesLeftVBox() { return samplesLeftVBox; } /** * @return samples view mode vertical box */ public VBox getSamplesModeVBox() { return samplesModeVBox; } /** * @return align view left vertical box */ public VBox getAlignLeftVBox() { return alignLeftVBox; } @FXML void about() { final Alert alert = StageUtils.getAboutDialog(); final DialogPane dialogPane = alert.getDialogPane(); injectStylesheets(dialogPane); alert.show(); } @FXML void applyDarkTheme() { setDarkTheme(); } @FXML void applyLightTheme() { setLightTheme(); } @FXML void refresh() { final Integer index = chartsSampleComboBox.getValue() - 1; createCharts(index); placeCharts(); validateChartsControlsDisableProperties(); } private void createCharts(final int index) { final List<Series<String, Number>> series = this.series.get(index); final List<BarChart<String, Number>> charts = this.charts.get(index); if (charts != null) charts.clear(); for (final Series s : series) { final BarChart<String, Number> chart = new BarChart<>(new CategoryAxis(), createValueAxis()); chart.getData().addAll(s); registerOnChartClicked(chart); charts.add(chart); } } private NumberAxis createValueAxis() { final NumberAxis yAxis = new NumberAxis(); yAxis.setLabel("Value"); return yAxis; } private void registerOnChartClicked(final BarChart<String, Number> chart) { chart.setOnMouseClicked(event -> { if (chart.getStyle().equals(CHART_SELECTED_STYLE)) chart.setStyle(CHART_DEFAULT_STYLE); else chart.setStyle(CHART_SELECTED_STYLE); validateChartsControlsDisableProperties(); }); } @FXML void deselectAllFunctions() { if (!featuresTab.isSelected()) rightVBoxTabPane.getSelectionModel().select(featuresTab); for (final Node chb : featuresVBox.getChildren()) { ((CheckBox) chb).setSelected(false); } dataGeneratorFactory.clearChosenFunctions(); } @FXML void exit() { root.getScene().getWindow().hide(); } @FXML void exportToCsv() { final File csvFile = getCSVFile(root.getScene().getWindow()); if (csvFile != null) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(csvFile))) { bw.write(createCsvContents()); } catch (final IOException e) { handleException(e, "Save failed! Check your write permissions."); } } } private String createCsvContents() { final Set<String> names = results.get().stream() .flatMap(r -> r.getScores().keySet().stream()).collect(toSet()); final TreeSet<String> functions = new TreeSet<>(names); String csvContents = createHeader(functions); csvContents += appendSampleScores(functions, results.get()); return csvContents; } private void handleException(final Exception e, final String alert) { LOGGER.log(Level.SEVERE, e.toString(), e); Platform.runLater(() -> showAlert(alert)); } private String createHeader(final TreeSet<String> functions) { String csvContents = "Sample,Image"; for (final String s : functions) csvContents += ",\"" + s + "\""; return csvContents; } private String appendSampleScores(final TreeSet<String> functions, final List<Result> results) { String csvContents = ""; for (int i = 0; i < results.size(); i++) csvContents += appendSampleScores(functions, results.get(i), i + 1); return csvContents; } private void showAlert(final String content) { final Alert alert = StageUtils.getErrorAlert(content); final DialogPane dialogPane = alert.getDialogPane(); injectStylesheets(dialogPane); alert.showAndWait(); } private String appendSampleScores(final TreeSet<String> functions, final Result result, final int sample) { final List<List<String>> imageNames = result.getImageNames().stream().distinct().collect(toList()); String csvContents = ""; for (final List<String> names : imageNames) { for (int i = 0; i < names.size(); i++) { csvContents += "\r\n" + sample + ",\"" + names.get(i) + "\""; int index = 0; for (final String s : functions) { if (!result.getImageNames().get(index).contains(names.get(i))) csvContents += ","; else { final double[] doubles = result.getScores().get(s).stream().mapToDouble(Double::doubleValue) .toArray(); csvContents += ",\"" + doubles[i] + "\""; } index++; } } } return csvContents; } @FXML void flipHorizontal() { final String imageName = alignImageList.getSelectionModel().getSelectedItem(); final ImageToAlignData img = state.imagesToAlign.get(imageName); Core.flip(img.imageData, img.imageData, 1); final Mat imageCopy = ImageUtils.getImageCopy(img.imageData); final Image fxImage = createImage(imageCopy); refreshImage(img, fxImage); } private void refreshImage(final ImageToAlignData img, final Image fxImage) { img.image.set(fxImage); img.writableImage.set(new WritableImage(fxImage.getPixelReader(), (int) fxImage.getWidth(), (int) fxImage .getHeight())); alignImageView.setImage(fxImage); img.recalculateVertices(); setImageViewTranslates(alignImageView); alignImageSizeLabel.setText((int) fxImage.getWidth() + "x" + (int) fxImage.getHeight() + " px"); } private void setImageViewTranslates(final ImageView view) { view.setTranslateX(view.getImage().getWidth() * 0.5 * (view.getScaleX() - 1.0)); view.setTranslateY(view.getImage().getHeight() * 0.5 * (view.getScaleY() - 1.0)); } @FXML void flipVertical() { final String imageName = alignImageList.getSelectionModel().getSelectedItem(); final ImageToAlignData img = state.imagesToAlign.get(imageName); Core.flip(img.imageData, img.imageData, 0); final Mat imageCopy = ImageUtils.getImageCopy(img.imageData); final Image fxImage = createImage(imageCopy); refreshImage(img, fxImage); } @FXML void rotateLeft() { final String imageName = alignImageList.getSelectionModel().getSelectedItem(); final ImageToAlignData img = state.imagesToAlign.get(imageName); Core.transpose(img.imageData, img.imageData); Core.flip(img.imageData, img.imageData, 0); final Mat imageCopy = ImageUtils.getImageCopy(img.imageData); final Image fxImage = createImage(imageCopy); refreshImage(img, fxImage); } @FXML void rotateRight() { final String imageName = alignImageList.getSelectionModel().getSelectedItem(); final ImageToAlignData img = state.imagesToAlign.get(imageName); Core.transpose(img.imageData, img.imageData); Core.flip(img.imageData, img.imageData, 1); final Mat imageCopy = ImageUtils.getImageCopy(img.imageData); final Image fxImage = createImage(imageCopy); refreshImage(img, fxImage); } private void createSummaryCharts() { final List<LineChart<String, Number>> charts = populateCharts(); bindColors(charts); saveCharts(charts); placeSummaryCharts(); } private List<LineChart<String, Number>> populateCharts() { final List<LineChart<String, Number>> charts = new ArrayList<>(); final List<Result> summary = results.get(); final Set<String> collectedNames = summary.stream().flatMap(r -> r.getScores().keySet().stream()) .collect(toSet()); final Set<String> functions = new TreeSet<>(collectedNames); for (final String function : functions) populateCharts(charts, summary, function); return charts; } private void populateCharts(final List<LineChart<String, Number>> charts, final List<Result> summary, final String function) { final LineChart<String, Number> chart = new LineChart<>(createCategoryAxis(), createValueAxis()); chart.setTitle(function); final List<Series<String, Number>> series = createSeries(charts.size(), summary, function); series.forEach(chart.getData()::add); charts.add(chart); } private CategoryAxis createCategoryAxis() { final CategoryAxis xAxis = new CategoryAxis(); xAxis.setLabel("Sample"); return xAxis; } private List<Series<String, Number>> createSeries(final int chartIndex, final List<Result> summary, final String function) { final List<Double[]> results = summary.stream() .map(r -> r.getScores().get(function) .toArray(new Double[0])) .collect(toList()); final List<Series<String, Number>> series = populateSeries(chartIndex, summary, results); return series; } private List<Series<String, Number>> populateSeries(final int chartIndex, final List<Result> summary, final List<Double[]> results) { final List<Series<String, Number>> series = new ArrayList<>(); for (int i = 0; i < results.size(); i++) { final double[] scores = stream(results.get(i)).mapToDouble(Double::doubleValue).toArray(); final List<List<String>> names = summary.get(i).getImageNames(); populateSeries(chartIndex, series, scores, names, i); } return series; } private void populateSeries(final int chartIndex, final List<Series<String, Number>> series, final double[] scores, final List<List<String>> names, final int index) { for (int i = 0; i < scores.length; i++) { if (series.size() == i) { final Series<String, Number> s = new Series<>(); s.setName(Optional.ofNullable(names.get(chartIndex).get(i)).orElse("Series " + (i + 1))); series.add(s); } final Series<String, Number> current = series.get(i); current.getData().add(new XYChart.Data<>("" + (index + 1), scores[i])); } } private void bindColors(final List<LineChart<String, Number>> charts) { final List<Color> defaultColors = asList( Color.web("#f3622d"), Color.web("#fba71b"), Color.web("#57b757"), Color.web("#41a9c9"), Color.web("#4258c9"), Color.web("#9a42c8"), Color.web("#c84164"), Color.web("#888888")); for (final LineChart<String, Number> chart : charts) { for (int i = 0; i < chart.getData().size(); i++) { final Series<String, Number> series = chart.getData().get(i); final LegendItem item = getLegendItem(chart, series); if (item != null) item.setSymbol(initializeColorPicker(defaultColors, chart, series, i)); } } } private LegendItem getLegendItem(final LineChart<? extends String, ? extends Number> chart, final Series<? extends String, ? extends Number> series) { return chart.getChildrenUnmodifiable().stream() .filter(x -> x instanceof Legend).findAny() .map(l -> ((Legend) l).getItems()) .map(it -> it.stream() .filter(r -> r.getText().equals(series.getName())).findAny().orElse(null)) .orElse(null); } private ColorPicker initializeColorPicker(final List<Color> defaultColors, final LineChart<String, Number> chart, final Series<String, Number> series, final int index) { final ColorPicker picker = new ColorPicker(); picker.setMaxWidth(12); picker.valueProperty().addListener((observable, oldValue, newValue) -> { final String web = getWebColor(newValue); updateColors(chart, series, newValue, web); }); picker.setValue(summarySeriesColors.get(chart.getTitle() + "/" + series.getName()) == null ? defaultColors.get(index % defaultColors.size()) : summarySeriesColors.get(chart.getTitle() + "/" + series.getName())); return picker; } private void updateColors(final LineChart<String, Number> chart, final Series<String, Number> s, final Color newValue, final String web) { s.getNode().setStyle("-fx-stroke: " + web + ";"); s.getData().forEach(n -> n.getNode().setStyle("-fx-background-color: " + web + ", white;")); summarySeriesColors.put(chart.getTitle() + "/" + s.getName(), newValue); } private void saveCharts(final List<LineChart<String, Number>> charts) { summaryCharts.clear(); summaryCharts.addAll(charts); } private void placeSummaryCharts() { calculateColumnsAndRows(chartsColumnsTextField, summaryCharts); placeNodes(summaryCharts, allChartsGrid); } private List<Series<String, Number>> generateSeries(final Result results) { final List<List<String>> imageNames = results.getImageNames(); final List<Series<String, Number>> series = new ArrayList<>(); int index = 0; for (final Entry<String, UnmodifiableArrayList<Double>> e : results.getScores().entrySet()) { final Series<String, Number> s = new Series<>(); s.setName(e.getKey()); for (int i = 0; i < e.getValue().size(); i++) { s.getData().add(new XYChart.Data<>(imageNames.get(index).get(i), e.getValue().get(i))); } series.add(s); index++; } return series; } @FXML void selectAllFunctions() { if (!featuresTab.isSelected()) rightVBoxTabPane.getSelectionModel().select(featuresTab); for (final Node chb : featuresVBox.getChildren()) { ((CheckBox) chb).setSelected(true); } dataGeneratorFactory.chooseAllAvailableFunctions(); } @FXML void merge() { final BarChart<String, Number> chart = new BarChart<>(new CategoryAxis(), createValueAxis()); chartsBySampleGrid.getChildren().stream().filter(node -> node.getStyle().equals(CHART_SELECTED_STYLE)) .map(node -> ((BarChart) node).getData()).forEach(series -> chart.getData().addAll(series)); registerOnChartClicked(chart); final Integer index = findMergeIndex(); charts.get(chartsSampleComboBox.getValue() - 1).removeAll(getSelectedCharts()); charts.get(chartsSampleComboBox.getValue() - 1).add(index, chart); placeCharts(); validateChartsControlsDisableProperties(); } private Integer findMergeIndex() { return chartsBySampleGrid.getChildren().stream().filter(n -> n.getStyle().equals(CHART_SELECTED_STYLE)) .map(n -> charts.get(chartsSampleComboBox.getValue() - 1).indexOf(n)) .min(Integer::compareTo).orElse(0); } @FXML void extract() { final BarChart<String, Number> chart = (BarChart<String, Number>) getSelectedCharts().get(0); final Integer index = chartsSampleComboBox.getValue() - 1; populateNewCharts(chart, index); } private void populateNewCharts(final BarChart<String, Number> chart, final Integer index) { final BarChart<String, Number> firstChart = new BarChart<>(new CategoryAxis(), createValueAxis()); final BarChart<String, Number> secondChart = new BarChart<>(new CategoryAxis(), createValueAxis()); final Series s = findLastSeries(chart, index); final Series[] other = getAllOtherSeries(chart, index, s); firstChart.getData().add(s); secondChart.getData().addAll(other); registerOnChartClicked(firstChart); registerOnChartClicked(secondChart); placeShiftedCharts(firstChart, secondChart, chart); } private Series findLastSeries(final BarChart<String, Number> chart, final Integer index) { return series.get(index).stream() .filter(n -> n.getName().equals(chart.getData().get(chart.getData().size() - 1).getName())) .findAny().orElse(null); } private Series[] getAllOtherSeries(final BarChart<String, Number> chart, final Integer index, final Series s) { final List<String> names = chart.getData().stream() .filter(n -> !n.getName().equals(s.getName())) .map(Series::getName).collect(toList()); return series.get(index).stream().filter(n -> names.contains(n.getName())).toArray(Series[]::new); } private void placeShiftedCharts(final BarChart<String, Number> firstChart, final BarChart<String, Number> secondChart, final BarChart<String, Number> chart) { final Integer index = chartsBySampleGrid.getChildren().stream() .filter(n -> n.getStyle().equals(CHART_SELECTED_STYLE)) .map(n -> charts.get(chartsSampleComboBox.getValue() - 1) .indexOf(n)).min(Integer::compareTo) .orElse(charts.get(chartsSampleComboBox.getValue() - 1).size() - 1); charts.get(chartsSampleComboBox.getValue() - 1).remove(chart); charts.get(chartsSampleComboBox.getValue() - 1).add(index, firstChart); charts.get(chartsSampleComboBox.getValue() - 1).add(index, secondChart); placeCharts(); validateChartsControlsDisableProperties(); } @FXML void delete() { charts.get(chartsSampleComboBox.getValue() - 1).removeAll(getSelectedCharts()); placeCharts(); validateChartsControlsDisableProperties(); } private List<Node> getSelectedCharts() { return chartsBySampleGrid.getChildren().stream() .filter(n -> n.getStyle().equals(CHART_SELECTED_STYLE)) .collect(toList()); } private void placeCharts() { final Integer index = chartsSampleComboBox.getValue() - 1; final List<BarChart<String, Number>> charts = this.charts.get(index); calculateColumnsAndRows(chartsColumnsTextField, charts); placeNodes(charts, chartsBySampleGrid); colorSeries(index); } private void validateChartsControlsDisableProperties() { final List<Node> nodes = getSelectedCharts(); final Integer seriesSize = checkSizes(); final boolean sameSeries = checkNames(nodes); chartsExtractButton.setDisable(nodes.size() != 1 || seriesSize <= 1); chartsRemoveButton.setDisable(nodes.isEmpty()); chartsMergeButton.setDisable(nodes.size() < 2 || !sameSeries); chartsMenuMergeCharts.setDisable(nodes.size() < 2); chartsMenuExtractChart.setDisable(nodes.size() != 1 || seriesSize <= 1); chartsMenuRemoveCharts.setDisable(nodes.isEmpty()); } private void colorSeries(final int index) { final List<BarChart<String, Number>> charts = this.charts.get(index); final List<Series<String, Number>> series = this.series.get(index); final List<Color> defaultColors = asList(Color.web("#f3622d"), Color.web("#fba71b"), Color.web ("#57b757"), Color.web("#41a9c9"), Color.web("#4258c9"), Color.web("#9a42c8"), Color.web ("#c84164"), Color.web("#888888")); for (int i = 0; i < series.size(); i++) { final Series<String, Number> s = series.get(i); final LegendItem item = getLegendItem(charts, s); if (item != null) item.setSymbol(instantiateColorPicker(defaultColors, index, charts, i, s)); } } private Integer checkSizes() { return chartsBySampleGrid .getChildren() .stream() .filter(n -> n.getStyle().equals(CHART_SELECTED_STYLE)) .map(n -> ((BarChart) n).getData().size()) .reduce(Integer::sum).orElse(0); } private boolean checkNames(final List<Node> nodes) { final List<List<String>> seriesNames = new ArrayList<>(); for (final Node node : nodes) { final List<Series<String, Number>> series = ((BarChart<String, Number>) node).getData(); for (final Series<String, Number> s : series) { final List<String> names = s.getData() .stream().map(XYChart.Data::getXValue).collect(Collectors.toList()); seriesNames.add(names); } } return seriesNames.stream().allMatch(list -> list.equals(seriesNames.get(0))); } private LegendItem getLegendItem(final List<BarChart<String, Number>> charts, final Series<? extends String, ? extends Number> series) { return charts.stream() .map(Parent::getChildrenUnmodifiable) .map(nodes -> nodes.stream() .filter(node -> node instanceof Legend).findAny().orElse(null)) .filter(Objects::nonNull) .map(legend -> ((Legend) legend).getItems()) .map(items -> items.stream() .filter(item -> item.getText().equals(series.getName())).findAny() .orElse(null)) .filter(Objects::nonNull) .findAny().orElse(null); } private ColorPicker instantiateColorPicker(final List<Color> defaultColors, final int chartIndex, final List<BarChart<String, Number>> charts, final int seriesIndex, final Series<? extends String, ? extends Number> series) { final ColorPicker picker = new ColorPicker(); picker.setMaxWidth(12); picker.valueProperty().addListener((observable, oldValue, newValue) -> { final String web = getWebColor(newValue); updateColors(chartIndex, charts, series, newValue, web); }); picker.setValue(seriesColors.get(chartIndex).get(series.getName()) == null ? defaultColors.get(seriesIndex % defaultColors.size()) : seriesColors.get(chartIndex).get(series.getName())); return picker; } private void updateColors(final int chartIndex, final List<BarChart<String, Number>> charts, final Series<? extends String, ? extends Number> series, final Color newValue, final String web) { charts.stream() .map(chart -> chart.getData().stream().filter(s -> s.getName().equals(series.getName())) .findAny().orElse(null)) .filter(Objects::nonNull) .map(Series::getData) .forEach(data -> data.forEach(bar -> bar.getNode().setStyle("-fx-bar-fill: " + web + ";"))); seriesColors.get(chartIndex).put(series.getName(), newValue); } @FXML void alignTab() { if (!alignTab.isSelected()) mainTabPane.getSelectionModel().select(alignTab); } @FXML void samplesTab() { if (!samplesTab.isSelected()) mainTabPane.getSelectionModel().select(samplesTab); } @FXML void chartsTab() { if (!chartsTab.isSelected()) mainTabPane.getSelectionModel().select(chartsTab); } @FXML void chartsBySample() { if (!chartsTab.isSelected()) mainTabPane.getSelectionModel().select(chartsTab); if (!bySampleTab.isSelected()) chartsTabPane.getSelectionModel().select(bySampleTab); chartsBySampleRadioButton.setSelected(true); } @FXML void imagesBySample() { if (!chartsTab.isSelected()) mainTabPane.getSelectionModel().select(chartsTab); if (!bySampleTab.isSelected()) chartsTabPane.getSelectionModel().select(bySampleTab); imagesBySampleRadioButton.setSelected(true); } @FXML void allCharts() { if (!chartsTab.isSelected()) mainTabPane.getSelectionModel().select(chartsTab); if (!allChartsTab.isSelected()) chartsTabPane.getSelectionModel().select(allChartsTab); } @FXML void zoomIn() { if (alignTab.isSelected()) updateScrollbars(alignImageView, alignScrollPane, 1); else if (samplesTab.isSelected()) updateScrollbars(samplesImageView, samplesScrollPane, 1); } private void updateScrollbars(final ImageView imageView, final ScrollPane imageScrollPane, final double deltaY) { final double oldScale = imageView.getScaleX(); final double hValue = imageScrollPane.getHvalue(); final double vValue = imageScrollPane.getVvalue(); if (deltaY > 0) { imageView.setScaleX(imageView.getScaleX() * 1.05); } else { imageView.setScaleX(imageView.getScaleX() / 1.05); } final double scale = imageView.getScaleX(); validateScrollbars(imageView, imageScrollPane, scale, oldScale, hValue, vValue); } private void validateScrollbars(final ImageView imageView, final ScrollPane imageScrollPane, final double scale, final double oldScale, final double hValue, final double vValue) { validateHorizontalScrollbar(imageView, imageScrollPane, scale, oldScale, hValue); validateVerticalScrollbar(imageView, imageScrollPane, scale, oldScale, vValue); } private void validateHorizontalScrollbar(final ImageView imageView, final ScrollPane imageScrollPane, final double scale, final double oldScale, final double hValue) { if ((scale * imageView.getImage().getWidth() > imageScrollPane.getWidth())) { final double oldHDenominator = calculateDenominator(oldScale, imageView.getImage().getWidth(), imageScrollPane.getWidth()); final double newHDenominator = calculateDenominator(scale, imageView.getImage().getWidth(), imageScrollPane.getWidth()); imageScrollPane.setHvalue(calculateValue(scale, oldScale, hValue, oldHDenominator, newHDenominator)); } } private void validateVerticalScrollbar(final ImageView imageView, final ScrollPane imageScrollPane, final double scale, final double oldScale, final double vValue) { if ((scale * imageView.getImage().getHeight() > imageScrollPane.getHeight())) { final double oldVDenominator = calculateDenominator(oldScale, imageView.getImage().getHeight(), imageScrollPane.getHeight()); final double newVDenominator = calculateDenominator(scale, imageView.getImage().getHeight(), imageScrollPane.getHeight()); imageScrollPane.setVvalue(calculateValue(scale, oldScale, vValue, oldVDenominator, newVDenominator)); } } private double calculateDenominator(final double scale, final double imageSize, final double paneSize) { return (scale * imageSize - paneSize) * 2 / paneSize; } private double calculateValue(final double scale, final double oldScale, final double value, final double oldDenominator, final double newDenominator) { return ((scale - 1) + (value * oldDenominator - (oldScale - 1)) / oldScale * scale) / newDenominator; } @FXML void zoomOut() { if (alignTab.isSelected()) updateScrollbars(alignImageView, alignScrollPane, -1); else if (samplesTab.isSelected()) updateScrollbars(samplesImageView, samplesScrollPane, -1); } @FXML void calculateResults() { final Stage dialog = showPopup("Calculating results"); final Task<? extends Void> task = createCalculateResultsTask(dialog); startTask(task); } private Task<? extends Void> createCalculateResultsTask(final Stage dialog) { return new Task<Void>() { @Override protected Void call() throws Exception { calculateResults(dialog); return null; } }; } private void calculateResults(final Stage dialog) { try { final SamplesImageData img = state.samplesImages.get(samplesImageList.getSelectionModel().getSelectedItem ()); resetFields(); if (img != null) { calculateResults(img); Platform.runLater(() -> showCharts(dialog)); } } catch (final CvException e) { handleException(dialog, e, "Generating results failed! If you are using custom functions, check them for errors."); } } private void resetFields() { results.set(new ArrayList<>()); series.clear(); charts.clear(); summaryCharts.clear(); seriesColors.clear(); summarySeriesColors.clear(); samples.clear(); } private void calculateResults(final SamplesImageData img) { for (int i = 0; i < img.samples.size(); i++) { samples.add(new ArrayList<>()); final Mat[] images = prepareImages(i); final DataGenerator generator = dataGeneratorFactory.createGenerator(); final Result result = generator .generateData(getImagesCopy(images), samplesImageList.getItems()); addSamplesFromPreprocessedImages(i, generator); saveResults(i, result); } } private Mat[] prepareImages(final int i) { int index = 0; final Mat[] images = new Mat[state.samplesImages.size()]; for (final String key : samplesImageList.getItems()) { final SamplesImageData imageData = state.samplesImages.get(key); prepareImage(imageData.samples.get(i), index, images, imageData); createView(i, images[index], key); index++; } return images; } private void createView(final int index, final Mat image, final String key) { final ImageView view = new ImageView(createImage(image)); view.setPreserveRatio(true); bindSize(view, imagesBySampleGridScrollPane, 2); samples.get(index).add(new Pair<>(key, view)); } private void addSamplesFromPreprocessedImages(final int index, final DataGenerator generator) { final Map<String, Pair<String[], Mat[]>> preprocessedImages = generator.getPreprocessedImages(); for (final Entry<String, Pair<String[], Mat[]>> entry : preprocessedImages.entrySet()) createViews(index, entry); } private void createViews(final int sampleIndex, final Entry<String, Pair<String[], Mat[]>> entry) { final String[] names = entry.getValue().getKey(); final Mat[] images = entry.getValue().getValue(); for (int i = 0; i < names.length; i++) { createView(sampleIndex, images[i], names[i].replaceAll("\\s+", "_") + "_" + entry.getKey().toLowerCase() .replaceAll("\\s+", "_")); } } private void saveResults(final int i, final Result result) { results.get().add(result); series.add(generateSeries(result)); charts.add(new ArrayList<>()); seriesColors.add(new HashMap<>()); createCharts(i); } private void showCharts(final Stage dialog) { chartsSampleComboBox.setItems(observableArrayList( IntStream.range(1, results.get().size() + 1).boxed().collect(toList()))); chartsSampleComboBox.setValue(1); allCharts(); createSummaryCharts(); validateChartsControlsDisableProperties(); dialog.close(); } @FXML void loadImages() { final List<File> selectedFiles = getImageFiles(root.getScene().getWindow()); if (selectedFiles != null) { final Stage dialog = showPopup("Loading images"); final Task<? extends Void> task = createLoadImagesTask(dialog, selectedFiles); startTask(task); } } private Stage showPopup(final String info) { final Stage dialog = StageUtils.initDialog(root.getScene().getWindow()); final HBox box = getHBoxWithLabelAndProgressIndicator(info); final Scene scene = new Scene(box); injectStylesheets(box); dialog.setScene(scene); dialog.show(); return dialog; } private Task<? extends Void> createLoadImagesTask(final Stage dialog, final List<File> selectedFiles) { return new Task<Void>() { @Override protected Void call() throws Exception { loadImages(dialog, selectedFiles); return null; } }; } private void loadImages(final Stage dialog, final List<File> selectedFiles) { for (final File f : selectedFiles) { final String filePath; try { filePath = f.getCanonicalPath(); final Mat image = getImage(filePath); final Image fxImage = getFXImage(image); addNewImage(filePath, image, fxImage); } catch (IOException | CvException e) { handleException(dialog, e, "Loading failed!\nImages might be corrupted, paths may contain non-ASCII symbols or " + "you do not have sufficient read permissions."); break; } } showImage(dialog); } private Mat getImage(final String filePath) { final Mat image = Imgcodecs.imread(filePath, Imgcodecs.CV_LOAD_IMAGE_COLOR); if (image.dataAddr() == 0) throw new CvException("Failed to load image! Check if file path contains only ASCII symbols"); return image; } private Image getFXImage(final Mat image) { final Mat imageCopy = ImageUtils.getImageCopy(image); return createImage(imageCopy); } private void addNewImage(final String filePath, final Mat image, final Image fxImage) { final String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1); if (state.imagesToAlign.containsKey(fileName)) { deleteImageWithName(fileName); } Platform.runLater(() -> { state.imagesToAlign.put(fileName, imageDataFactory.createImageToAlignData(fxImage, image)); alignImageList.getItems().add(fileName); }); } private void handleException(final Stage dialog, final Exception e, final String alert) { Platform.runLater(dialog::close); LOGGER.log(Level.SEVERE, e.toString(), e); Platform.runLater(() -> showAlert(alert)); } private void showImage(final Stage dialog) { Platform.runLater(() -> { alignScrollPane.setHvalue(0.5); alignScrollPane.setVvalue(0.5); alignImageList.getSelectionModel().selectLast(); dialog.close(); }); } private void deleteImageWithName(final String key) { Platform.runLater(() -> { alignImageList.getSelectionModel().clearSelection(); alignImageList.getItems().remove(key); state.imagesToAlign.remove(key); }); } @FXML void deleteImage() { final String key = alignImageList.getSelectionModel().getSelectedItem(); if (key != null) { deleteImageWithName(key); } } @FXML void clearImages() { Platform.runLater(() -> { alignImageList.getSelectionModel().clearSelection(); alignImageList.getItems().clear(); state.imagesToAlign.clear(); }); } @Override public void initialize(final URL location, final ResourceBundle resources) { //FXML fields load assertions assert samplesImageViewAnchor != null : "fx:id=\"samplesImageViewAnchor\" was not injected: check your FXML file 'gifa.fxml'."; assert alignImageViewAnchor != null : "fx:id=\"alignImageViewAnchor\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsMainPane != null : "fx:id=\"chartsMainPane\" was not injected: check your FXML file 'gifa.fxml'."; assert featuresBorderPane != null : "fx:id=\"featuresBorderPane\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesBorderPane != null : "fx:id=\"samplesBorderPane\" was not injected: check your FXML file 'gifa.fxml'."; assert alignBorderPane != null : "fx:id=\"alignBorderPane\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsRemoveButton != null : "fx:id=\"chartsRemoveButton\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsMergeButton != null : "fx:id=\"chartsMergeButton\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsRefreshButton != null : "fx:id=\"chartsRefreshButton\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsExtractButton != null : "fx:id=\"chartsExtractButton\" was not injected: check your FXML file 'gifa.fxml'."; assert clearImagesButton != null : "fx:id=\"clearImagesButton\" was not injected: check your FXML file 'gifa.fxml'."; assert clearSamplesButton != null : "fx:id=\"clearSamplesButton\" was not injected: check your FXML file 'gifa.fxml'."; assert removeImageButton != null : "fx:id=\"removeImageButton\" was not injected: check your FXML file 'gifa.fxml'."; assert removeSampleButton != null : "fx:id=\"removeSampleButton\" was not injected: check your FXML file 'gifa.fxml'."; assert deselectAllButton != null : "fx:id=\"deselectAllButton\" was not injected: check your FXML file 'gifa.fxml'."; assert horizontalFlipButton != null : "fx:id=\"horizontalFlipButton\" was not injected: check your FXML file 'gifa.fxml'."; assert loadImagesButton != null : "fx:id=\"loadImagesButton\" was not injected: check your FXML file 'gifa.fxml'."; assert calculateResultsButton != null : "fx:id=\"calculateResultsButton\" was not injected: check your FXML file 'gifa.fxml'."; assert rotateLeftButton != null : "fx:id=\"rotateLeftButton\" was not injected: check your FXML file 'gifa.fxml'."; assert rotateRightButton != null : "fx:id=\"rotateRightButton\" was not injected: check your FXML file 'gifa.fxml'."; assert selectAllButton != null : "fx:id=\"selectAllButton\" was not injected: check your FXML file 'gifa.fxml'."; assert alignButton != null : "fx:id=\"alignButton\" was not injected: check your FXML file 'gifa.fxml'."; assert verticalFlipButton != null : "fx:id=\"verticalFlipButton\" was not injected: check your FXML file 'gifa.fxml'."; assert sampleBorderColor != null : "fx:id=\"sampleBorderColor\" was not injected: check your FXML file 'gifa.fxml'."; assert sampleFillColor != null : "fx:id=\"sampleFillColor\" was not injected: check your FXML file 'gifa.fxml'."; assert sampleStrokeColor != null : "fx:id=\"sampleStrokeColor\" was not injected: check your FXML file 'gifa.fxml'."; assert triangleFillColor != null : "fx:id=\"triangleFillColor\" was not injected: check your FXML file 'gifa.fxml'."; assert triangleStrokeColor != null : "fx:id=\"triangleStrokeColor\" was not injected: check your FXML file 'gifa.fxml'."; assert vertexBorderColor != null : "fx:id=\"vertexBorderColor\" was not injected: check your FXML file 'gifa.fxml'."; assert vertexFillColor != null : "fx:id=\"vertexFillColor\" was not injected: check your FXML file 'gifa.fxml'."; assert vertexStrokeColor != null : "fx:id=\"vertexStrokeColor\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsSampleComboBox != null : "fx:id=\"chartsSampleComboBox\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesScaleCombo != null : "fx:id=\"samplesScaleCombo\" was not injected: check your FXML file 'gifa.fxml'."; assert alignScaleCombo != null : "fx:id=\"alignScaleCombo\" was not injected: check your FXML file 'gifa.fxml'."; assert allChartsGrid != null : "fx:id=\"allChartsGrid\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsBySampleGrid != null : "fx:id=\"chartsBySampleGrid\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsControls != null : "fx:id=\"chartsControls\" was not injected: check your FXML file 'gifa.fxml'."; assert imagesBySampleGrid != null : "fx:id=\"imagesBySampleGrid\" was not injected: check your FXML file 'gifa.fxml'."; assert root != null : "fx:id=\"root\" was not injected: check your FXML file 'gifa.fxml'."; assert sampleColorControls != null : "fx:id=\"sampleColorControls\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesBottomGrid != null : "fx:id=\"samplesBottomGrid\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesImageListGrid != null : "fx:id=\"samplesImageListGrid\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMainPane != null : "fx:id=\"samplesMainPane\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesToolsGridPane != null : "fx:id=\"samplesToolsGridPane\" was not injected: check your FXML file 'gifa.fxml'."; assert alignBottomGrid != null : "fx:id=\"alignBottomGrid\" was not injected: check your FXML file 'gifa.fxml'."; assert alignColorControls != null : "fx:id=\"alignColorControls\" was not injected: check your FXML file 'gifa.fxml'."; assert alignImageListGrid != null : "fx:id=\"alignImageListGrid\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMainPane != null : "fx:id=\"alignMainPane\" was not injected: check your FXML file 'gifa.fxml'."; assert alignToolsGridPane != null : "fx:id=\"alignToolsGridPane\" was not injected: check your FXML file 'gifa.fxml'."; assert vertexColorControls != null : "fx:id=\"vertexColorControls\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesImageViewGroup != null : "fx:id=\"samplesImageViewGroup\" was not injected: check your FXML file 'gifa.fxml'."; assert alignImageViewGroup != null : "fx:id=\"alignImageViewGroup\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsGraphsHBox != null : "fx:id=\"chartsGraphsHBox\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsGraphsToolbar != null : "fx:id=\"chartsGraphsToolbar\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesTopHBox != null : "fx:id=\"samplesTopHBox\" was not injected: check your FXML file 'gifa.fxml'."; assert selectionButtonsHBox != null : "fx:id=\"selectionButtonsHBox\" was not injected: check your FXML file 'gifa.fxml'."; assert alignImageListToolbar != null : "fx:id=\"alignImageListToolbar\" was not injected: check your FXML file 'gifa.fxml'."; assert alignTopHBox != null : "fx:id=\"alignTopHBox\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesImageView != null : "fx:id=\"samplesImageView\" was not injected: check your FXML file 'gifa.fxml'."; assert alignImageView != null : "fx:id=\"alignImageView\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsColumnsLabel != null : "fx:id=\"chartsColumnsLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsGraphsInfo != null : "fx:id=\"chartsGraphsInfo\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsSampleLabel != null : "fx:id=\"chartsSampleLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert sampleBorderLabel != null : "fx:id=\"sampleBorderLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert sampleFillLabel != null : "fx:id=\"sampleFillLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert sampleStrokeLabel != null : "fx:id=\"sampleStrokeLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesImageSizeLabel != null : "fx:id=\"samplesImageSizeLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesInfo != null : "fx:id=\"samplesInfo\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMousePositionLabel != null : "fx:id=\"samplesMousePositionLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert alignImageListInfo != null : "fx:id=\"alignImageListInfo\" was not injected: check your FXML file 'gifa.fxml'."; assert alignImageSizeLabel != null : "fx:id=\"alignImageSizeLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert alignInfo != null : "fx:id=\"alignInfo\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMousePositionLabel != null : "fx:id=\"alignMousePositionLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert triangleFillLabel != null : "fx:id=\"triangleFillLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert triangleStrokeLabel != null : "fx:id=\"triangleStrokeLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert vertexBorderLabel != null : "fx:id=\"vertexBorderLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert vertexFillLabel != null : "fx:id=\"vertexFillLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert vertexStrokeLabel != null : "fx:id=\"vertexStrokeLabel\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesImageList != null : "fx:id=\"samplesImageList\" was not injected: check your FXML file 'gifa.fxml'."; assert alignImageList != null : "fx:id=\"alignImageList\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsMenu != null : "fx:id=\"chartsMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert editMenu != null : "fx:id=\"editMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert fileMenu != null : "fx:id=\"fileMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert helpMenu != null : "fx:id=\"helpMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert navMenu != null : "fx:id=\"navMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert optionsMenu != null : "fx:id=\"optionsMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert optionsMenuTheme != null : "fx:id=\"optionsMenuTheme\" was not injected: check your FXML file 'gifa.fxml'."; assert runMenu != null : "fx:id=\"runMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMenu != null : "fx:id=\"samplesMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMenu != null : "fx:id=\"alignMenu\" was not injected: check your FXML file 'gifa.fxml'."; assert menuBar != null : "fx:id=\"menuBar\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsMenuExtractChart != null : "fx:id=\"chartsMenuExtractChart\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsMenuMergeCharts != null : "fx:id=\"chartsMenuMergeCharts\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsMenuRemoveCharts != null : "fx:id=\"chartsMenuRemoveCharts\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsMenuRestoreCharts != null : "fx:id=\"chartsMenuRestoreCharts\" was not injected: check your FXML file 'gifa.fxml'."; assert editMenuZoomIn != null : "fx:id=\"editMenuZoomIn\" was not injected: check your FXML file 'gifa.fxml'."; assert editMenuZoomOut != null : "fx:id=\"editMenuZoomOut\" was not injected: check your FXML file 'gifa.fxml'."; assert fileMenuExit != null : "fx:id=\"fileMenuExit\" was not injected: check your FXML file 'gifa.fxml'."; assert fileMenuExportToCsv != null : "fx:id=\"fileMenuExportToCsv\" was not injected: check your FXML file 'gifa.fxml'."; assert fileMenuExportToPng != null : "fx:id=\"fileMenuExportToPng\" was not injected: check your FXML file 'gifa.fxml'."; assert helpMenuAbout != null : "fx:id=\"helpMenuAbout\" was not injected: check your FXML file 'gifa.fxml'."; assert helpMenuHelp != null : "fx:id=\"helpMenuHelp\" was not injected: check your FXML file 'gifa.fxml'."; assert navMenuAllCharts != null : "fx:id=\"navMenuAllCharts\" was not injected: check your FXML file 'gifa.fxml'."; assert navMenuCharts != null : "fx:id=\"navMenuCharts\" was not injected: check your FXML file 'gifa.fxml'."; assert navMenuChartsBySample != null : "fx:id=\"navMenuChartsBySample\" was not injected: check your FXML file 'gifa.fxml'."; assert navMenuImagesBySample != null : "fx:id=\"navMenuImagesBySample\" was not injected: check your FXML file 'gifa.fxml'."; assert navMenuSamples != null : "fx:id=\"navMenuSamples\" was not injected: check your FXML file 'gifa.fxml'."; assert navMenuAlign != null : "fx:id=\"navMenuAlign\" was not injected: check your FXML file 'gifa.fxml'."; assert runMenuCalculateResults != null : "fx:id=\"runMenuCalculateResults\" was not injected: check your FXML file 'gifa.fxml'."; assert runMenuAlign != null : "fx:id=\"runMenuAlign\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMenuClearSamples != null : "fx:id=\"samplesMenuClearSamples\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMenuCreateMode != null : "fx:id=\"samplesMenuCreateMode\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMenuRemoveSample != null : "fx:id=\"samplesMenuRemoveSample\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMenuDeselectAllFeatures != null : "fx:id=\"samplesMenuDeselectAllFeatures\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMenuRotateMode != null : "fx:id=\"samplesMenuRotateMode\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMenuSelectAllFeatures != null : "fx:id=\"samplesMenuSelectAllFeatures\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesMenuSelectMode != null : "fx:id=\"samplesMenuSelectMode\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMenuClearImages != null : "fx:id=\"alignMenuClearImages\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMenuRemoveImage != null : "fx:id=\"alignMenuRemoveImage\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMenuHorizontalFlip != null : "fx:id=\"alignMenuHorizontalFlip\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMenuLoadImages != null : "fx:id=\"alignMenuLoadImages\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMenuMenuRotateLeft != null : "fx:id=\"alignMenuMenuRotateLeft\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMenuMenuRotateRight != null : "fx:id=\"alignMenuMenuRotateRight\" was not injected: check your FXML file 'gifa.fxml'."; assert alignMenuVerticalFlip != null : "fx:id=\"alignMenuVerticalFlip\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsBySampleRadioButton != null : "fx:id=\"chartsBySampleRadioButton\" was not injected: check your FXML file 'gifa.fxml'."; assert createRadioButton != null : "fx:id=\"createRadioButton\" was not injected: check your FXML file 'gifa.fxml'."; assert cubicRadioButton != null : "fx:id=\"cubicRadioButton\" was not injected: check your FXML file 'gifa.fxml'."; assert imagesBySampleRadioButton != null : "fx:id=\"imagesBySampleRadioButton\" was not injected: check your FXML file 'gifa.fxml'."; assert linearRadioButton != null : "fx:id=\"linearRadioButton\" was not injected: check your FXML file 'gifa.fxml'."; assert nearestRadioButton != null : "fx:id=\"nearestRadioButton\" was not injected: check your FXML file 'gifa.fxml'."; assert rotateRadioButton != null : "fx:id=\"rotateRadioButton\" was not injected: check your FXML file 'gifa.fxml'."; assert selectRadioButton != null : "fx:id=\"selectRadioButton\" was not injected: check your FXML file 'gifa.fxml'."; assert optionsMenuThemeDark != null : "fx:id=\"optionsMenuThemeDark\" was not injected: check your FXML file 'gifa.fxml'."; assert optionsMenuThemeLight != null : "fx:id=\"optionsMenuThemeLight\" was not injected: check your FXML file 'gifa.fxml'."; assert allChartsGridScrollPane != null : "fx:id=\"allChartsGridScrollPane\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsBySampleGridScrollPane != null : "fx:id=\"chartsBySampleGridScrollPane\" was not injected: check your FXML file 'gifa.fxml'."; assert featuresScrollPane != null : "fx:id=\"featuresScrollPane\" was not injected: check your FXML file 'gifa.fxml'."; assert imagesBySampleGridScrollPane != null : "fx:id=\"imagesBySampleGridScrollPane\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesScrollPane != null : "fx:id=\"samplesScrollPane\" was not injected: check your FXML file 'gifa.fxml'."; assert alignScrollPane != null : "fx:id=\"alignScrollPane\" was not injected: check your FXML file 'gifa.fxml'."; assert allChartsTab != null : "fx:id=\"allChartsTab\" was not injected: check your FXML file 'gifa.fxml'."; assert bySampleTab != null : "fx:id=\"bySampleTab\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsTab != null : "fx:id=\"chartsTab\" was not injected: check your FXML file 'gifa.fxml'."; assert featuresTab != null : "fx:id=\"featuresTab\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesTab != null : "fx:id=\"samplesTab\" was not injected: check your FXML file 'gifa.fxml'."; assert imageListTab != null : "fx:id=\"imageListTab\" was not injected: check your FXML file 'gifa.fxml'."; assert alignTab != null : "fx:id=\"alignTab\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsTabPane != null : "fx:id=\"chartsTabPane\" was not injected: check your FXML file 'gifa.fxml'."; assert mainTabPane != null : "fx:id=\"mainTabPane\" was not injected: check your FXML file 'gifa.fxml'."; assert rightVBoxTabPane != null : "fx:id=\"rightVBoxTabPane\" was not injected: check your FXML file 'gifa.fxml'."; assert chartsColumnsTextField != null : "fx:id=\"chartsColumnsTextField\" was not injected: check your FXML file 'gifa.fxml'."; assert interpolationTitledPane != null : "fx:id=\"interpolationTitledPane\" was not injected: check your FXML file 'gifa.fxml'."; assert sampleTitledPane != null : "fx:id=\"sampleTitledPane\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesModeTitledPane != null : "fx:id=\"samplesModeTitledPane\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesToolsTitledPane != null : "fx:id=\"samplesToolsTitledPane\" was not injected: check your FXML file 'gifa.fxml'."; assert toolsTitledPane != null : "fx:id=\"toolsTitledPane\" was not injected: check your FXML file 'gifa.fxml'."; assert triangleTitledPane != null : "fx:id=\"triangleTitledPane\" was not injected: check your FXML file 'gifa.fxml'."; assert vertexTitledPane != null : "fx:id=\"vertexTitledPane\" was not injected: check your FXML file 'gifa.fxml'."; assert drawMethod != null : "fx:id=\"drawMethod\" was not injected: check your FXML file 'gifa.fxml'."; assert interpolation != null : "fx:id=\"interpolation\" was not injected: check your FXML file 'gifa.fxml'."; assert bySampleToggle != null : "fx:id=\"bySampleToggle\" was not injected: check your FXML file 'gifa.fxml'."; assert themeToggleGroup != null : "fx:id=\"themeToggleGroup\" was not injected: check your FXML file 'gifa.fxml'."; assert featuresVBox != null : "fx:id=\"featuresVBox\" was not injected: check your FXML file 'gifa.fxml'."; assert interpolationVBox != null : "fx:id=\"interpolationVBox\" was not injected: check your FXML file 'gifa.fxml'."; assert rightVBox != null : "fx:id=\"rightVBox\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesLeftVBox != null : "fx:id=\"samplesLeftVBox\" was not injected: check your FXML file 'gifa.fxml'."; assert samplesModeVBox != null : "fx:id=\"samplesModeVBox\" was not injected: check your FXML file 'gifa.fxml'."; assert alignLeftVBox != null : "fx:id=\"alignLeftVBox\" was not injected: check your FXML file 'gifa.fxml'."; initializeComponents(location, resources); setBindings(); addListeners(); } private void addListeners() { setSelectionListeners(); addVertexZoomListener(); addVertexSelectionListener(); addSampleZoomListener(); addSampleSelectionListener(); addColumnsTextFieldListener(); addScaleListeners(); addOnMouseReleasedListeners(); addOnMouseClickedListeners(); addRotateListeners(); addChartsListeners(); setImageViewControls(alignImageView, alignScrollPane, alignImageViewGroup, alignScaleCombo, alignMousePositionLabel); setImageViewControls(samplesImageView, samplesScrollPane, samplesImageViewGroup, samplesScaleCombo, samplesMousePositionLabel); } private void setBindings() { setVisibilityBindings(); setEnablementBindings(); } private void initializeComponents(final URL location, final ResourceBundle resources) { this.location = location; this.resources = resources; bindScrollPaneSize(); initializeStyle(); initializeComboBoxes(); initializeColorPickers(); createCheckBoxes(); disableChartsControls(); setTooltips(); } private void bindScrollPaneSize() { alignScrollPane.prefHeightProperty().bind(root.heightProperty()); alignScrollPane.prefWidthProperty().bind(root.widthProperty()); } private void addRotateListeners() { rotateRadioButton.selectedProperty().addListener((observable, oldValue, newValue) -> { state.rotate.set(newValue); }); } private void addChartsListeners() { onChartsTabChanged(); onBySampleToggleChanged(); } private void onChartsTabChanged() { chartsTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (oldValue.equals(allChartsTab)) { columns.put(allChartsTab, chartsColumnsTextField.getText()); chartsColumnsTextField.setText(columns.getOrDefault(bySampleToggle.getSelectedToggle(), "3")); refreshSample(bySampleToggle.getSelectedToggle()); } else { columns.put(bySampleToggle.getSelectedToggle(), chartsColumnsTextField.getText()); chartsColumnsTextField.setText(columns.getOrDefault(allChartsTab, "3")); } }); } private void onBySampleToggleChanged() { bySampleToggle.selectedToggleProperty().addListener((observable, oldValue, newValue) -> { if (oldValue != null) { columns.put(oldValue, chartsColumnsTextField.getText()); } chartsColumnsTextField.setText(columns.getOrDefault(newValue, "3")); refreshSample(newValue); }); } private void refreshSample(final Toggle newValue) { if (newValue.equals(chartsBySampleRadioButton)) placeCharts(); else if (newValue.equals(imagesBySampleRadioButton)) placeImages(); } private void addOnMouseClickedListeners() { setOnAlignImageMouseClicked(); setOnSamplesImageMouseClicked(); } private void setOnAlignImageMouseClicked() { alignImageViewGroup.setOnMouseClicked(event -> { if (state.selectedVertex.isNotNull().get()) uncheck(event, state.selectedVertex, alignImageView); }); } private void setOnSamplesImageMouseClicked() { samplesImageViewGroup.setOnMouseClicked(event -> { if (createRadioButton.isSelected()) { state.selectedSample.set(null); final SamplesImageData imageData = createNewSamples(event); showSamples(imageData); } else if (state.selectedSample.isNotNull().get()) uncheck(event, state.selectedSample, samplesImageView); }); } private void uncheck(final MouseEvent event, final ObjectProperty<? extends BasicSample> property, final ImageView samplesImageView) { final Rectangle rectangle = property.get().sampleArea; final double dX = event.getX() / samplesImageView.getScaleX() - rectangle.getX(); final double dY = event.getY() / samplesImageView.getScaleY() - rectangle.getY(); if (dX < 0 || dY < 0 || dX > rectangle.getWidth() || dY > rectangle.getHeight()) property.set(null); } private SamplesImageData createNewSamples(final MouseEvent event) { final SamplesImageData imageData = state.samplesImages.get(samplesImageList.getSelectionModel() .getSelectedItem()); final Image image = imageData.image.get(); final double x = event.getX() / samplesImageView.getScaleX(); final double y = event.getY() / samplesImageView.getScaleY(); final double centerX = Math.max(x, 0); final double centerY = Math.max(y, 0); final double size = image.getWidth() > image.getHeight() ? image.getHeight() / 15 : image.getWidth() / 15; final double radiusX = Math.min(centerX, Math.min(size, image.getWidth() - centerX)); final double radiusY = Math.min(centerY, Math.min(size, image.getHeight() - centerY)); for (final SamplesImageData img : state.samplesImages.values()) basicSampleFactory.createNewSample(img, centerX, centerY, radiusX, radiusY); return imageData; } private void showSamples(final SamplesImageData imageData) { final List<Sample> samples = imageData.samples; final Sample sample = samples.get(samples.size() - 1); samplesImageViewAnchor.getChildren().add(sample.sampleArea); samplesImageViewAnchor.getChildren().add(sample); } private void addOnMouseReleasedListeners() { mainTabPane.setOnMouseReleased(event -> { alignImageViewGroup.getScene().setCursor(Cursor.DEFAULT); samplesImageViewGroup.getScene().setCursor(Cursor.DEFAULT); }); } private void addScaleListeners() { alignImageView.scaleXProperty().addListener((observable, oldValue, newValue) -> { final double scale = newValue.doubleValue(); final ImageToAlignData img = state.imagesToAlign.get(alignImageList.getSelectionModel().getSelectedItem()); if (img != null) img.scale.set(scale); }); samplesImageView.scaleXProperty().addListener((observable, oldValue, newValue) -> { final double scale = newValue.doubleValue(); final SamplesImageData img = state.samplesImages.get(samplesImageList.getSelectionModel().getSelectedItem()); if (img != null) img.scale.set(scale); }); } private void addSampleSelectionListener() { state.selectedSample.addListener((observable, oldValue, newValue) -> { if (newValue != null) { sampleFillColor.setValue((Color) newValue.getFill()); sampleStrokeColor.setValue((Color) newValue.getStroke()); sampleBorderColor.setValue((Color) newValue.sampleArea.getStroke()); for (final Entry<String, SamplesImageData> e : state.samplesImages.entrySet()) { if (e.getValue().samples.contains(newValue)) { samplesTab(); samplesImageList.getSelectionModel().select(e.getKey()); break; } } } }); } private void addVertexSelectionListener() { state.selectedVertex.addListener((observable, oldValue, newValue) -> { if (newValue != null) { vertexFillColor.setValue((Color) newValue.getFill()); vertexStrokeColor.setValue((Color) newValue.getStroke()); vertexBorderColor.setValue((Color) newValue.sampleArea.getStroke()); for (final Entry<String, ImageToAlignData> e : state.imagesToAlign.entrySet()) { if (asList(e.getValue().vertices).contains(newValue)) { alignTab(); alignImageList.getSelectionModel().select(e.getKey()); break; } } } }); } private void addSampleZoomListener() { state.zoomSample.addListener((observable, oldValue, newValue) -> { if (newValue) { final Sample sample = state.selectedSample.get(); calculateZoom(sample, samplesScrollPane, samplesImageView); state.zoomSample.set(false); } }); } private void addVertexZoomListener() { state.zoomVertex.addListener((observable, oldValue, newValue) -> { if (newValue) { final Vertex vertex = state.selectedVertex.get(); calculateZoom(vertex, alignScrollPane, alignImageView); state.zoomVertex.set(false); } }); } private void calculateZoom(final BasicSample sample, final ScrollPane pane, final ImageView view) { final double newX = Math.max(0, sample.sampleArea.getX() - 50); final double newY = Math.max(0, sample.sampleArea.getY() - 50); final double newWidth = sample.sampleArea.getWidth() + 100; final double newHeight = sample.sampleArea.getHeight() + 100; final double scale = pane.getWidth() / pane.getHeight() > newWidth / newHeight ? pane.getHeight() / newHeight : pane.getWidth() / newWidth; view.setScaleX(scale); final double newHDenominator = calculateDenominator( view.getScaleX(), view.getImage().getWidth(), pane.getWidth()); final double newVDenominator = calculateDenominator( view.getScaleX(), view.getImage().getHeight(), pane.getHeight()); pane.setHvalue((Math.max(0, (newX + newWidth / 2) * view.getScaleX() - (pane.getWidth() / 2)) / (pane.getWidth() / 2)) / newHDenominator); pane.setVvalue((Math.max(0, (newY + newHeight / 2) * view.getScaleX() - (pane.getHeight() / 2)) / (pane.getHeight() / 2)) / newVDenominator); } private void initializeColorPickers() { initializeTriangleColorPickers(); initializeVertexColorPickers(); initializeSampleColorPickers(); } private void initializeTriangleColorPickers() { triangleFillColor.valueProperty() .addListener((observable, oldValue, newValue) -> state.imagesToAlign .get(alignImageList.getSelectionModel().getSelectedItem()) .triangle.setFill(newValue)); triangleStrokeColor.valueProperty() .addListener((observable, oldValue, newValue) -> state.imagesToAlign .get(alignImageList.getSelectionModel().getSelectedItem()) .triangle.setStroke(newValue)); } private void initializeVertexColorPickers() { vertexFillColor.valueProperty() .addListener((observable, oldValue, newValue) -> state.selectedVertex.get().setFill(newValue)); vertexStrokeColor.valueProperty() .addListener((observable, oldValue, newValue) -> state.selectedVertex.get().setStroke(newValue)); vertexBorderColor.valueProperty() .addListener((observable, oldValue, newValue) -> state.selectedVertex.get().sampleArea.setStroke(newValue)); } private void initializeSampleColorPickers() { sampleFillColor.valueProperty() .addListener((observable, oldValue, newValue) -> state.selectedSample.get().setFill(newValue)); sampleStrokeColor.valueProperty() .addListener((observable, oldValue, newValue) -> state.selectedSample.get().setStroke(newValue)); sampleBorderColor.valueProperty() .addListener((observable, oldValue, newValue) -> state.selectedSample.get().sampleArea.setStroke(newValue)); } private void disableChartsControls() { chartsExtractButton.setDisable(true); chartsRemoveButton.setDisable(true); chartsMergeButton.setDisable(true); chartsMenuMergeCharts.setDisable(true); chartsMenuExtractChart.setDisable(true); chartsMenuRemoveCharts.setDisable(true); } private void initializeComboBoxes() { initializeScaleComboBoxes(); chartsSampleComboBox.getSelectionModel().selectedItemProperty() .addListener((observable, oldValue, newValue) -> { if (newValue != null) { placeCharts(); placeImages(); validateChartsControlsDisableProperties(); } }); } private void initializeScaleComboBoxes() { alignScaleCombo.itemsProperty().get().addAll( "25%", "50%", "75%", "100%", "125%", "150%", "175%", "200%", "250%", "500%", "1000%" ); alignScaleCombo.setValue("100%"); samplesScaleCombo.itemsProperty().get().addAll( "25%", "50%", "75%", "100%", "125%", "150%", "175%", "200%", "250%", "500%", "1000%" ); samplesScaleCombo.setValue("100%"); } private void initializeStyle() { injectStylesheets(root); if (isLightThemeSelected()) { themeToggleGroup.selectToggle(optionsMenuThemeLight); } else { themeToggleGroup.selectToggle(optionsMenuThemeDark); } } private void placeImages() { final Integer index = chartsSampleComboBox.getValue() - 1; final List<Pair<String, ImageView>> samples = this.samples.get(index); final List<VBox> images = createSampleVBoxes(samples); calculateColumnsAndRows(chartsColumnsTextField, images); placeNodes(images, imagesBySampleGrid); } private List<VBox> createSampleVBoxes(final List<Pair<String, ImageView>> samples) { return samples.stream().map(pair -> { VBox vbox = new VBox(); vbox.setAlignment(Pos.CENTER); vbox.setSpacing(10.0); vbox.getChildren().add(pair.getValue()); vbox.getChildren().add(new Label(pair.getKey())); return vbox; }).collect(toList()); } private void addColumnsTextFieldListener() { chartsColumnsTextField.textProperty().addListener((observable, oldValue, newValue) -> { if (!newValue.matches("[1-9]\\d*")) chartsColumnsTextField.setText(oldValue); else { if (bySampleTab.isSelected() && chartsBySampleRadioButton.isSelected()) placeCharts(); else if (bySampleTab.isSelected() && imagesBySampleRadioButton.isSelected()) placeImages(); else if (allChartsTab.isSelected()) placeSummaryCharts(); } }); } private void createCheckBoxes() { for (final String function : dataGeneratorFactory.getAvailableFunctionsNames()) { final CheckBox checkBox = new CheckBox(function); featuresVBox.getChildren().add(checkBox); checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> { if (newValue) dataGeneratorFactory.chooseFunction(function); else dataGeneratorFactory.deselectFunction(function); }); checkBox.setSelected(true); } } private void setTooltips() { setImagesControlsTooltips(); setAlignControlsTooltips(); setSamplesControlsTooltips(); setChartsControlsTooltips(); } private void setImagesControlsTooltips() { loadImagesButton.setTooltip(new Tooltip("Load images")); removeImageButton.setTooltip(new Tooltip("Remove image")); clearImagesButton.setTooltip(new Tooltip("Clear image list")); } private void setAlignControlsTooltips() { horizontalFlipButton.setTooltip(new Tooltip("Flip horizontally")); verticalFlipButton.setTooltip(new Tooltip("Flip vertically")); rotateLeftButton.setTooltip(new Tooltip("Rotate left by 90°")); rotateRightButton.setTooltip(new Tooltip("Rotate right by 90°")); } private void setSamplesControlsTooltips() { removeSampleButton.setTooltip(new Tooltip("Remove sample")); clearSamplesButton.setTooltip(new Tooltip("Clear samples")); } private void setChartsControlsTooltips() { chartsRefreshButton.setTooltip(new Tooltip("Restore charts")); chartsMergeButton.setTooltip(new Tooltip("Merge charts")); chartsExtractButton.setTooltip(new Tooltip("Extract chart")); chartsRemoveButton.setTooltip(new Tooltip("Remove charts")); } private void setImageViewControls(final ImageView imageView, final ScrollPane imageScrollPane, final Group imageViewGroup, final ComboBox<String> scaleCombo, final Label mousePositionLabel) { setImageViewGroupListeners(imageView, imageScrollPane, imageViewGroup, mousePositionLabel); setImageScrollPaneEventFilter(imageView, imageScrollPane); setImageViewScaleListener(imageView, imageScrollPane, scaleCombo); setComboBoxListener(imageView, scaleCombo); } private void setImageViewGroupListeners(final ImageView imageView, final ScrollPane imageScrollPane, final Group imageViewGroup, final Label mousePositionLabel) { imageViewGroup.setOnMouseMoved(event -> mousePositionLabel.setText( (int) (event.getX() / imageView.getScaleX()) + " : " + (int) (event.getY() / imageView.getScaleY()))); imageViewGroup.setOnMouseExited(event -> mousePositionLabel.setText("- : -")); imageViewGroup.setOnScroll(event -> { if (event.isControlDown() && imageView.getImage() != null) { final double deltaY = event.getDeltaY(); updateScrollbars(imageView, imageScrollPane, deltaY); } }); } private void setImageScrollPaneEventFilter(final ImageView imageView, final ScrollPane imageScrollPane) { imageScrollPane.addEventFilter(ScrollEvent.ANY, event -> { if (event.isControlDown() && imageView.getImage() != null) { final double deltaY = event.getDeltaY(); updateScrollbars(imageView, imageScrollPane, deltaY); event.consume(); } }); } private void setImageViewScaleListener(final ImageView imageView, final ScrollPane imageScrollPane, final ComboBox<String> scaleCombo) { imageView.scaleXProperty().addListener((observable, oldValue, newValue) -> { final double oldScale = oldValue.doubleValue(); final double hValue = imageScrollPane.getHvalue(); final double vValue = imageScrollPane.getVvalue(); final double scale = newValue.doubleValue(); imageView.setScaleY(scale); setImageViewTranslates(imageView); updateScrollbars(imageView, imageScrollPane, oldScale, hValue, vValue, scale); updateComboBox(scaleCombo, newValue); }); } private void updateScrollbars(final ImageView imageView, final ScrollPane imageScrollPane, final double oldScale, final double hValue, final double vValue, final double scale) { if (Math.round(oldScale * 100) != Math.round(scale * 100)) { validateScrollbars(imageView, imageScrollPane, scale, oldScale, hValue, vValue); } } private void updateComboBox(final ComboBox<String> scaleCombo, final Number newValue) { final String asString = String.format("%.0f%%", newValue.doubleValue() * 100); if (!scaleCombo.getValue().equals(asString)) scaleCombo.setValue(asString); } private void setComboBoxListener(final ImageView imageView, final ComboBox<String> scaleCombo) { scaleCombo.valueProperty().addListener((observable, oldValue, newValue) -> { if (!newValue.matches("[1-9]\\d*%")) scaleCombo.setValue(oldValue); else imageView.setScaleX(Double.parseDouble(newValue.substring(0, newValue.length() - 1)) / 100.0); }); } private void setVisibilityBindings() { menuVisibilityBindings(); onAlignImageIsPresent(); onSamplesImageIsPresent(); setChartsControlsVisibilityBindings(); alignImageListInfo.visibleProperty().bind(Bindings.isEmpty(alignImageList.getItems())); onSampleSelected(); } private void menuVisibilityBindings() { alignMenu.visibleProperty().bind(alignTab.selectedProperty()); samplesMenu.visibleProperty().bind(samplesTab.selectedProperty()); chartsMenu.visibleProperty().bind(chartsTab.selectedProperty()); } private void onAlignImageIsPresent() { final BooleanBinding alignImageIsPresent = alignImageView.imageProperty().isNotNull(); alignInfo.visibleProperty().bind(alignImageIsPresent); alignLeftVBox.visibleProperty().bind(alignImageIsPresent); alignImageViewGroup.visibleProperty().bind(alignImageIsPresent); alignBottomGrid.visibleProperty().bind(alignImageIsPresent); } private void onSamplesImageIsPresent() { final BooleanBinding samplesImageIsPresent = samplesImageView.imageProperty().isNotNull(); samplesLeftVBox.visibleProperty().bind(samplesImageIsPresent); samplesImageViewGroup.visibleProperty().bind(samplesImageIsPresent); samplesBottomGrid.visibleProperty().bind(samplesImageIsPresent); rightVBoxTabPane.visibleProperty().bind(samplesImageIsPresent); } private void setChartsControlsVisibilityBindings() { final ReadOnlyBooleanProperty bySampleTabSelected = bySampleTab.selectedProperty(); onBySampleTabSelected(bySampleTabSelected); final BooleanProperty chartsBySampleSelected = chartsBySampleRadioButton.selectedProperty(); chartsGraphsToolbar.visibleProperty().bind(Bindings.and(bySampleTabSelected, chartsBySampleSelected)); chartsGraphsHBox.visibleProperty().bind(Bindings.and(bySampleTabSelected, chartsBySampleSelected)); chartsBySampleGridScrollPane.visibleProperty().bind(chartsBySampleSelected); imagesBySampleGridScrollPane.visibleProperty().bind(imagesBySampleRadioButton.selectedProperty()); } private void onBySampleTabSelected(final ReadOnlyBooleanProperty bySampleTabSelected) { chartsBySampleRadioButton.visibleProperty().bind(bySampleTabSelected); imagesBySampleRadioButton.visibleProperty().bind(bySampleTabSelected); chartsSampleComboBox.visibleProperty().bind(bySampleTabSelected); chartsSampleLabel.visibleProperty().bind(bySampleTabSelected); } private void onSampleSelected() { sampleTitledPane.visibleProperty().bind(Bindings.isNotNull(state.selectedSample)); vertexTitledPane.visibleProperty().bind(Bindings.isNotNull(state.selectedVertex)); } private void setEnablementBindings() { setImageControlsEnablementBindings(); setOnResultsPresentEnablementBindings(); setSamplesControlsEnablementBindings(); setSamplesMenuEnablementBindings(); final ReadOnlyBooleanProperty alignTabSelected = alignTab.selectedProperty(); final ReadOnlyBooleanProperty samplesTabSelected = samplesTab.selectedProperty(); final ReadOnlyBooleanProperty chartsTabSelected = chartsTab.selectedProperty(); final ReadOnlyBooleanProperty bySampleTabSelected = bySampleTab.selectedProperty(); final BooleanProperty chartsBySampleSelected = chartsBySampleRadioButton.selectedProperty(); final BooleanBinding emptyAlignImages = Bindings.isEmpty(alignImageList.getItems()); final BooleanBinding nullAlignImage = alignImageView.imageProperty().isNull(); final BooleanBinding nullSamplesImage = samplesImageView.imageProperty().isNull(); final BooleanBinding alignMenuNotVisible = alignMenu.visibleProperty().not(); final BooleanBinding disableZoom = Bindings.or( chartsTabSelected, Bindings.or(Bindings.and(nullAlignImage, alignTabSelected), Bindings.and(nullSamplesImage, samplesTabSelected))); final BooleanBinding disableAlignControls = Bindings.or(nullAlignImage, alignMenuNotVisible); final BooleanBinding noImages = Bindings.or(emptyAlignImages, alignMenuNotVisible); final BooleanBinding bySampleTabAndChartsTabSelected = Bindings.and(chartsTabSelected, bySampleTabSelected); alignButton.disableProperty().bind(emptyAlignImages); chartsMenuRestoreCharts.disableProperty().bind( Bindings.or(Bindings.or(chartsBySampleSelected.not(), bySampleTabSelected.not()), chartsMenu.visibleProperty().not())); alignMenuClearImages.disableProperty().bind(noImages); alignMenuVerticalFlip.disableProperty().bind(disableAlignControls); alignMenuHorizontalFlip.disableProperty().bind(disableAlignControls); alignMenuMenuRotateLeft.disableProperty().bind(disableAlignControls); alignMenuMenuRotateRight.disableProperty().bind(disableAlignControls); alignMenuLoadImages.disableProperty().bind(alignMenuNotVisible); alignMenuRemoveImage.disableProperty() .bind(Bindings.or(alignImageList.getSelectionModel().selectedItemProperty().isNull(), alignMenuNotVisible)); editMenuZoomIn.disableProperty().bind(disableZoom); editMenuZoomOut.disableProperty().bind(disableZoom); navMenuAlign.disableProperty().bind(alignTabSelected); navMenuSamples.disableProperty().bind(Bindings.or(Bindings.isEmpty(state.samplesImages), samplesTabSelected)); navMenuCharts.disableProperty().bind(Bindings.or(results.isNull(), chartsTabSelected)); navMenuAllCharts.disableProperty().bind(Bindings.or(navMenuCharts.disableProperty(), allChartsTab .selectedProperty())); navMenuChartsBySample.disableProperty().bind(Bindings.or(navMenuCharts.disableProperty(), Bindings.and( bySampleTabAndChartsTabSelected, chartsBySampleSelected))); navMenuImagesBySample.disableProperty().bind(Bindings.or(navMenuCharts.disableProperty(), Bindings.and (bySampleTabAndChartsTabSelected, imagesBySampleRadioButton.selectedProperty()))); runMenuAlign.disableProperty().bind(noImages); } private void setImageControlsEnablementBindings() { removeImageButton.disableProperty().bind(alignImageList.getSelectionModel().selectedItemProperty().isNull()); clearImagesButton.disableProperty().bind(Bindings.isEmpty(alignImageList.getItems())); } private void setOnResultsPresentEnablementBindings() { final BooleanBinding nullResults = results.isNull(); fileMenuExportToCsv.disableProperty().bind(nullResults); fileMenuExportToPng.disableProperty().bind(nullResults); chartsTab.disableProperty().bind(nullResults); } private void setSamplesControlsEnablementBindings() { final IntegerProperty featuresSize = new SimpleIntegerProperty(featuresVBox.getChildren().size()); final BooleanBinding noFeaturesAvailable = Bindings.equal(0, featuresSize); final BooleanBinding noFeaturesChosen = getNoFeaturesChosenBinding(); final BooleanBinding noSamplesAdded = getNoSamplesAddedBinding(); final BooleanBinding noSampleSelected = state.selectedSample.isNull(); final BooleanBinding samplesMenuNotVisible = samplesMenu.visibleProperty().not(); final BooleanBinding emptyList = Bindings.isEmpty(samplesImageList.getItems()); final BooleanBinding cannotCalculateResults = Bindings.or(noSamplesAdded, Bindings.or(emptyList, Bindings.or (noFeaturesAvailable, noFeaturesChosen))); samplesTab.disableProperty().bind(emptyList); removeSampleButton.disableProperty().bind(noSampleSelected); clearSamplesButton.disableProperty().bind(noSamplesAdded); samplesMenuRemoveSample.disableProperty().bind(Bindings.or(noSampleSelected, samplesMenuNotVisible)); samplesMenuClearSamples.disableProperty().bind(Bindings.or(samplesMenuNotVisible, noSamplesAdded)); calculateResultsButton.disableProperty().bind(cannotCalculateResults); runMenuCalculateResults.disableProperty().bind(Bindings.or(samplesMenuNotVisible, cannotCalculateResults)); } private BooleanBinding getNoFeaturesChosenBinding() { return Bindings.createBooleanBinding( () -> featuresVBox.getChildren().stream().filter(CheckBox.class::isInstance) .map(CheckBox.class::cast).noneMatch(CheckBox::isSelected), featuresVBox.getChildren().stream().filter(CheckBox.class::isInstance) .map(CheckBox.class::cast).map(CheckBox::selectedProperty).toArray(Observable[]::new) ); } private BooleanBinding getNoSamplesAddedBinding() { return Bindings.createBooleanBinding( () -> !samplesImageViewAnchor.getChildren().stream().filter(Sample.class::isInstance) .findAny().isPresent(), samplesImageViewAnchor.getChildren() ); } private void setSamplesMenuEnablementBindings() { final BooleanBinding samplesMenuNotVisible = samplesMenu.visibleProperty().not(); samplesMenuCreateMode.disableProperty().bind(Bindings.or(samplesMenuNotVisible, createRadioButton.selectedProperty())); samplesMenuSelectMode.disableProperty().bind(Bindings.or(samplesMenuNotVisible, selectRadioButton.selectedProperty())); samplesMenuRotateMode.disableProperty().bind(Bindings.or(samplesMenuNotVisible, rotateRadioButton.selectedProperty())); samplesMenuSelectAllFeatures.disableProperty().bind(samplesMenuNotVisible); samplesMenuDeselectAllFeatures.disableProperty().bind(samplesMenuNotVisible); } private void setSelectionListeners() { addAlignImageListListener(); addSampleImageListListener(); } private void addAlignImageListListener() { alignImageList.getSelectionModel().selectedItemProperty().addListener( (observable, oldValue, newValue) -> { checkOldAlignImage(oldValue); checkNewAlignImage(newValue); }); } private void checkOldAlignImage(final String oldValue) { if (oldValue != null && !oldValue.isEmpty()) { final ImageToAlignData img = state.imagesToAlign.get(oldValue); hideImage(alignScrollPane, img); removeChildren(img); } } private void removeChildren(final ImageToAlignData img) { if (asList(img.vertices).contains(state.selectedVertex.get())) state.selectedVertex.set(null); alignImageViewAnchor.getChildren().removeAll(img.vertices); alignImageViewAnchor.getChildren().removeAll( stream(img.vertices).map(r -> r.sampleArea).toArray(Rectangle[]::new)); alignImageViewAnchor.getChildren().remove(img.triangle); } private void checkNewAlignImage(final String newValue) { if (newValue != null) { final ImageToAlignData img = state.imagesToAlign.get(newValue); setImage(alignScrollPane, alignImageView, alignImageSizeLabel, img); addChildren(img); setColors(img); } else hideAll(state.selectedVertex, alignImageView, alignImageSizeLabel); } private void addChildren(final ImageToAlignData img) { alignImageViewAnchor.getChildren().add(img.triangle); alignImageViewAnchor.getChildren().addAll( stream(img.vertices).map(r -> r.sampleArea).toArray(Rectangle[]::new) ); alignImageViewAnchor.getChildren().addAll(img.vertices); } private void setColors(final ImageToAlignData img) { triangleFillColor.setValue((Color) img.triangle.getFill()); triangleStrokeColor.setValue((Color) img.triangle.getStroke()); } private void addSampleImageListListener() { samplesImageList.getSelectionModel().selectedItemProperty().addListener( (observable, oldValue, newValue) -> { checkOldSampleImage(oldValue); checkNewSampleImage(newValue); }); } private void checkOldSampleImage(final String oldValue) { if (oldValue != null && !oldValue.isEmpty()) { final SamplesImageData img = state.samplesImages.get(oldValue); hideImage(samplesScrollPane, img); removeChildren(img); } } private void removeChildren(final SamplesImageData img) { if (img.samples.contains(state.selectedSample.get())) state.selectedSample.set(null); samplesImageViewAnchor.getChildren().removeAll(img.samples); samplesImageViewAnchor.getChildren().removeAll( img.samples.stream().map(r -> r.sampleArea).toArray(Rectangle[]::new)); } private void checkNewSampleImage(final String newValue) { if (newValue != null) { final SamplesImageData img = state.samplesImages.get(newValue); setImage(samplesScrollPane, samplesImageView, samplesImageSizeLabel, img); addChildren(img); } else hideAll(state.selectedSample, samplesImageView, samplesImageSizeLabel); } private void addChildren(final SamplesImageData img) { samplesImageViewAnchor.getChildren().addAll( img.samples.stream().map(r -> r.sampleArea).toArray(Rectangle[]::new)); samplesImageViewAnchor.getChildren().addAll(img.samples); } private void hideImage(final ScrollPane pane, final ImageData img) { img.hScrollPos.set(pane.getHvalue()); img.vScrollPos.set(pane.getVvalue()); } private void setImage(final ScrollPane pane, final ImageView view, final Label label, final ImageData img) { view.setImage(img.image.get()); view.setScaleX(img.scale.get()); pane.setHvalue(img.hScrollPos.get()); pane.setVvalue(img.vScrollPos.get()); label.setText((int) img.image.get().getWidth() + "x" + (int) img.image.get().getHeight() + " px"); } private void hideAll(final ObjectProperty<? extends BasicSample> property, final ImageView view, final Label label) { view.setScaleX(1.0); view.setImage(null); label.setText(""); property.set(null); } @FXML void align() { final Stage dialog = showPopup("Aligning images"); final Task<Void> task = createAlignTask(dialog); startTask(task); } private Task<Void> createAlignTask(final Stage dialog) { return new Task<Void>() { @Override protected Void call() throws Exception { align(dialog); return null; } }; } private void align(final Stage dialog) { Platform.runLater(this::resetSamples); final Mat[] images = new Mat[state.imagesToAlign.size()]; final MatOfPoint2f[] points = new MatOfPoint2f[state.imagesToAlign.size()]; int i = 0; for (final String key : alignImageList.getItems()) { images[i] = state.imagesToAlign.get(key).imageData; points[i] = state.imagesToAlign.get(key).triangle.getMatOfVertices(); i++; } final int interpolation = getInterpolationType(); try { align(dialog, images, points, interpolation); } catch (final CvException e) { handleException(dialog, e, "Aligning images failed! Please check selected points."); } } private int getInterpolationType() { return cubicRadioButton.isSelected() ? INTER_CUBIC : linearRadioButton.isSelected() ? INTER_LINEAR : INTER_NEAREST; } private void align(final Stage dialog, final Mat[] images, final MatOfPoint2f[] points, final int interpolation) { final SamplesImageData[] result = align(getImagesCopy(images), points, interpolation); Platform.runLater(() -> addSampleImages(dialog, result)); } private SamplesImageData[] align(final Mat[] images, final MatOfPoint2f[] points, final int interpolation) { assert images.length == points.length : "Images count does not match passed vertices count!"; ImageUtils.performAffineTransformations(images, points, interpolation); return stream(images) .map(i -> imageDataFactory.createSamplesImageData(createImage(i), i)) .toArray(SamplesImageData[]::new); } private void addSampleImages(final Stage dialog, final SamplesImageData[] result) { samplesImageList.getItems().addAll(alignImageList.getItems()); for (int j = 0; j < result.length; j++) state.samplesImages.put(samplesImageList.getItems().get(j), result[j]); showSampleImage(); dialog.close(); } private void showSampleImage() { mainTabPane.getSelectionModel().select(samplesTab); samplesImageList.getSelectionModel().selectFirst(); samplesScrollPane.setHvalue(0.5); samplesScrollPane.setVvalue(0.5); } private void resetSamples() { samplesImageList.getSelectionModel().clearSelection(); samplesImageList.getItems().clear(); state.samplesImages.clear(); samplesImageViewAnchor.getChildren().removeIf(n -> !(n instanceof ImageView)); } @FXML void deleteSample() { final Sample sample = state.selectedSample.get(); if (sample != null) { Platform.runLater(() -> { final int index = sample.getIndexOf(); deleteSample(sample, index); }); } } private void deleteSample(final Sample sample, final int index) { for (final SamplesImageData img : state.samplesImages.values()) { img.samples.remove(index); } state.selectedSample.set(null); samplesImageViewAnchor.getChildren().remove(sample.sampleArea); samplesImageViewAnchor.getChildren().remove(sample); sample.dispose(); } @FXML void clearSamples() { Platform.runLater(() -> { for (final SamplesImageData img : state.samplesImages.values()) { img.samples.forEach(Sample::dispose); img.samples.clear(); } state.selectedSample.set(null); samplesImageViewAnchor.getChildren().removeIf(Sample.class::isInstance); samplesImageViewAnchor.getChildren().removeIf(Rectangle.class::isInstance); }); } @FXML void setCreateMode() { if (!createRadioButton.isSelected()) createRadioButton.setSelected(true); } @FXML void setSelectMode() { if (!selectRadioButton.isSelected()) selectRadioButton.setSelected(true); } @FXML void setRotateMode() { if (!rotateRadioButton.isSelected()) rotateRadioButton.setSelected(true); } @FXML void exportToPng() { final File selectedDirectory = getDirectory(root.getScene().getWindow()); if (selectedDirectory != null) { if (selectedDirectory.canWrite()) { final Stage dialog = showPopup("Saving images"); final Task<Void> task = createWriteImagesTask(selectedDirectory, dialog); startTask(task); } else Platform.runLater(() -> showAlert("Save failed! Check your write permissions.")); } } private Task<Void> createWriteImagesTask(final File selectedDirectory, final Stage dialog) { return new Task<Void>() { @Override protected Void call() throws Exception { writeImages(selectedDirectory, dialog); return null; } }; } private void writeImages(final File selectedDirectory, final Stage dialog) { for (int i = 0; i < samples.size(); i++) { final List<Pair<String, ImageView>> currentSamples = samples.get(i); for (int j = 0; j < currentSamples.size(); j++) { try { writeImage(selectedDirectory, currentSamples, i, j); } catch (final IOException e) { handleException(dialog, e, "Save failed! Check your write permissions."); } } Platform.runLater(dialog::close); } } @FXML void help() { final Stage stage = new Stage(); final WebView helpView = getHelpView(); StageUtils.prepareHelpStage(stage, helpView); injectStylesheets(helpView); stage.show(); } }
package pl.coderslab.domain.devices; import javax.persistence.*; @Entity @Table(name = "raspberry_pins") public class RaspberryPin { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private Integer pinNumber; private Long deviceId; private Boolean available; public RaspberryPin() { } public RaspberryPin(Integer pinNumber, Boolean available) { this.pinNumber = pinNumber; this.available = available; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getPinNumber() { return pinNumber; } public void setPinNumber(Integer pinNumber) { this.pinNumber = pinNumber; } public Long getDeviceId() { return deviceId; } public void setDeviceId(Long deviceId) { this.deviceId = deviceId; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } @Override public String toString() { return pinNumber.toString(); } }
package model.units; import java.util.ArrayList; import simulation.*; import model.people.Citizen; public class PoliceUnit extends Unit{ ArrayList<Citizen> passengers ; int maxCapacity ; int distanceToBase ; public PoliceUnit(String id , Address address ,int stepsPerCycle , int maxCapacity ){ super(id , address ,stepsPerCycle); this.maxCapacity = maxCapacity ; } }
package Tree; import java.util.Stack; /** * @author renyujie518 * @version 1.0.0 * @ClassName BSTtoDoubleLinkedList.java * @Description * 双向链表节点结构和二叉树节点结构是一样的, * 如果你把last认为是left, next认为是next的话。 * 给定一个搜索二叉树(左小右大)的头节点head, 请转化成一条有序的双向链表, 并返回链表的头节点。 * * 使用左神的二叉树的递归套路 提取公共的,从左右树中索取,递归 * * 或者搜索二叉树的中序遍历(左中右)就是升序的,然后再构建双向链表 * * 使用中序遍历访问树的各节点 cur ; * 并在访问每个节点时构建 cur 和前驱节点 pre 的引用指向;中序遍历完成后,最后构建头节点和尾节点的引用指向即可。 * @createTime 2021年08月09日 14:29:00 */ public class BSTtoDoubleLinkedList { public static class Node { public int value; public Node left; public Node right; public Node(int data) { this.value = data; } } //递归方式中序遍历 dfs 转链表 //题中说了还要返回链表的头节点,所以我们还要使用一个变量head来记录第一个节点的指针。 static Node head = null; //pre来记录遍历当前节点之前遍历的那个节点,主要用它来和当前节点给串起来。 static Node pre = null; public static Node convertWithRecursion(Node root) { if (root == null) { return root; } //转化为双向链表(中序遍历每个节点时构建 cur 和前驱节点 pre 的引用指向) dfs(root); /**在剑指offer36中是要求构建"循环双向链表" 进行头节点和尾节点的相互指向 pre.right = head; head.left = pre;**/ //本题只是一个双向链表返回头结点,注意,在上述dfs后,pre一步步走,最终pre指向双向链表中的尾节点 //head还是在那个if里被被指定了 //所以pre直接右指向null把这里断开就可以了 pre.right = null; return head; } public static void dfs(Node curr) { if (curr == null) { return; } //pre用于记录双向链表中位于cur左侧的节点,即上一次迭代中的cur, curr.left = pre; //先遍历左子节点 dfs(curr.left); /**本来这一部分是print在中序遍历的时候,现在把它转化为To链表的逻辑**/ //当pre==null时,cur左侧没有节点,即此时cur为双向链表中的头节点 if (pre == null) { head = curr; } else {//反之,pre!=null时,cur左侧存在节点pre,需要进行pre.right=cur的操作。 //串起来的结果就是前一个节点pre的right指向当前节点curr,然后当前节点curr的left指向前一个节点pre pre.right = curr; } pre = curr;//pre指向当前的cur /**本来这一部分是print在中序遍历的时候,现在把它转化为To链表的逻辑**/ dfs(curr.right);//在递归右子树 //全部迭代完成后,pre指向双向链表中的尾节点 } /** 首先复习非递归写法: public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode cur = root; while (cur != null || !stack.isEmpty()) { if (cur != null) { stack.push(cur); cur = cur.left; } else { cur = stack.pop(); list.add(cur.val); cur = cur.right; } } return list; } **/ //非递归方式中序遍历转链表 public static Node convertWithoutRecursion(Node root) { if (root == null) { return null; } Stack<Node> stack = new Stack<>(); //题中说了还要返回链表的头节点,所以我们还要使用一个变量head来记录第一个节点的指针。 Node head = null; //pre来记录遍历当前节点之前遍历的那个节点,主要用它来和当前节点给串起来。 Node pre = null; Node curr = root; while (curr != null || !stack.isEmpty()) { if (curr != null) { stack.push(root); curr = curr.left; } else { curr = stack.pop(); /**本来这一部分是print在中序遍历的时候,现在把它转化为To链表的逻辑**/ curr.left = pre; if (pre == null) {//当pre==null时,cur左侧没有节点,即此时cur为双向链表中的头节点 head = root; } else { pre.right = curr; } pre = curr; /**本来这一部分是print在中序遍历的时候,现在把它转化为To链表的逻辑**/ curr = curr.right; } } //这一步看上面递归的分析 pre.right = null; return head; } //左神二叉树递归的套路 //公共信息就是二叉树转化为链表后的头和尾 public static class convertType { public Node start; public Node end; public convertType(Node start, Node end) { this.start = start; this.end = end; } } public static Node convertWithZS(Node root) { if (root == null) { return null; } //返回的是链表的头结点信息 return process(root).start; } public static convertType process(Node root){ if (root == null) { return new convertType(null, null); } //获取左右节点的公共信息 convertType leftInfo = process(root.left); convertType rightInfo = process(root.right); if (leftInfo.end != null) {//防止空指针异常 //左树的最后一个节点的右侧连接root 构成链表的左半部分 leftInfo.end.right = root; } //单独处理链表中间部分的root root.left = leftInfo.end; root.right = rightInfo.start; if (rightInfo.start != null) { //右树的第一个节点的左侧连接root 构成链表的右半部分 rightInfo.start.left = root; } //这时候要考虑两种畸形 比如没有左半树只有root后右半树这样的半个数(右边同理) //这时候要保证返回的链表信息中的正确性 leftInfo.start和rightInfo.end都是上述的畸形情况,说明没有那半个 //最理想的情况当然是返回convertType(leftInfo.start,rightInfo.end) return new convertType( leftInfo.start != null ? leftInfo.start : root, rightInfo.end != null ? rightInfo.end : root ); } public static void printBSTInOrder(Node head) { System.out.print("二叉搜索树中序: "); if (head != null) { inOrderPrint(head); } System.out.println(); } //中序打印树 public static void inOrderPrint(Node head) { if (head == null) { return; } inOrderPrint(head.left); System.out.print(head.value + " "); inOrderPrint(head.right); } //打印双向链表 public static void printDoubleLinkedList(Node head) { System.out.print("双向链表: "); Node end = null; while (head != null) { System.out.print(head.value + " "); end = head; head = head.right; } System.out.print("| "); while (end != null) { System.out.print(end.value + " "); end = end.left; } System.out.println(); } public static void main(String[] args) { Node head1 = new Node(5); head1.left = new Node(2); head1.right = new Node(9); head1.left.left = new Node(1); head1.left.right = new Node(3); head1.left.right.right = new Node(4); head1.right.left = new Node(7); head1.right.right = new Node(10); head1.left.left = new Node(1); head1.right.left.left = new Node(6); head1.right.left.right = new Node(8); System.out.println("非递归中序"); printBSTInOrder(head1); head1 = convertWithoutRecursion(head1); printDoubleLinkedList(head1); Node head2 = new Node(5); head2.left = new Node(2); head2.right = new Node(9); head2.left.left = new Node(1); head2.left.right = new Node(3); head2.left.right.right = new Node(4); head2.right.left = new Node(7); head2.right.right = new Node(10); head2.left.left = new Node(1); head2.right.left.left = new Node(6); head2.right.left.right = new Node(8); System.out.println("递归中序"); printBSTInOrder(head2); head2 = convertWithRecursion(head2); printDoubleLinkedList(head2); Node head3 = new Node(5); head3.left = new Node(2); head3.right = new Node(9); head3.left.left = new Node(1); head3.left.right = new Node(3); head3.left.right.right = new Node(4); head3.right.left = new Node(7); head3.right.right = new Node(10); head3.left.left = new Node(1); head3.right.left.left = new Node(6); head3.right.left.right = new Node(8); System.out.println("左神递归"); printBSTInOrder(head3); head3 = convertWithZS(head3); printDoubleLinkedList(head3); } }
package sort; import java.util.Arrays; /** * 选择排序 * @author gq *(1)每次排序的时候都需要寻找第n小的数据,并且和array[n-1]发生交换 (2)等到n个数据都排序好,那么选择排序结束。 */ public class Select { private static int[] array = { 49, 38, 65, 97, 76, 13, 27, 65}; private static void sort(int[] array) { for (int i = 0; i < array.length; i++) { for (int j = i+1; j < array.length; j++) { if(array[i]>array[j]){ sortUtils.change(array, i, j); } } } } public static void main(String[] args) { sort(array); System.out.println(Arrays.toString(array)); } }
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.cirqwizard.test.fx; import org.cirqwizard.fx.PCBSize; import org.junit.Test; import static org.junit.Assert.*; public class PCBSizeTest { private PCBSize largePcb = PCBSize.Large; @Test public void testPCBSmallerThanLaminate() { assertTrue(largePcb.checkFit(10_000, 10_000)); } @Test public void testPCBLargerThanLaminate() { assertFalse(largePcb.checkFit(200_000, 200_000)); } @Test public void testPCBSizeEqualToLaminate() { assertTrue(largePcb.checkFit(100_000, 160_000)); } @Test public void testPCBWidthEqualToLaminate() { assertTrue(largePcb.checkFit(100_000, 50_000)); } @Test public void testPCBHeightEqualToLaminate() { assertTrue(largePcb.checkFit(50_000, 160_000)); } @Test public void testPCBSizeCheckTolerance() { assertTrue(largePcb.checkFit(100_100, 160_100)); } }
package pro.eddiecache.kits.paxos.messages; import pro.eddiecache.kits.paxos.comm.Member; /** * 成员给leader回复确认 */ public class SuccessAck implements MessageWithSender, SpecialMessage { private static final long serialVersionUID = 1L; private final long msgId; private Member sender; public SuccessAck(long msgId, Member sender) { this.msgId = msgId; this.sender = sender; } @Override public Member getSender() { return sender; } public long getMsgId() { return msgId; } @Override public MessageType getMessageType() { return MessageType.SUCCESS_ACK; } @Override public String toString() { return "SUCCESS_ACK " + msgId + " " + sender.toString(); } }
package com.mrhan.text.tatl.base; import com.mrhan.util.CodeRuntimeTest; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import java.lang.reflect.Field; import java.util.Date; import static org.junit.Assert.*; public class TextTemplateTest { public double i ; @Test public void test() throws NoSuchFieldException, IllegalAccessException { CodeRuntimeTest crt = new CodeRuntimeTest(); CodeRuntimeTest.hidden(); crt.lockTime(); TextTemplateTest t = new TextTemplateTest(); Field f= TextTemplateTest.class.getField("i"); crt.showTimeMsg("Create:"); Object o = new Integer(1); f.set(t,o); crt.showTimeMsg("SET:"); o = f.get(t); crt.showTimeMsg("GET:"); System.out.println(o.getClass()); crt.showTimeMsg("OUT:"); } @Test public void typeTest() { System.out.println(int.class.asSubclass(int.class)); } }
/* Reverse list iteratively and recursively */ class Node { int data; Node next; /* public Node() { data = -1; next = null; } */ public Node(int d) { data = d; next = null; } } class LinkedList { Node head = null; int length; public LinkedList() { length = 0; } public void printList() { if (isEmpty()) return; Node ptr = head; while (ptr != null) { System.out.println(ptr.data); ptr = ptr.next; } System.out.println(); } public boolean isEmpty() { if (head == null || length <=0) { System.out.println("The list is empty"); return true; } else return false; } // time complexity O(n) public void append(int d) { Node node = new Node(d); // empty list, first node if (head == null) { head = node; length++; return; } Node ptr = head; // cursor pointer while (ptr.next != null) ptr = ptr.next; ptr.next = node; length++; } // delete list quick public void deleteListQuick() { head = null; length = 0; } // invert linked list LINEARLY // header --> a --> b --> c --> null public void reverseList(){ Node curr = head; Node prev = null; Node next = null; while(curr != null){ next = curr.next; // store the next item to invert curr.next = prev; // the curr.next will previous : null, a, b prev = curr; // the next previous will be the present current curr = next; // the current will the stored next } head = prev; } // invert linked list RECURSIVELY public void reverseListRec(){ head = reverseUtil(head, null); } public Node reverseUtil(Node curr, Node next){ Node prev; if (curr == null) return curr; if (curr.next == null) { curr.next = next; return curr; } prev = reverseUtil(curr.next, curr); curr.next = next; return prev; } } public class Main { public static void main(String args[]) { LinkedList list = new LinkedList(); System.out.println("\nInsert node without sorting"); list.append(27); list.append(12); list.append(1); list.append(1009); list.append(4); list.append(5); list.append(23); list.append(9); list.printList(); System.out.println("\nReverse list : "); list.reverseList(); list.printList(); System.out.println("\nRecursively Reverse list : "); list.reverseListRec(); list.printList(); } }
package initializer; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; public class EnvPicker { private static final String ENV_KEY = "available_environment"; private static final String ENV_RESOURCE_FILE = "env.conf"; static String getEnvKey(String env){ Config config = ConfigFactory.parseResources(ENV_RESOURCE_FILE); if(!config.getAnyRefList(ENV_KEY).contains(env)){ throw new RuntimeException( "The Environment you choose is not valid. " + "Please Choose one in this list: "+ config.getAnyRefList(ENV_KEY)); } return env; } }
package com; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class CalculatorService { @GetMapping("/calculate") public int sum(int a, int b) { return a+b; } public int diff(int a, int b) { return a-b; } public int mul(int a, int b) { return a*b; } public int div(int a, int b) { return a/b; } }
package safezero.base2048; final class Japanese { static final String[] WORDS = new String[]{ "あいこくしん", "あいさつ", "あいだ", "あおぞら", "あかちゃん", "あきる", "あけがた", "あける", "あこがれる", "あさい", "あさひ", "あしあと", "あじわう", "あずかる", "あずき", "あそぶ", "あたえる", "あたためる", "あたりまえ", "あたる", "あつい", "あつかう", "あっしゅく", "あつまり", "あつめる", "あてな", "あてはまる", "あひる", "あぶら", "あぶる", "あふれる", "あまい", "あまど", "あまやかす", "あまり", "あみもの", "あめりか", "あやまる", "あゆむ", "あらいぐま", "あらし", "あらすじ", "あらためる", "あらゆる", "あらわす", "ありがとう", "あわせる", "あわてる", "あんい", "あんがい", "あんこ", "あんぜん", "あんてい", "あんない", "あんまり", "いいだす", "いおん", "いがい", "いがく", "いきおい", "いきなり", "いきもの", "いきる", "いくじ", "いくぶん", "いけばな", "いけん", "いこう", "いこく", "いこつ", "いさましい", "いさん", "いしき", "いじゅう", "いじょう", "いじわる", "いずみ", "いずれ", "いせい", "いせえび", "いせかい", "いせき", "いぜん", "いそうろう", "いそがしい", "いだい", "いだく", "いたずら", "いたみ", "いたりあ", "いちおう", "いちじ", "いちど", "いちば", "いちぶ", "いちりゅう", "いつか", "いっしゅん", "いっせい", "いっそう", "いったん", "いっち", "いってい", "いっぽう", "いてざ", "いてん", "いどう", "いとこ", "いない", "いなか", "いねむり", "いのち", "いのる", "いはつ", "いばる", "いはん", "いびき", "いひん", "いふく", "いへん", "いほう", "いみん", "いもうと", "いもたれ", "いもり", "いやがる", "いやす", "いよかん", "いよく", "いらい", "いらすと", "いりぐち", "いりょう", "いれい", "いれもの", "いれる", "いろえんぴつ", "いわい", "いわう", "いわかん", "いわば", "いわゆる", "いんげんまめ", "いんさつ", "いんしょう", "いんよう", "うえき", "うえる", "うおざ", "うがい", "うかぶ", "うかべる", "うきわ", "うくらいな", "うくれれ", "うけたまわる", "うけつけ", "うけとる", "うけもつ", "うける", "うごかす", "うごく", "うこん", "うさぎ", "うしなう", "うしろがみ", "うすい", "うすぎ", "うすぐらい", "うすめる", "うせつ", "うちあわせ", "うちがわ", "うちき", "うちゅう", "うっかり", "うつくしい", "うったえる", "うつる", "うどん", "うなぎ", "うなじ", "うなずく", "うなる", "うねる", "うのう", "うぶげ", "うぶごえ", "うまれる", "うめる", "うもう", "うやまう", "うよく", "うらがえす", "うらぐち", "うらない", "うりあげ", "うりきれ", "うるさい", "うれしい", "うれゆき", "うれる", "うろこ", "うわき", "うわさ", "うんこう", "うんちん", "うんてん", "うんどう", "えいえん", "えいが", "えいきょう", "えいご", "えいせい", "えいぶん", "えいよう", "えいわ", "えおり", "えがお", "えがく", "えきたい", "えくせる", "えしゃく", "えすて", "えつらん", "えのぐ", "えほうまき", "えほん", "えまき", "えもじ", "えもの", "えらい", "えらぶ", "えりあ", "えんえん", "えんかい", "えんぎ", "えんげき", "えんしゅう", "えんぜつ", "えんそく", "えんちょう", "えんとつ", "おいかける", "おいこす", "おいしい", "おいつく", "おうえん", "おうさま", "おうじ", "おうせつ", "おうたい", "おうふく", "おうべい", "おうよう", "おえる", "おおい", "おおう", "おおどおり", "おおや", "おおよそ", "おかえり", "おかず", "おがむ", "おかわり", "おぎなう", "おきる", "おくさま", "おくじょう", "おくりがな", "おくる", "おくれる", "おこす", "おこなう", "おこる", "おさえる", "おさない", "おさめる", "おしいれ", "おしえる", "おじぎ", "おじさん", "おしゃれ", "おそらく", "おそわる", "おたがい", "おたく", "おだやか", "おちつく", "おっと", "おつり", "おでかけ", "おとしもの", "おとなしい", "おどり", "おどろかす", "おばさん", "おまいり", "おめでとう", "おもいで", "おもう", "おもたい", "おもちゃ", "おやつ", "おやゆび", "およぼす", "おらんだ", "おろす", "おんがく", "おんけい", "おんしゃ", "おんせん", "おんだん", "おんちゅう", "おんどけい", "かあつ", "かいが", "がいき", "がいけん", "がいこう", "かいさつ", "かいしゃ", "かいすいよく", "かいぜん", "かいぞうど", "かいつう", "かいてん", "かいとう", "かいふく", "がいへき", "かいほう", "かいよう", "がいらい", "かいわ", "かえる", "かおり", "かかえる", "かがく", "かがし", "かがみ", "かくご", "かくとく", "かざる", "がぞう", "かたい", "かたち", "がちょう", "がっきゅう", "がっこう", "がっさん", "がっしょう", "かなざわし", "かのう", "がはく", "かぶか", "かほう", "かほご", "かまう", "かまぼこ", "かめれおん", "かゆい", "かようび", "からい", "かるい", "かろう", "かわく", "かわら", "がんか", "かんけい", "かんこう", "かんしゃ", "かんそう", "かんたん", "かんち", "がんばる", "きあい", "きあつ", "きいろ", "ぎいん", "きうい", "きうん", "きえる", "きおう", "きおく", "きおち", "きおん", "きかい", "きかく", "きかんしゃ", "ききて", "きくばり", "きくらげ", "きけんせい", "きこう", "きこえる", "きこく", "きさい", "きさく", "きさま", "きさらぎ", "ぎじかがく", "ぎしき", "ぎじたいけん", "ぎじにってい", "ぎじゅつしゃ", "きすう", "きせい", "きせき", "きせつ", "きそう", "きぞく", "きぞん", "きたえる", "きちょう", "きつえん", "ぎっちり", "きつつき", "きつね", "きてい", "きどう", "きどく", "きない", "きなが", "きなこ", "きぬごし", "きねん", "きのう", "きのした", "きはく", "きびしい", "きひん", "きふく", "きぶん", "きぼう", "きほん", "きまる", "きみつ", "きむずかしい", "きめる", "きもだめし", "きもち", "きもの", "きゃく", "きやく", "ぎゅうにく", "きよう", "きょうりゅう", "きらい", "きらく", "きりん", "きれい", "きれつ", "きろく", "ぎろん", "きわめる", "ぎんいろ", "きんかくじ", "きんじょ", "きんようび", "ぐあい", "くいず", "くうかん", "くうき", "くうぐん", "くうこう", "ぐうせい", "くうそう", "ぐうたら", "くうふく", "くうぼ", "くかん", "くきょう", "くげん", "ぐこう", "くさい", "くさき", "くさばな", "くさる", "くしゃみ", "くしょう", "くすのき", "くすりゆび", "くせげ", "くせん", "ぐたいてき", "くださる", "くたびれる", "くちこみ", "くちさき", "くつした", "ぐっすり", "くつろぐ", "くとうてん", "くどく", "くなん", "くねくね", "くのう", "くふう", "くみあわせ", "くみたてる", "くめる", "くやくしょ", "くらす", "くらべる", "くるま", "くれる", "くろう", "くわしい", "ぐんかん", "ぐんしょく", "ぐんたい", "ぐんて", "けあな", "けいかく", "けいけん", "けいこ", "けいさつ", "げいじゅつ", "けいたい", "げいのうじん", "けいれき", "けいろ", "けおとす", "けおりもの", "げきか", "げきげん", "げきだん", "げきちん", "げきとつ", "げきは", "げきやく", "げこう", "げこくじょう", "げざい", "けさき", "げざん", "けしき", "けしごむ", "けしょう", "げすと", "けたば", "けちゃっぷ", "けちらす", "けつあつ", "けつい", "けつえき", "けっこん", "けつじょ", "けっせき", "けってい", "けつまつ", "げつようび", "げつれい", "けつろん", "げどく", "けとばす", "けとる", "けなげ", "けなす", "けなみ", "けぬき", "げねつ", "けねん", "けはい", "げひん", "けぶかい", "げぼく", "けまり", "けみかる", "けむし", "けむり", "けもの", "けらい", "けろけろ", "けわしい", "けんい", "けんえつ", "けんお", "けんか", "げんき", "けんげん", "けんこう", "けんさく", "けんしゅう", "けんすう", "げんそう", "けんちく", "けんてい", "けんとう", "けんない", "けんにん", "げんぶつ", "けんま", "けんみん", "けんめい", "けんらん", "けんり", "こあくま", "こいぬ", "こいびと", "ごうい", "こうえん", "こうおん", "こうかん", "ごうきゅう", "ごうけい", "こうこう", "こうさい", "こうじ", "こうすい", "ごうせい", "こうそく", "こうたい", "こうちゃ", "こうつう", "こうてい", "こうどう", "こうない", "こうはい", "ごうほう", "ごうまん", "こうもく", "こうりつ", "こえる", "こおり", "ごかい", "ごがつ", "ごかん", "こくご", "こくさい", "こくとう", "こくない", "こくはく", "こぐま", "こけい", "こける", "ここのか", "こころ", "こさめ", "こしつ", "こすう", "こせい", "こせき", "こぜん", "こそだて", "こたい", "こたえる", "こたつ", "こちょう", "こっか", "こつこつ", "こつばん", "こつぶ", "こてい", "こてん", "ことがら", "ことし", "ことば", "ことり", "こなごな", "こねこね", "このまま", "このみ", "このよ", "ごはん", "こひつじ", "こふう", "こふん", "こぼれる", "ごまあぶら", "こまかい", "ごますり", "こまつな", "こまる", "こむぎこ", "こもじ", "こもち", "こもの", "こもん", "こやく", "こやま", "こゆう", "こゆび", "こよい", "こよう", "こりる", "これくしょん", "ころっけ", "こわもて", "こわれる", "こんいん", "こんかい", "こんき", "こんしゅう", "こんすい", "こんだて", "こんとん", "こんなん", "こんびに", "こんぽん", "こんまけ", "こんや", "こんれい", "こんわく", "ざいえき", "さいかい", "さいきん", "ざいげん", "ざいこ", "さいしょ", "さいせい", "ざいたく", "ざいちゅう", "さいてき", "ざいりょう", "さうな", "さかいし", "さがす", "さかな", "さかみち", "さがる", "さぎょう", "さくし", "さくひん", "さくら", "さこく", "さこつ", "さずかる", "ざせき", "さたん", "さつえい", "ざつおん", "ざっか", "ざつがく", "さっきょく", "ざっし", "さつじん", "ざっそう", "さつたば", "さつまいも", "さてい", "さといも", "さとう", "さとおや", "さとし", "さとる", "さのう", "さばく", "さびしい", "さべつ", "さほう", "さほど", "さます", "さみしい", "さみだれ", "さむけ", "さめる", "さやえんどう", "さゆう", "さよう", "さよく", "さらだ", "ざるそば", "さわやか", "さわる", "さんいん", "さんか", "さんきゃく", "さんこう", "さんさい", "ざんしょ", "さんすう", "さんせい", "さんそ", "さんち", "さんま", "さんみ", "さんらん", "しあい", "しあげ", "しあさって", "しあわせ", "しいく", "しいん", "しうち", "しえい", "しおけ", "しかい", "しかく", "じかん", "しごと", "しすう", "じだい", "したうけ", "したぎ", "したて", "したみ", "しちょう", "しちりん", "しっかり", "しつじ", "しつもん", "してい", "してき", "してつ", "じてん", "じどう", "しなぎれ", "しなもの", "しなん", "しねま", "しねん", "しのぐ", "しのぶ", "しはい", "しばかり", "しはつ", "しはらい", "しはん", "しひょう", "しふく", "じぶん", "しへい", "しほう", "しほん", "しまう", "しまる", "しみん", "しむける", "じむしょ", "しめい", "しめる", "しもん", "しゃいん", "しゃうん", "しゃおん", "じゃがいも", "しやくしょ", "しゃくほう", "しゃけん", "しゃこ", "しゃざい", "しゃしん", "しゃせん", "しゃそう", "しゃたい", "しゃちょう", "しゃっきん", "じゃま", "しゃりん", "しゃれい", "じゆう", "じゅうしょ", "しゅくはく", "じゅしん", "しゅっせき", "しゅみ", "しゅらば", "じゅんばん", "しょうかい", "しょくたく", "しょっけん", "しょどう", "しょもつ", "しらせる", "しらべる", "しんか", "しんこう", "じんじゃ", "しんせいじ", "しんちく", "しんりん", "すあげ", "すあし", "すあな", "ずあん", "すいえい", "すいか", "すいとう", "ずいぶん", "すいようび", "すうがく", "すうじつ", "すうせん", "すおどり", "すきま", "すくう", "すくない", "すける", "すごい", "すこし", "ずさん", "すずしい", "すすむ", "すすめる", "すっかり", "ずっしり", "ずっと", "すてき", "すてる", "すねる", "すのこ", "すはだ", "すばらしい", "ずひょう", "ずぶぬれ", "すぶり", "すふれ", "すべて", "すべる", "ずほう", "すぼん", "すまい", "すめし", "すもう", "すやき", "すらすら", "するめ", "すれちがう", "すろっと", "すわる", "すんぜん", "すんぽう", "せあぶら", "せいかつ", "せいげん", "せいじ", "せいよう", "せおう", "せかいかん", "せきにん", "せきむ", "せきゆ", "せきらんうん", "せけん", "せこう", "せすじ", "せたい", "せたけ", "せっかく", "せっきゃく", "ぜっく", "せっけん", "せっこつ", "せっさたくま", "せつぞく", "せつだん", "せつでん", "せっぱん", "せつび", "せつぶん", "せつめい", "せつりつ", "せなか", "せのび", "せはば", "せびろ", "せぼね", "せまい", "せまる", "せめる", "せもたれ", "せりふ", "ぜんあく", "せんい", "せんえい", "せんか", "せんきょ", "せんく", "せんげん", "ぜんご", "せんさい", "せんしゅ", "せんすい", "せんせい", "せんぞ", "せんたく", "せんちょう", "せんてい", "せんとう", "せんぬき", "せんねん", "せんぱい", "ぜんぶ", "ぜんぽう", "せんむ", "せんめんじょ", "せんもん", "せんやく", "せんゆう", "せんよう", "ぜんら", "ぜんりゃく", "せんれい", "せんろ", "そあく", "そいとげる", "そいね", "そうがんきょう", "そうき", "そうご", "そうしん", "そうだん", "そうなん", "そうび", "そうめん", "そうり", "そえもの", "そえん", "そがい", "そげき", "そこう", "そこそこ", "そざい", "そしな", "そせい", "そせん", "そそぐ", "そだてる", "そつう", "そつえん", "そっかん", "そつぎょう", "そっけつ", "そっこう", "そっせん", "そっと", "そとがわ", "そとづら", "そなえる", "そなた", "そふぼ", "そぼく", "そぼろ", "そまつ", "そまる", "そむく", "そむりえ", "そめる", "そもそも", "そよかぜ", "そらまめ", "そろう", "そんかい", "そんけい", "そんざい", "そんしつ", "そんぞく", "そんちょう", "ぞんび", "ぞんぶん", "そんみん", "たあい", "たいいん", "たいうん", "たいえき", "たいおう", "だいがく", "たいき", "たいぐう", "たいけん", "たいこ", "たいざい", "だいじょうぶ", "だいすき", "たいせつ", "たいそう", "だいたい", "たいちょう", "たいてい", "だいどころ", "たいない", "たいねつ", "たいのう", "たいはん", "だいひょう", "たいふう", "たいへん", "たいほ", "たいまつばな", "たいみんぐ", "たいむ", "たいめん", "たいやき", "たいよう", "たいら", "たいりょく", "たいる", "たいわん", "たうえ", "たえる", "たおす", "たおる", "たおれる", "たかい", "たかね", "たきび", "たくさん", "たこく", "たこやき", "たさい", "たしざん", "だじゃれ", "たすける", "たずさわる", "たそがれ", "たたかう", "たたく", "ただしい", "たたみ", "たちばな", "だっかい", "だっきゃく", "だっこ", "だっしゅつ", "だったい", "たてる", "たとえる", "たなばた", "たにん", "たぬき", "たのしみ", "たはつ", "たぶん", "たべる", "たぼう", "たまご", "たまる", "だむる", "ためいき", "ためす", "ためる", "たもつ", "たやすい", "たよる", "たらす", "たりきほんがん", "たりょう", "たりる", "たると", "たれる", "たれんと", "たろっと", "たわむれる", "だんあつ", "たんい", "たんおん", "たんか", "たんき", "たんけん", "たんご", "たんさん", "たんじょうび", "だんせい", "たんそく", "たんたい", "だんち", "たんてい", "たんとう", "だんな", "たんにん", "だんねつ", "たんのう", "たんぴん", "だんぼう", "たんまつ", "たんめい", "だんれつ", "だんろ", "だんわ", "ちあい", "ちあん", "ちいき", "ちいさい", "ちえん", "ちかい", "ちから", "ちきゅう", "ちきん", "ちけいず", "ちけん", "ちこく", "ちさい", "ちしき", "ちしりょう", "ちせい", "ちそう", "ちたい", "ちたん", "ちちおや", "ちつじょ", "ちてき", "ちてん", "ちぬき", "ちぬり", "ちのう", "ちひょう", "ちへいせん", "ちほう", "ちまた", "ちみつ", "ちみどろ", "ちめいど", "ちゃんこなべ", "ちゅうい", "ちゆりょく", "ちょうし", "ちょさくけん", "ちらし", "ちらみ", "ちりがみ", "ちりょう", "ちるど", "ちわわ", "ちんたい", "ちんもく", "ついか", "ついたち", "つうか", "つうじょう", "つうはん", "つうわ", "つかう", "つかれる", "つくね", "つくる", "つけね", "つける", "つごう", "つたえる", "つづく", "つつじ", "つつむ", "つとめる", "つながる", "つなみ", "つねづね", "つのる", "つぶす", "つまらない", "つまる", "つみき", "つめたい", "つもり", "つもる", "つよい", "つるぼ", "つるみく", "つわもの", "つわり", "てあし", "てあて", "てあみ", "ていおん", "ていか", "ていき", "ていけい", "ていこく", "ていさつ", "ていし", "ていせい", "ていたい", "ていど", "ていねい", "ていひょう", "ていへん", "ていぼう", "てうち", "ておくれ", "てきとう", "てくび", "でこぼこ", "てさぎょう", "てさげ", "てすり", "てそう", "てちがい", "てちょう", "てつがく", "てつづき", "でっぱ", "てつぼう", "てつや", "でぬかえ", "てぬき", "てぬぐい", "てのひら", "てはい", "てぶくろ", "てふだ", "てほどき", "てほん", "てまえ", "てまきずし", "てみじか", "てみやげ", "てらす", "てれび", "てわけ", "てわたし", "でんあつ", "てんいん", "てんかい", "てんき", "てんぐ", "てんけん", "てんごく", "てんさい", "てんし", "てんすう", "でんち", "てんてき", "てんとう", "てんない", "てんぷら", "てんぼうだい", "てんめつ", "てんらんかい", "でんりょく", "でんわ", "どあい", "といれ", "どうかん", "とうきゅう", "どうぐ", "とうし", "とうむぎ", "とおい", "とおか", "とおく", "とおす", "とおる", "とかい", "とかす", "ときおり", "ときどき", "とくい", "とくしゅう", "とくてん", "とくに", "とくべつ", "とけい", "とける", "とこや", "とさか", "としょかん", "とそう", "とたん", "とちゅう", "とっきゅう", "とっくん", "とつぜん", "とつにゅう", "とどける", "ととのえる", "とない", "となえる", "となり", "とのさま", "とばす", "どぶがわ", "とほう", "とまる", "とめる", "ともだち", "ともる", "どようび", "とらえる", "とんかつ", "どんぶり", "ないかく", "ないこう", "ないしょ", "ないす", "ないせん", "ないそう", "なおす", "ながい", "なくす", "なげる", "なこうど", "なさけ", "なたでここ", "なっとう", "なつやすみ", "ななおし", "なにごと", "なにもの", "なにわ", "なのか", "なふだ", "なまいき", "なまえ", "なまみ", "なみだ", "なめらか", "なめる", "なやむ", "ならう", "ならび", "ならぶ", "なれる", "なわとび", "なわばり", "にあう", "にいがた", "にうけ", "におい", "にかい", "にがて", "にきび", "にくしみ", "にくまん", "にげる", "にさんかたんそ", "にしき", "にせもの", "にちじょう", "にちようび", "にっか", "にっき", "にっけい", "にっこう", "にっさん", "にっしょく", "にっすう", "にっせき", "にってい", "になう", "にほん", "にまめ", "にもつ", "にやり", "にゅういん", "にりんしゃ", "にわとり", "にんい", "にんか", "にんき", "にんげん", "にんしき", "にんずう", "にんそう", "にんたい", "にんち", "にんてい", "にんにく", "にんぷ", "にんまり", "にんむ", "にんめい", "にんよう", "ぬいくぎ", "ぬかす", "ぬぐいとる", "ぬぐう", "ぬくもり", "ぬすむ", "ぬまえび", "ぬめり", "ぬらす", "ぬんちゃく", "ねあげ", "ねいき", "ねいる", "ねいろ", "ねぐせ", "ねくたい", "ねくら", "ねこぜ", "ねこむ", "ねさげ", "ねすごす", "ねそべる", "ねだん", "ねつい", "ねっしん", "ねつぞう", "ねったいぎょ", "ねぶそく", "ねふだ", "ねぼう", "ねほりはほり", "ねまき", "ねまわし", "ねみみ", "ねむい", "ねむたい", "ねもと", "ねらう", "ねわざ", "ねんいり", "ねんおし", "ねんかん", "ねんきん", "ねんぐ", "ねんざ", "ねんし", "ねんちゃく", "ねんど", "ねんぴ", "ねんぶつ", "ねんまつ", "ねんりょう", "ねんれい", "のいず", "のおづま", "のがす", "のきなみ", "のこぎり", "のこす", "のこる", "のせる", "のぞく", "のぞむ", "のたまう", "のちほど", "のっく", "のばす", "のはら", "のべる", "のぼる", "のみもの", "のやま", "のらいぬ", "のらねこ", "のりもの", "のりゆき", "のれん", "のんき", "ばあい", "はあく", "ばあさん", "ばいか", "ばいく", "はいけん", "はいご", "はいしん", "はいすい", "はいせん", "はいそう", "はいち", "ばいばい", "はいれつ", "はえる", "はおる", "はかい", "ばかり", "はかる", "はくしゅ", "はけん", "はこぶ", "はさみ", "はさん", "はしご", "ばしょ", "はしる", "はせる", "ぱそこん", "はそん", "はたん", "はちみつ", "はつおん", "はっかく", "はづき", "はっきり", "はっくつ", "はっけん", "はっこう", "はっさん", "はっしん", "はったつ", "はっちゅう", "はってん", "はっぴょう", "はっぽう", "はなす", "はなび", "はにかむ", "はぶらし", "はみがき", "はむかう", "はめつ", "はやい", "はやし", "はらう", "はろうぃん", "はわい", "はんい", "はんえい", "はんおん", "はんかく", "はんきょう", "ばんぐみ", "はんこ", "はんしゃ", "はんすう", "はんだん", "ぱんち", "ぱんつ", "はんてい", "はんとし", "はんのう", "はんぱ", "はんぶん", "はんぺん", "はんぼうき", "はんめい", "はんらん", "はんろん", "ひいき", "ひうん", "ひえる", "ひかく", "ひかり", "ひかる", "ひかん", "ひくい", "ひけつ", "ひこうき", "ひこく", "ひさい", "ひさしぶり", "ひさん", "びじゅつかん", "ひしょ", "ひそか", "ひそむ", "ひたむき", "ひだり", "ひたる", "ひつぎ", "ひっこし", "ひっし", "ひつじゅひん", "ひっす", "ひつぜん", "ぴったり", "ぴっちり", "ひつよう", "ひてい", "ひとごみ", "ひなまつり", "ひなん", "ひねる", "ひはん", "ひびく", "ひひょう", "ひほう", "ひまわり", "ひまん", "ひみつ", "ひめい", "ひめじし", "ひやけ", "ひやす", "ひよう", "びょうき", "ひらがな", "ひらく", "ひりつ", "ひりょう", "ひるま", "ひるやすみ", "ひれい", "ひろい", "ひろう", "ひろき", "ひろゆき", "ひんかく", "ひんけつ", "ひんこん", "ひんしゅ", "ひんそう", "ぴんち", "ひんぱん", "びんぼう", "ふあん", "ふいうち", "ふうけい", "ふうせん", "ぷうたろう", "ふうとう", "ふうふ", "ふえる", "ふおん", "ふかい", "ふきん", "ふくざつ", "ふくぶくろ", "ふこう", "ふさい", "ふしぎ", "ふじみ", "ふすま", "ふせい", "ふせぐ", "ふそく", "ぶたにく", "ふたん", "ふちょう", "ふつう", "ふつか", "ふっかつ", "ふっき", "ふっこく", "ぶどう", "ふとる", "ふとん", "ふのう", "ふはい", "ふひょう", "ふへん", "ふまん", "ふみん", "ふめつ", "ふめん", "ふよう", "ふりこ", "ふりる", "ふるい", "ふんいき", "ぶんがく", "ぶんぐ", "ふんしつ", "ぶんせき", "ふんそう", "ぶんぽう", "へいあん", "へいおん", "へいがい", "へいき", "へいげん", "へいこう", "へいさ", "へいしゃ", "へいせつ", "へいそ", "へいたく", "へいてん", "へいねつ", "へいわ", "へきが", "へこむ", "べにいろ", "べにしょうが", "へらす", "へんかん", "べんきょう", "べんごし", "へんさい", "へんたい", "べんり", "ほあん", "ほいく", "ぼうぎょ", "ほうこく", "ほうそう", "ほうほう", "ほうもん", "ほうりつ", "ほえる", "ほおん", "ほかん", "ほきょう", "ぼきん", "ほくろ", "ほけつ", "ほけん", "ほこう", "ほこる", "ほしい", "ほしつ", "ほしゅ", "ほしょう", "ほせい", "ほそい", "ほそく", "ほたて", "ほたる", "ぽちぶくろ", "ほっきょく", "ほっさ", "ほったん", "ほとんど", "ほめる", "ほんい", "ほんき", "ほんけ", "ほんしつ", "ほんやく", "まいにち", "まかい", "まかせる", "まがる", "まける", "まこと", "まさつ", "まじめ", "ますく", "まぜる", "まつり", "まとめ", "まなぶ", "まぬけ", "まねく", "まほう", "まもる", "まゆげ", "まよう", "まろやか", "まわす", "まわり", "まわる", "まんが", "まんきつ", "まんぞく", "まんなか", "みいら", "みうち", "みえる", "みがく", "みかた", "みかん", "みけん", "みこん", "みじかい", "みすい", "みすえる", "みせる", "みっか", "みつかる", "みつける", "みてい", "みとめる", "みなと", "みなみかさい", "みねらる", "みのう", "みのがす", "みほん", "みもと", "みやげ", "みらい", "みりょく", "みわく", "みんか", "みんぞく", "むいか", "むえき", "むえん", "むかい", "むかう", "むかえ", "むかし", "むぎちゃ", "むける", "むげん", "むさぼる", "むしあつい", "むしば", "むじゅん", "むしろ", "むすう", "むすこ", "むすぶ", "むすめ", "むせる", "むせん", "むちゅう", "むなしい", "むのう", "むやみ", "むよう", "むらさき", "むりょう", "むろん", "めいあん", "めいうん", "めいえん", "めいかく", "めいきょく", "めいさい", "めいし", "めいそう", "めいぶつ", "めいれい", "めいわく", "めぐまれる", "めざす", "めした", "めずらしい", "めだつ", "めまい", "めやす", "めんきょ", "めんせき", "めんどう", "もうしあげる", "もうどうけん", "もえる", "もくし", "もくてき", "もくようび", "もちろん", "もどる", "もらう", "もんく", "もんだい", "やおや", "やける", "やさい", "やさしい", "やすい", "やすたろう", "やすみ", "やせる", "やそう", "やたい", "やちん", "やっと", "やっぱり", "やぶる", "やめる", "ややこしい", "やよい", "やわらかい", "ゆうき", "ゆうびんきょく", "ゆうべ", "ゆうめい", "ゆけつ", "ゆしゅつ", "ゆせん", "ゆそう", "ゆたか", "ゆちゃく", "ゆでる", "ゆにゅう", "ゆびわ", "ゆらい", "ゆれる", "ようい", "ようか", "ようきゅう", "ようじ", "ようす", "ようちえん", "よかぜ", "よかん", "よきん", "よくせい", "よくぼう", "よけい", "よごれる", "よさん", "よしゅう", "よそう", "よそく", "よっか", "よてい", "よどがわく", "よねつ", "よやく", "よゆう", "よろこぶ", "よろしい", "らいう", "らくがき", "らくご", "らくさつ", "らくだ", "らしんばん", "らせん", "らぞく", "らたい", "らっか", "られつ", "りえき", "りかい", "りきさく", "りきせつ", "りくぐん", "りくつ", "りけん", "りこう", "りせい", "りそう", "りそく", "りてん", "りねん", "りゆう", "りゅうがく", "りよう", "りょうり", "りょかん", "りょくちゃ", "りょこう", "りりく", "りれき", "りろん", "りんご", "るいけい", "るいさい", "るいじ", "るいせき", "るすばん", "るりがわら", "れいかん", "れいぎ", "れいせい", "れいぞうこ", "れいとう", "れいぼう", "れきし", "れきだい", "れんあい", "れんけい", "れんこん", "れんさい", "れんしゅう", "れんぞく", "れんらく", "ろうか", "ろうご", "ろうじん", "ろうそく", "ろくが", "ろこつ", "ろじうら", "ろしゅつ", "ろせん", "ろてん", "ろめん", "ろれつ", "ろんぎ", "ろんぱ", "ろんぶん", "ろんり", "わかす", "わかめ", "わかやま", "わかれる", "わしつ", "わじまし", "わすれもの", "わらう", "われる" }; }
package Java; import java.util.Scanner; public class PrimeNumber { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a Number : "); int num = sc.nextInt(); int flag =1; for(int i=2; i<num; i++) { int rem = num%i; if(rem==1) flag = 0; return; } if(flag==1) { System.out.println(num+"is a PN"); } else System.out.println(num+"is not a PN"); } }
package com.springinaction.core.jdbc; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring-jdbc.xml") public class JdbcSpitterDAOTest { @Autowired private SpitterDAO spitterDAO; @Test public void spitterShouldBeInserted() { Spitter spitter = new Spitter(); spitter.setUsername("zhouqing8826"); spitter.setPassword("123456"); spitter.setFullname("周卿"); spitterDAO.addSpitter(spitter); } @Test public void selectSpitterById() { Spitter spitter = spitterDAO.getSpitterById(1L); System.out.println(spitter.getFullname()); } }
// Sun Certified Java Programmer // Chapter 7, P627_1 // Generics and Collections public class AnimalHolder<T extends Animal> { // use "T" instead // of "?" T animal; public static void main(String[] args) { AnimalHolder<Dog> dogHolder = new AnimalHolder<Dog>(); // OK AnimalHolder<Integer> x = new AnimalHolder<Integer>(); // NO! } }
import java.util.Scanner; public class exer10 { public static void main(String[] args) { Scanner input = new Scanner(System.in); float calF = 1; float expF = 0; System.out.println("Digite a base:"); float baseF = input.nextFloat(); System.out.println("Digite o expoente:"); expF = input.nextFloat(); int i = 1; while(i <= expF) { calF = calF * baseF; i++; } System.out.println(baseF + " ^ " + expF + " = " +calF); input.close(); } }
package com.fleet.online.controller; import com.fleet.online.json.R; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @RestController @RequestMapping public class LoginController { /** * 登陆 * * @param name 账户 * @param pwd 密码 */ @GetMapping("/login") public R login(@RequestParam("name") String name, @RequestParam("pwd") String pwd, HttpServletRequest request) { HttpSession session = request.getSession(); session.removeAttribute("name"); session.setAttribute("name", name); return R.ok(); } @RequestMapping("/session") public String session(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session != null) { System.out.println(session.getMaxInactiveInterval()); return (String) session.getAttribute("name"); } return ""; } }
package com.fh.controller; import com.fh.entity.po.Shop_Type; import com.fh.entity.vo.ResultData; import com.fh.service.Shop_Type_Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.yaml.snakeyaml.events.Event; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author ShaoQuanC * @create 2021-01-12 下午 17:03 */ @RestController @CrossOrigin @RequestMapping("api/type/") public class Shop_Type_Controller { @Autowired private Shop_Type_Service shopTypeService; /* 1.查询所有的分类数据据 路径:http://localhost:8080/api/type/getData 请求方式:get请求 参数: 返回值:{"code":200,"message":"提示",data:[{*}]}*/ @GetMapping("getData") public ResultData getData(){ List<Shop_Type> types = shopTypeService.queryTypeData(); return ResultData.success(types); } /* 2 查询指定pid的数据 路径:http://localhost:8080/api/type/getDataByPid 请求方式:get请求 参数:Pid 返回值:{"code":200,"message":"提示",data:[{*}]}*/ @PostMapping("getDataByPid") public ResultData getDataByPid(Integer pid){ Map rs = shopTypeService.queryTypeDataByPid(pid); return ResultData.success(rs); } /* 新增分类 路径:http://localhost:8080/api/type/add 请求方式: post请求 参数:pid,name 返回值: {code:"",message:"",data:新增的id}*/ @PostMapping("add") public ResultData addType(Shop_Type shopType){ shopTypeService.addType(shopType); Integer id = shopType.getId(); Map m = new HashMap(); m.put("id",id); return ResultData.success(m); } /* 路径:http://localhost:8080/api/type/updateTypeDataById 请求方式: post请求 参数:id (必传) pid name isDel 返回值: {code:"",message:""}*/ @PostMapping("queryTypeDataById") public ResultData queryTypeDataById(Integer id){ Shop_Type shopType = shopTypeService.queryTypeDataById(id); return ResultData.success(shopType); } /* 修改 路径:http://localhost:8080/api/type/update 请求方式: post请求 参数:id (必传) pid name isDel 返回值: {code:"",message:""}*/ @PostMapping("update") public ResultData updateType(Shop_Type shopType){ Date date = new Date(); shopType.setUpdateDate(date); shopTypeService.updateType(shopType); return ResultData.success(null); } /* 类型的逻辑删除 路径:http://localhost:8080/api/type/del 请求方式: delete请求 参数:id (必传) 返回值: {code:"",message:""}*/ @DeleteMapping("del") public ResultData deleteTypeByIsDel(Integer id){ shopTypeService.deleteTypeByIsDel(id); return ResultData.success(null); } }
//Essentially the main class of the project, and is what can be referred to to initiate it public class Calculator { public static void main(String[] args) { new CalculatorView(); } }
package day5; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JFrame; public class Started extends JFrame { public Started(){ JFrame frame = new JFrame("·É»ú´óÕ½"); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); MyPanel panel = new MyPanel(dim); Thread thread = new Thread(panel); thread.start(); frame.add(panel); frame.setSize(dim); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setResizable(false); } }
package com.yboweb.bestmovie; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.yboweb.bestmovie.androidnavigationdrawerexample.R; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by test on 25/05/16. */ class CustomPagerAdapter extends PagerAdapter { Context mContext; private float proportion = 1; private ArrayList<ImageItem> mGridData = new ArrayList<>(); LayoutInflater mLayoutInflater; public CustomPagerAdapter(Context context) { mContext = context; mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return mGridData.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == ((LinearLayout) object); } @Override public Object instantiateItem(ViewGroup container, final int position) { final String id = mGridData.get(position).getId(); View itemView = null; String imageUrl = mGridData.get(position).getImage(); final String actorsJson = mGridData.get(position).getActorsJaon(); int type = mGridData.get(position).getType(); ImageView imageView = null; Log.d("CustomPage", "Type:" + type + " Actorsjson:" + actorsJson + " id:" + id); if (type == ImageItem.ACTOR_DETAIL_MOVIE_ITEM) { if(id != null) { Log.d("CustomPage", "MYID Type:" + type + " Id:" + id + " Title:" + mGridData.get(position).gettTitle()); itemView = mLayoutInflater.inflate(R.layout.actor_movie_layout, container, false); TextView title = (TextView) itemView.findViewById(R.id.my_item_title); title.setText(mGridData.get(position).gettTitle()); imageView = (ImageView) itemView.findViewById(R.id.my_item_image); Picasso.with(mContext).load(imageUrl).into(imageView); imageView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(mContext, ScrollingActivity.class); Bundle args = new Bundle(); args.putString("id", mGridData.get(position).getId()); intent.putExtras(args); mContext.startActivity(intent); } }); } } else if (type == ImageItem.ACTOR_ITEM) { itemView = mLayoutInflater.inflate(R.layout.actor_name, container, false); imageView = (ImageView) itemView.findViewById(R.id.my_actor_item_image); TextView title = (TextView) itemView.findViewById(R.id.my_actor_item_title); title.setText(mGridData.get(position).gettTitle()); Picasso.with(mContext).load(imageUrl).into(imageView); title.setText(mGridData.get(position).gettTitle()); imageView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Bundle mBundle = new Bundle(); mBundle.putString("combined", actorsJson); Intent mIntent = new Intent(mContext, ActorScrollingActivity.class); mIntent.putExtras(mBundle); mContext.startActivity(mIntent); } }); } else if (type == ImageItem.VIDEO_ITEM) { final String key = mGridData.get(position).getVideoKey(); //Youtube comment if (key != null) { Log.d("CustomPage", "Youtube: " + "Type:" + type); itemView = mLayoutInflater.inflate(R.layout.image_item_layout, container, false); final ImageView imageButton = (ImageView) itemView.findViewById(R.id.play_button); imageButton.setVisibility(View.VISIBLE); // We want that the click will take place in any place we touch FrameLayout frame = (FrameLayout) itemView.findViewById(R.id.touch_link); frame.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(mContext, PlayVideo.class); intent.setPackage(mContext.getPackageName()); Bundle args = new Bundle(); args.putString("YOUTUBE_PARAM", key); intent.putExtras(args); mContext.startActivity(intent); } }); imageView = (ImageView) itemView.findViewById(R.id.my_item_image); Picasso.with(mContext).load(imageUrl).into(imageView); } } else if (type == ImageItem.GALLERY_ITEM) { final String imageGalleryNames = mGridData.get(position).getimageGalleryNames(); if (imageGalleryNames != null) { itemView = mLayoutInflater.inflate(R.layout.image_item_layout, container, false); imageView = (ImageView) itemView.findViewById(R.id.my_item_image); imageView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(mContext, GridViewActivity.class); intent.setPackage(mContext.getPackageName()); Bundle args = new Bundle(); args.putString("images", imageGalleryNames); intent.putExtras(args); mContext.startActivity(intent); } }); } Picasso.with(mContext).load(imageUrl).into(imageView); } else { Log.d("CustomPage", "else"); itemView = mLayoutInflater.inflate(R.layout.image_item_layout, container, false); imageView = (ImageView) itemView.findViewById(R.id.my_item_image); mGridData.get(position).setImageView(imageView); Picasso.with(mContext).load(imageUrl).into(imageView); } container.addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((LinearLayout) object); } @Override public float getPageWidth(int position) { return(proportion); } public void set_propop(float value) { proportion = value; } void addItem(ImageItem item) { mGridData.add(item); } public ArrayList<ImageItem> getData() { return(mGridData); } public void setGridData(ArrayList<ImageItem> mGridData) { this.mGridData = mGridData; notifyDataSetChanged(); } }
package com.example.demo.java8; public class IntroMethodReference { public static void main(String[] args) { IntroMethodReference reference = new IntroMethodReference(); reference.myDisplayMethod(); MethodRef ref = reference::myDisplayMethod;; ref.display(); } void myDisplayMethod(){ System.out.println("My Display Method"); } } interface MethodRef{ void display(); }
package application; import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.shape.Circle; import javafx.scene.shape.Line; public class Main extends Application { @Override public void start(Stage primaryStage) { BorderPane root = new BorderPane(); Scene scene = new Scene(root,500,500); Line y1=new Line(10,10,10,490); Line x1=new Line(10,250,490,250); root.getChildren().addAll(x1,y1); //Coseno double PI=3.14159265; double x; for(int y=240;y<=260;y++) { x=Math.cos(y-250)+PI*3; Circle circulo=new Circle(x,y,5); root.getChildren().addAll(circulo); } primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
package game.app.helper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Service; import game.app.dtos.request.ShopDto; import game.app.entities.Shop; @Service public class ShopHelper { @Autowired private ConversionService converter; public Shop convertShopRequestToShop(ShopDto shopRequest) { Shop shop = converter.convert(shopRequest, Shop.class); return shop; } }
package test.abcd.pierwszaAplikacja.modelcookie; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Scope(BeanDefinition.SCOPE_PROTOTYPE) @Component public class Ciastka { private boolean ugryzione = true; public boolean ugryz() { if (ugryzione) { return false; } System.out.println("Chummm!"); ugryzione = true; return true; } }
package com.mysql.cj.protocol.a.result; import com.mysql.cj.protocol.ColumnDefinition; import com.mysql.cj.protocol.Resultset; import com.mysql.cj.protocol.ResultsetRows; import com.mysql.cj.result.DefaultColumnDefinition; import com.mysql.cj.result.Row; import java.util.HashMap; public class NativeResultset implements Resultset { protected ColumnDefinition columnDefinition; protected ResultsetRows rowData; protected Resultset nextResultset = null; protected int resultId; protected long updateCount; protected long updateId = -1L; protected String serverInfo = null; protected Row thisRow = null; public NativeResultset() {} public NativeResultset(OkPacket ok) { this.updateCount = ok.getUpdateCount(); this.updateId = ok.getUpdateID(); this.serverInfo = ok.getInfo(); this.columnDefinition = (ColumnDefinition)new DefaultColumnDefinition(new com.mysql.cj.result.Field[0]); } public NativeResultset(ResultsetRows rows) { this.columnDefinition = rows.getMetadata(); this.rowData = rows; this.updateCount = this.rowData.size(); if (this.rowData.size() > 0) { if (this.updateCount == 1L && this.thisRow == null) { this.rowData.close(); this.updateCount = -1L; } } else { this.thisRow = null; } } public void setColumnDefinition(ColumnDefinition metadata) { this.columnDefinition = metadata; } public ColumnDefinition getColumnDefinition() { return this.columnDefinition; } public boolean hasRows() { return (this.rowData != null); } public int getResultId() { return this.resultId; } public void initRowsWithMetadata() { this.rowData.setMetadata(this.columnDefinition); this.columnDefinition.setColumnToIndexCache(new HashMap<>()); } public synchronized void setNextResultset(Resultset nextResultset) { this.nextResultset = nextResultset; } public synchronized Resultset getNextResultset() { return this.nextResultset; } public synchronized void clearNextResultset() { this.nextResultset = null; } public long getUpdateCount() { return this.updateCount; } public long getUpdateID() { return this.updateId; } public String getServerInfo() { return this.serverInfo; } public ResultsetRows getRows() { return this.rowData; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\a\result\NativeResultset.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package ec.com.yacare.y4all.lib.sqllite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import ec.com.yacare.y4all.lib.dto.Mensaje; public class MensajeDataSource { // Database fields private SQLiteDatabase database; private MySQLiteHelper dbHelper; private String[] allColumns = { MySQLiteHelper.COLUMN_MENSAJE_ID, MySQLiteHelper.COLUMN_DISP_ID, MySQLiteHelper.COLUMN_DISP_MENSAJE, MySQLiteHelper.COLUMN_DISP_FECHA, MySQLiteHelper.COLUMN_DISP_HORA , MySQLiteHelper.COLUMN_DISP_ESTADO, MySQLiteHelper.COLUMN_DISP_TIPO, MySQLiteHelper.COLUMN_DISP_DIRECCION}; public MensajeDataSource(Context context) { dbHelper = new MySQLiteHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public Mensaje createMensajeNew(Mensaje mensaje) { ContentValues values = new ContentValues(); values.put(MySQLiteHelper.COLUMN_MENSAJE_ID, mensaje.getId()); values.put(MySQLiteHelper.COLUMN_DISP_ID, mensaje.getIdDispositivo()); values.put( MySQLiteHelper.COLUMN_DISP_MENSAJE, mensaje.getMensaje()); values.put(MySQLiteHelper.COLUMN_DISP_FECHA, mensaje.getFecha()); values.put(MySQLiteHelper.COLUMN_DISP_HORA , mensaje.getHora()); values.put(MySQLiteHelper.COLUMN_DISP_ESTADO, mensaje.getEstado()); values.put(MySQLiteHelper.COLUMN_DISP_TIPO, mensaje.getTipo()); values.put(MySQLiteHelper.COLUMN_DISP_DIRECCION, mensaje.getDireccion()); database.insert(MySQLiteHelper.TABLA_MENSAJE, null, values); Cursor cursor = database.query(MySQLiteHelper.TABLA_MENSAJE, allColumns, MySQLiteHelper.COLUMN_MENSAJE_ID + " = '" + mensaje.getId() + "'" , null, null, null, null); cursor.moveToFirst(); Mensaje mensajeNew = cursorToMensaje(cursor); cursor.close(); return mensajeNew; } public void deleteMensaje(String idMensaje) { // System.out.println("deleteMensajeOffLineNew with id: " + idMensaje); database.delete(MySQLiteHelper.TABLA_MENSAJE, MySQLiteHelper.COLUMN_MENSAJE_ID + " = '" + idMensaje + "'", null); } public void deleteAllMensaje() { database.delete(MySQLiteHelper.TABLA_MENSAJE, null, null); } public void updateMensaje(Mensaje mensaje) { // System.out.println("updateMensajeOffLine with id: " + mensaje.getId()); ContentValues values = new ContentValues(); values.put(MySQLiteHelper.COLUMN_DISP_ID, mensaje.getIdDispositivo()); values.put( MySQLiteHelper.COLUMN_DISP_MENSAJE, mensaje.getMensaje()); values.put(MySQLiteHelper.COLUMN_DISP_FECHA, mensaje.getFecha()); values.put(MySQLiteHelper.COLUMN_DISP_HORA , mensaje.getHora()); values.put(MySQLiteHelper.COLUMN_DISP_ESTADO, mensaje.getEstado()); values.put(MySQLiteHelper.COLUMN_DISP_TIPO, mensaje.getTipo()); values.put(MySQLiteHelper.COLUMN_DISP_DIRECCION, mensaje.getDireccion()); database.update(MySQLiteHelper.TABLA_MENSAJE, values, MySQLiteHelper.COLUMN_MENSAJE_ID + " = '" + mensaje.getId() + "'", null); } public ArrayList<Mensaje> getMensajeByDispositivo(String idDispositivo) { ArrayList<Mensaje> mensajes = new ArrayList<Mensaje>(); Cursor cursor = database.query(MySQLiteHelper.TABLA_MENSAJE, allColumns, MySQLiteHelper.COLUMN_DISP_ID + " = '" + idDispositivo + "'" , null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Mensaje mensaje = cursorToMensaje(cursor); mensajes.add(mensaje); cursor.moveToNext(); } cursor.close(); return mensajes; } private Mensaje cursorToMensaje(Cursor cursor) { Mensaje mensaje = new Mensaje(); mensaje.setId(cursor.getString(0)); mensaje.setIdDispositivo(cursor.getString(1)); mensaje.setMensaje(cursor.getString(2)); mensaje.setFecha(cursor.getString(3)); mensaje.setHora(cursor.getString(4)); mensaje.setEstado(cursor.getString(5)); mensaje.setTipo(cursor.getString(6)); mensaje.setDireccion(cursor.getString(7)); return mensaje; } }
package com.diozero.sampleapps.mfrc522; /*- * #%L * Organisation: diozero * Project: diozero - Sample applications * Filename: ReadAndWrite.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * 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. * #L% */ import org.tinylog.Logger; import com.diozero.devices.MFRC522; import com.diozero.devices.MFRC522.StatusCode; import com.diozero.util.Hex; import com.diozero.util.SleepUtil; public class ReadAndWrite { public static void main(String[] args) { if (args.length < 4) { Logger.error("Usage: {} <spi-controller> <chip-select> <rst-gpio> <auth-key-hex>", ReadAndWrite.class.getName()); System.exit(1); } int index = 0; int controller = Integer.parseInt(args[index++]); int chip_select = Integer.parseInt(args[index++]); int reset_pin = Integer.parseInt(args[index++]); byte[] auth_key = Hex.decodeHex(args[index++]); MFRC522.UID uid = null; try (MFRC522 rfid = new MFRC522(controller, chip_select, reset_pin)) { Logger.info("Scanning for RFID tags..."); while (uid == null) { SleepUtil.sleepSeconds(1); if (rfid.isNewCardPresent()) { uid = rfid.readCardSerial(); } } Logger.info("Found card with UID 0x{}, type: {}", Hex.encodeHexString(uid.getUidBytes()), uid.getType()); if (uid.getType() != MFRC522.PiccType.MIFARE_MINI && uid.getType() != MFRC522.PiccType.MIFARE_1K && uid.getType() != MFRC522.PiccType.MIFARE_4K) { Logger.error("This example only works with Mifare Classic cards"); return; } readAndWrite(rfid, uid, auth_key, false); // Halt PICC rfid.haltA(); // Stop encryption on PCD rfid.stopCrypto1(); } } private static void readAndWrite(MFRC522 rfid, MFRC522.UID uid, byte[] authKey, boolean write) { // In this sample we use the second sector, that is: sector #1, // covering block #4 up to and including block #7 byte blocks_per_sector = 4; byte sector = 15; byte blockAddr = (byte) (sector * blocks_per_sector); byte trailerBlock = (byte) (blockAddr + (blocks_per_sector - 1)); // Authenticate using key A Logger.info("Authenticating using key A..."); StatusCode status = rfid.authenticate(true, trailerBlock, authKey, uid); if (status != StatusCode.OK) { Logger.error("PCD_Authenticate() failed: {}", status); return; } // Show the whole sector as it currently is Logger.info("Current data in sector:"); rfid.dumpMifareClassicSectorToConsole(uid, authKey, sector); // Read data from the block Logger.info("Reading data from block 0x{} ...", Integer.toHexString(blockAddr)); byte[] buffer = rfid.mifareRead(blockAddr); if (buffer == null) { Logger.error("MIFARE_Read() failed: buffer was null"); return; } Logger.info("Data in block 0x{} : 0x{}", Integer.toHexString(blockAddr), Hex.encodeHexString(buffer, 4)); // Authenticate using key B Logger.info("Authenticating again using key B..."); status = rfid.authenticate(false, trailerBlock, authKey, uid); if (status != StatusCode.OK) { Logger.error("PCD_Authenticate() failed: {}", status); return; } if (write) { byte[] dataBlock = { 0x01, 0x02, 0x03, 0x04, // 1, 2, 3, 4, 0x05, 0x06, 0x07, 0x08, // 5, 6, 7, 8, 0x08, 0x09, (byte) 0xff, 0x0b, // 9, 10, 255, 12, 0x0c, 0x0d, 0x0e, 0x0f // 13, 14, 15, 16 }; // Write data to the block Logger.info("Writing data into block 0x{} : 0x{} ...", Integer.toHexString(blockAddr), Hex.encodeHexString(dataBlock, 4)); status = rfid.mifareWrite(blockAddr, dataBlock); if (status != StatusCode.OK) { Logger.error("MIFARE_Write() failed: {}", status); return; } // Read data from the block (again, should now be what we have written) Logger.info("Reading data from block 0x{} ...", Integer.toHexString(blockAddr)); buffer = rfid.mifareRead(blockAddr); if (buffer == null) { Logger.error("MIFARE_Read() failed: buffer was null"); return; } Logger.info("Data in block 0x{}: 0x{}", Integer.toHexString(blockAddr), Hex.encodeHexString(buffer, 4)); // Check that data in block is what we have written // by counting the number of bytes that are equal Logger.info("Checking result..."); byte count = 0; for (int i=0; i<16; i++) { // Compare buffer (= what we've read) with dataBlock (= what we've written) if (buffer[i] == dataBlock[i]) { count++; } } Logger.info("Number of bytes that match = {}", Integer.valueOf(count)); if (count == 16) { Logger.info("Success :-)"); } else { Logger.info("Failure, no match :-("); Logger.info(" perhaps the write didn't work properly..."); } // Dump the sector data Logger.info("Current data in sector:"); rfid.dumpMifareClassicSectorToConsole(uid, authKey, sector); } } }
package Lab07.Zad1; import java.util.Scanner; public class Keyboard { public int number; public int[] Get(int[] array){ System.out.println("Enter values: "); Scanner sc = new Scanner(System.in); for(int i=0;i<array.length;i++) { System.out.println("Add value"); int val = sc.nextInt(); array[i] = val; } System.out.println("Numbers added"); return array; } }
package edu.umn.cs.recsys.svd; import it.unimi.dsi.fastutil.longs.*; import org.apache.commons.math3.linear.*; import org.lenskit.api.ItemScorer; import org.lenskit.baseline.BaselineScorer; import org.lenskit.inject.Transient; import org.lenskit.util.io.ObjectStream; import org.lenskit.data.dao.ItemDAO; import org.lenskit.data.dao.UserDAO; import org.lenskit.data.dao.UserEventDAO; import org.lenskit.data.events.Event; import org.lenskit.data.ratings.Rating; import org.lenskit.data.ratings.Ratings; import org.lenskit.data.history.UserHistory; import org.grouplens.lenskit.vectors.MutableSparseVector; import org.grouplens.lenskit.vectors.VectorEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Provider; import java.util.Map; /** * Model builder that computes the SVD model. */ public class SVDModelBuilder implements Provider<SVDModel> { private static final Logger logger = LoggerFactory.getLogger(SVDModelBuilder.class); private final UserEventDAO userEventDAO; private final UserDAO userDAO; private final ItemDAO itemDAO; private final ItemScorer baselineScorer; private final int featureCount; /** * Construct the model builder. * @param uedao The user event DAO. * @param udao The user DAO. * @param idao The item DAO. * @param baseline The baseline scorer (this will be used to compute means). * @param nfeatures The number of latent features to train. */ @Inject public SVDModelBuilder(@Transient UserEventDAO uedao, @Transient UserDAO udao, @Transient ItemDAO idao, @Transient @BaselineScorer ItemScorer baseline, @LatentFeatureCount int nfeatures) { logger.debug("user DAO: {}", udao); userEventDAO = uedao; userDAO = udao; itemDAO = idao; baselineScorer = baseline; featureCount = nfeatures; } /** * Build the SVD model. * * @return A singular value decomposition recommender model. */ @Override public SVDModel get() { // Create index mappings of user and item IDs. // You can use these to find row and columns in the matrix based on user/item IDs. Long2LongMap userMapping = new Long2LongOpenHashMap(); int i = 0; for (Long userId : userDAO.getUserIds()) { userMapping.put(userId, i); i++; } Long2LongMap itemMapping = new Long2LongOpenHashMap(); int j = 0; for (Long itemId : itemDAO.getItemIds()) { itemMapping.put(itemId, j); j++; } // We have to do 2 things: // First, prepare a matrix containing the rating data. RealMatrix matrix = createRatingMatrix(userMapping, itemMapping); // Second, compute its factorization SingularValueDecomposition svd = new SingularValueDecomposition(matrix); // Set LatentFeatureCount to 0 to turn off truncation int numFeatures = featureCount; if (numFeatures == 0) { numFeatures = Math.min(itemDAO.getItemIds().size(), userDAO.getUserIds().size()); } // Third, truncate the decomposed matrix RealMatrix userMatrix = svd.getU().getSubMatrix(0, userMapping.size() - 1, 0, numFeatures - 1); RealMatrix itemMatrix = svd.getV().getSubMatrix(0, itemMapping.size() - 1, 0, numFeatures - 1); RealVector weights = new ArrayRealVector(svd.getSingularValues(), 0, numFeatures); return new SVDModel(userMapping, itemMapping, userMatrix, itemMatrix, weights); } /** * Build a rating residual matrix from the rating data. Each user's ratings are * normalized by subtracting a baseline score (usually a mean). * * @param userMapping The index mapping of user IDs to column numbers. * @param itemMapping The index mapping of item IDs to row numbers. * @return A matrix storing the <i>normalized</i> user ratings. */ private RealMatrix createRatingMatrix(Long2LongMap userMapping, Long2LongMap itemMapping) { final int nusers = userMapping.size(); final int nitems = itemMapping.size(); // Create a matrix with users on rows and items on columns logger.info("creating {} by {} rating matrix", nusers, nitems); RealMatrix matrix = MatrixUtils.createRealMatrix(nusers, nitems); // populate it with data ObjectStream<UserHistory<Event>> users = userEventDAO.streamEventsByUser(); try { for (UserHistory<Event> user: users) { int u = (int) userMapping.get(user.getUserId()); Long2DoubleMap ratings = new Long2DoubleOpenHashMap(Ratings.userRatingVector(user.filter(Rating.class))); Map<Long, Double> baselines = baselineScorer.score(user.getUserId(), ratings.keySet()); // Populate this user's row wiht their ratings, minus the baseline scores for (Map.Entry<Long, Double> e : ratings.entrySet()) { long item = e.getKey(); int i = (int)itemMapping.get(item); double rating = e.getValue() - baselines.get(item); matrix.setEntry(u, i, rating); } } } finally { users.close(); } return matrix; } }
package pe.gob.trabajo.repository.search; import pe.gob.trabajo.domain.Motcese; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the Motcese entity. */ public interface MotceseSearchRepository extends ElasticsearchRepository<Motcese, Long> { }
package com.microservice.githubApp; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; @RestController public class Controller { final private RestTemplate restTemplate; public Controller(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Value("${adress}") private String adress; @RequestMapping("/repositories/{owner}/{repository-name}") public OutData getData(@PathVariable(value = "owner") String name, @PathVariable(value = "repository-name") String repoName) { String urlString = adress + name + "/" + repoName; RepoData data = restTemplate.getForObject(urlString, RepoData.class); if (data == null) { throw new EmptyFieldException(); } return new OutData(data.getFullName(), data.getDescription(), data.getCloneUrl(), Integer.parseInt(data.getStargazersCount()), data.getCreatedAt()); } @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "You should correct name Owner of Repository") @ExceptionHandler(EmptyFieldException.class) private void emptyNameException() { } @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Wrong Repo or Wrong User name") @ExceptionHandler(WrongRepoOrUserException.class) public void handlerWrongUserException() { } }
package com.chilkens.timeset.dao; import com.chilkens.timeset.domain.PickJoin; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by hoody on 2017-08-02. */ @Repository public interface PickJoinRepository extends JpaRepository<PickJoin, Long> { List<PickJoin> findByTableId(Long tableId); }
package com.legalzoom.api.test.dto; /** * */ public class CreateProcessingStatusIdDTO implements DTO { private String processingStatusId; //pkProcessingStatus from ProcessingStatus private String processId; //pkProcess from Process public String getProcessingStatusId() { return processingStatusId; } public void setProcessingStatusId(String processingStatusId) { this.processingStatusId = processingStatusId; } public String getProcessId() { return processId; } public void setProcessId(String processId) { this.processId = processId; } }
package com.ml.coupon.service.util; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; @Component public class ListUtil<T> { public List<T> distinct(List<T> list) { if (list==null) { return null; } return list.stream().distinct().collect(Collectors.toList()); } }
package com.takshine.wxcrm.base.util; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Hashtable; import org.apache.log4j.Logger; import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; import org.apache.commons.net.ftp.FTPClient; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.takshine.wxcrm.controller.DcCrmOperatorController; /** * 二维码工具类 * @author dengbo * */ public class QRCodeUtil { protected static Logger logger = Logger .getLogger(QRCodeUtil.class.getName()); private static final String CHARSET = "utf-8"; private static final String FORMAT_NAME = "JPEG"; // 二维码尺寸 private static final int QRCODE_SIZE = 300; // LOGO宽度 private static final int WIDTH = 60; // LOGO高度 private static final int HEIGHT = 60; private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception { Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } if (imgPath == null || "".equals(imgPath)) { return image; } // 插入图片 if(StringUtils.isNotNullOrEmptyStr(imgPath)){ QRCodeUtil.insertImage(image, imgPath, needCompress); } return image; } /** * 插入LOGO * * @param source * 二维码图片 * @param imgPath * LOGO图片地址 * @param needCompress * 是否压缩 * @throws Exception */ private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception { //new一个URL对象 URL url = new URL(imgPath); //打开链接 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置请求方式为"GET" conn.setRequestMethod("GET"); //超时响应时间为5秒 conn.setConnectTimeout(5 * 1000); //通过输入流获取图片数据 InputStream is = conn.getInputStream(); Image src = ImageIO.read(is); // Image src = ImageIO.read(new File(imgPath)); int width = src.getWidth(null); int height = src.getHeight(null); if (needCompress) { // 压缩LOGO if (width > WIDTH) { width = WIDTH; } if (height > HEIGHT) { height = HEIGHT; } Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(image, 0, 0, null); // 绘制缩小后的图 g.dispose(); src = image; } // 插入LOGO Graphics2D graph = source.createGraphics(); int x = (QRCODE_SIZE - width) / 2; int y = (QRCODE_SIZE - height) / 2; graph.drawImage(src, x, y, width, height, null); Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6); graph.setStroke(new BasicStroke(3f)); graph.draw(shape); graph.dispose(); } /** * 生成二维码(内嵌LOGO) * * @param content * 内容 * @param imgPath * LOGO地址 * @param destPath * 存放目录 * @param needCompress * 是否压缩LOGO * @param loaPath * 本地存储路径 * @throws Exception */ public static String encode(String openId,String content, String imgPath, boolean needCompress,String loaPath) throws Exception { try{ BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress); String filename = openId+".jpeg"; File file = new File(loaPath+"/"+filename); logger.info(file); File parentFile = file.getParentFile(); logger.info(parentFile); if(!parentFile.isDirectory()){ parentFile.mkdirs(); } if(file.exists()){ file.delete(); file.createNewFile(); }else{ file.createNewFile(); } boolean flag = ImageIO.write(image, FORMAT_NAME, file); if(true==flag){ return filename; }else{ return "0"; } }catch(Exception ex){ logger.error("QRCodeUtil ---- encode --- error"+ex.toString()); return "0"; } // mkdirs(destPath); //直接存储到ftp服务器 // ByteArrayOutputStream bs =new ByteArrayOutputStream(); // ImageOutputStream imOut =ImageIO.createImageOutputStream(bs); // ImageIO.write(image, FORMAT_NAME, imOut); // InputStream is =new ByteArrayInputStream(bs.toByteArray()); // FTPUtil fu = new FTPUtil(); // FTPClient ftp = fu.getConnectionFTP(PropertiesUtil.getAppContext("file.service"),Integer.parseInt(PropertiesUtil.getAppContext("file.service.port")), PropertiesUtil.getAppContext("file.service.uid"), PropertiesUtil.getAppContext("file.service.pwd")); // if(fu.uploadPic(ftp, PropertiesUtil.getAppContext("file.service.path.qrcode"), filename, is)){ // fu.closeFTP(ftp); // return filename; // }else{ // fu.closeFTP(ftp); // return "0"; // } } /** * 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常) * @param destPath 存放目录 */ // public static void mkdirs(String destPath) { // File file =new File(destPath); // if (!file.exists() && !file.isDirectory()) { // file.mkdirs(); // } // } public static void main(String[] args) throws Exception { String logoPath = "d:/123.jpg"; String contents = "MECARD:N:MR ZHANG;" + "ADR:中国上海徐汇;" + "ORG:XXXX;" + "DIV:研发一部;" + "TIL:高级软件开发工程师;" + "TEL:138********;" + "EMAIL:ztyjr88@163.com;" + "URL:www.baidu.com;" + "NOTE:QQ :gomain@vip.qq.com;"; QRCodeUtil.encode("asdasd",contents,null,true,"d:/"); } }
package com.smartwerkz.bytecode.vm.methods; import com.smartwerkz.bytecode.primitives.JavaInteger; import com.smartwerkz.bytecode.primitives.JavaObjectReference; import com.smartwerkz.bytecode.vm.Frame; import com.smartwerkz.bytecode.vm.OperandStack; import com.smartwerkz.bytecode.vm.RuntimeDataArea; public class ThreadIsAliveMethod implements NativeMethod { @Override public void execute(RuntimeDataArea rda, Frame frame, OperandStack operandStack) { JavaObjectReference threadReference = (JavaObjectReference) frame.getLocalVariables().getLocalVariable(0); if (rda.getThreads().isAlive(threadReference)) { operandStack.push(new JavaInteger(1)); } else { operandStack.push(new JavaInteger(0)); } } }
package com.tencent.wecall.talkroom.model; import com.tencent.wecall.talkroom.model.g.a; import java.util.List; class g$19 implements Runnable { final /* synthetic */ g vyO; final /* synthetic */ List vyT; g$19(g gVar, List list) { this.vyO = gVar; this.vyT = list; } public final void run() { synchronized (this.vyO.cWy) { for (a em : this.vyO.cWy) { em.em(this.vyT); } } } }
/** * Theme support plugin for Enonic CMS 4.7.4 and newer * * @author Henady Zakalusky ( henady.zakalusky@gmail.com ) */ package com.enonic.cms.plugin.themes.modern; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.servlet.ServletOutputStream; class HookedOutputStream extends ServletOutputStream { private ByteArrayOutputStream outputStream; public HookedOutputStream( final ByteArrayOutputStream outputStream ) { this.outputStream = outputStream; } @Override public void write( final int b ) throws IOException { outputStream.write( b ); } @Override public void write( final byte[] b ) throws IOException { outputStream.write( b ); } @Override public void write( final byte[] b, final int off, final int len ) throws IOException { outputStream.write( b, off, len ); } }
package lab01.tdd; public interface SelectStrategyFactory { SelectStrategy createEvenStrategy(); SelectStrategy createMultipleOfStrategy(int divisor); SelectStrategy createEqualsStrategy(int value); }
package com.yfancy.web.boss.interceptor; import com.yfancy.common.base.Result; import com.yfancy.common.base.enums.SystemCodeMsgEnum; import com.yfancy.common.base.util.RewriteMsgUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Slf4j public class AuthInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { // log.info("【AuthInterceptor】【preHandle】,鉴权开始,判断鉴权是否通过"); // String noauth = httpServletRequest.getHeader("NOAUTH"); // if (noauth != null){ // log.info("【AuthInterceptor】【preHandle】,不需要鉴权,通过"); // return true; // } // // // log.info("【AuthInterceptor】【preHandle】,鉴权失败"); // RewriteMsgUtil.writeJsonMsg(httpServletResponse, Result.ERROR(SystemCodeMsgEnum.authError)); // return false; return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
package it.unical.asd.group6.computerSparePartsCompany.core.services; import it.unical.asd.group6.computerSparePartsCompany.data.dto.OrderRequestDTO; import it.unical.asd.group6.computerSparePartsCompany.data.entities.OrderRequest; import java.util.List; import java.util.Optional; public interface OrderRequestService { public List<OrderRequestDTO> getAllOrderRequests(); public OrderRequestDTO getOrderRequestById(Long id); Optional<OrderRequest> getOrderRequestEntityById(Long id); public OrderRequestDTO saveOrderRequest(OrderRequest orderRequest); List<OrderRequestDTO> getAllOrderRequestsForWarehouse(Long parseLong); }
package org.powellmakerspace.signonserver; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; import io.swagger.client.ApiException; import io.swagger.client.api.MemberControllerApi; import io.swagger.client.model.Member; public class jsonTest extends AppCompatActivity { ListView listView; Button btnFragmentTests; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_json_test); listView = (ListView) findViewById(R.id.listView); btnFragmentTests = (Button) findViewById(R.id.btnFragmentTests); ApiClient apiClient = new ApiClient(); apiClient.setBasePath("http://10.0.1.94:8080"); MemberControllerApi client = new MemberControllerApi(apiClient); try { client.getMembersUsingGETAsync(null, null, new ApiCallback<List<Member>>() { @Override public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) { } @Override public void onSuccess(List<Member> result, int statusCode, Map<String, List<String>> responseHeaders) { jsonAdapter JsonAdapter = new jsonAdapter(jsonTest.this, result); listView.setAdapter(JsonAdapter); } @Override public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { } @Override public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { } } ); } catch (ApiException e) { e.printStackTrace(); } btnFragmentTests.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Fragment Tests", Toast.LENGTH_SHORT).show(); Intent fragmentTestsIntent = new Intent(getApplicationContext(), FragmentCanvas.class); startActivity(fragmentTestsIntent); } }); } }
package org.bricolages.mys3dump; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Created by shimpei-kodama on 2016/02/29. */ class ResultSetSchema { private final List<ResultSetColumn> columns; private final int columnCount; private final List<Integer> columnTypes; private final List<String> columnNames; public ResultSetSchema(List<ResultSetColumn> columns) throws SQLException { this.columns = columns; this.columnCount = columns.size(); this.columnTypes = columns.stream().map(c -> c.type).collect(Collectors.toList()); this.columnNames = columns.stream().map(c -> c.name).collect(Collectors.toList()); } static public ResultSetSchema newInstance(ResultSetMetaData metadata) throws SQLException { List<ResultSetColumn> columns = new ArrayList<ResultSetColumn>(); for (int i = 0; i < metadata.getColumnCount(); i++) { int idx = 1 + i; ResultSetColumn c = new ResultSetColumn(metadata.getColumnName(idx), metadata.getColumnType(idx), metadata.getColumnTypeName(idx)); columns.add(c); } return new ResultSetSchema(columns); } public List<ResultSetColumn> getColumns() { return columns; } public int getColumnCount() { return columnCount; } public List<Integer> getColumnTypes() { return columnTypes; } public List<String> getColumnNames() { return columnNames; } }
/** * Date:2015年7月17日下午11:37:33 * Mail:zhaoqi19880624@163.com * Copyright (c) 2015 by ZhaoQi , All Rights Reserved . * */ package com.kellyqi.ttgl.service; import com.kellyqi.ttgl.model.Role; /** * Function: TODO ADD FUNCTION. <br/> * Date: 2015年7月17日 下午11:37:33 <br/> * @author ZhaoQi * @version enclosing_typetags * @since JDK 1.7 * @see */ public interface RoleService { public Role findRoleByID(int id); }
package org.com.ramboindustries.corp.test; import org.com.ramboindustries.corp.sql.annotations.SQLForeignKey; import org.com.ramboindustries.corp.sql.annotations.SQLInheritancePK; import org.com.ramboindustries.corp.sql.annotations.SQLTable; @SQLTable(table = "TB_MATEHUS", dropTableIfExists = false) @SQLInheritancePK(primaryKeyName = "Matheus_ID") public class Matheus extends Aluno { @SQLForeignKey(required = true, classReferenced = Departamento.class, name = "Departamento_ID") private Departamento departamento; public Departamento getDepartamento() { return departamento; } public void setDepartamento(Departamento departamento) { this.departamento = departamento; } @Override public String toString() { return "Matheus [departamento=" + departamento + ", getNota()=" + getNota() + ", getId()=" + getId() + ", getNome()=" + getNome() + ", toString()=" + super.toString() + "]"; } }
package com.parkinglot.entities; public abstract class Vehicle { private String plateNumber; private Color color; public Vehicle(String plateNumber, Color color) { this.color = color; this.plateNumber = plateNumber; } public String getPlateNumber() { return plateNumber; } public void setPlateNumber(String plateNumber) { this.plateNumber = plateNumber; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } }
package com.suhid.practice.controller; import com.suhid.practice.dto.request.SignUpRequest; import com.suhid.practice.services.CourseService; import com.suhid.practice.services.SignUpAndSignInServices; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/students") public class SignUpAndSignInController { private final SignUpAndSignInServices signUpAndSignInServices; private final CourseService courseService; public SignUpAndSignInController(SignUpAndSignInServices signUpAndSignInServices, CourseService courseService) { this.signUpAndSignInServices = signUpAndSignInServices; this.courseService = courseService; } @PostMapping("/signup/") public ResponseEntity<String> SignUp(@RequestBody SignUpRequest signUpRequest){ return new ResponseEntity(signUpAndSignInServices.SignUp(signUpRequest), HttpStatus.CREATED); } @PutMapping("/user/{id}") public void updateUser(@PathVariable Long id, @RequestBody SignUpRequest signUpRequest) { signUpAndSignInServices.UpdateUser(id,signUpRequest); } @GetMapping("/signin/") public String SignIn(){ return ""; } }
package backendjava.Modul2.MileStone2; import javax.swing.JOptionPane; public class Fase1 { /** * Crea una aplicació que dibuixi una escala de nombres, sent cada línia nombres * començant en un i acabant en el nombre de la línia */ public static void main(String[] args) { // TODO Auto-generated method stub int num = Integer.parseInt(JOptionPane.showInputDialog("Introdueix numero=")); for (int i = 1; i <= num; i++) { for (int j = 1; j <= i; j++) { System.out.print(j); } System.out.println(); } } }
package com.fansolomon.Creational.Singleton; /** * 饿汉式 * 类加载到内存后,就实例化一个单例,JVM保证线程安全 * 唯一缺点:不论用到与否,类装载时就会完成实例化 * 关于懒加载:Class.forName("") */ public class Singleton01 { // 方式一 private static final Singleton01 INSTANCE = new Singleton01(); // 方式二 /*private static final Singleton01 INSTANCE; static { INSTANCE = new Singleton01(); }*/ private Singleton01() {}; public static Singleton01 getInstance() { return INSTANCE; } public static void main(String[] args) { Singleton01 s1 = Singleton01.getInstance(); Singleton01 s2 = Singleton01.getInstance(); System.out.println(s1 == s2); } }
package com.github.vinja.omni; public class ReferenceLocation { public String className; public String methodName; public String methodDesc; public String source; public int line; public ReferenceLocation(String cName, String mName, String mDesc, String src, int ln) { className = cName; methodName = mName; methodDesc = mDesc; source = src; line = ln; } }
package com.yoeki.kalpnay.hrporatal.Interview; import android.app.Activity; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.yoeki.kalpnay.hrporatal.Notification.EventAdapter; import com.yoeki.kalpnay.hrporatal.Notification.EventDetails; import com.yoeki.kalpnay.hrporatal.Notification.NotificationEventModel; import com.yoeki.kalpnay.hrporatal.R; import java.util.List; public class InterviewhomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int TYPE_ITEM = 2; private List<INterViewHomeModel> stringArrayList; private Activity activity; public InterviewhomeAdapter(Activity activity,List<INterViewHomeModel> strings) { this.activity = activity; this.stringArrayList = strings; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //Inflating recycle view item layout View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_interviewhome, parent, false); return new ItemViewHolder(itemView); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { ItemViewHolder itemViewHolder = (ItemViewHolder) holder; itemViewHolder.tv_candidatename.setText(stringArrayList.get(position).getName()); itemViewHolder.tv_candidatedesignation.setText(stringArrayList.get(position).getDesignation()); itemViewHolder.tv_candidatedate.setText(stringArrayList.get(position).getDate()); itemViewHolder.card_interviewhome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(activity,InterviewScheduleActivity.class); intent.putExtra("name",stringArrayList.get(position).getName()); intent.putExtra("deg",stringArrayList.get(position).getDesignation()); activity.startActivity(intent); } }); } @Override public int getItemViewType(int position) { return TYPE_ITEM; } @Override public int getItemCount() { return stringArrayList.size(); } private class ItemViewHolder extends RecyclerView.ViewHolder { TextView tv_candidatename, tv_candidatedesignation, tv_candidatedate; CardView card_interviewhome; public ItemViewHolder(View itemView) { super(itemView); tv_candidatename = itemView.findViewById(R.id.tv_candidatename); tv_candidatedesignation = itemView.findViewById(R.id.tv_candidatedesignation); tv_candidatedate = itemView.findViewById(R.id.tv_candidatedate); card_interviewhome=itemView.findViewById(R.id.card_interviewhome); } } }
package edu.data.service; import edu.curd.dto.StudentGradesDTO; import java.util.List; public interface ManageGradesService { public List<StudentGradesDTO> viewStudentGrades(int selectedClassId, int selectedExcercisesId, int selectedTopicId); public boolean updateMarks(int gradesId, String newScore); public boolean insertMarks(int studentEnrollId, int selectedTopicId, String newScore); }
package ad.joyplus.com.myapplication.AppUtil; /** * Created by UPC on 2017/1/5. */ public class Consts { public static final String REQUEST_HEAD_LINK = "getAppVersion.php?";//请求链接 public static final String SDK_VERSION = "1.0.1";//SDK版本号 public static final String CONFIG_VERSION = "config_verson"; public static final String SP_NAME = "config"; public static final String SP_JSON_INFO = "info_json"; public static final String AD_VIDEOIMG = "videoimg"; public static final String AD_STARTMEDIA = "startmedia"; public static final String AD_ENDMEDIA = "endmedia"; public static final String AD_CORNERIMG = "cornerimg"; public static final String AD_SIMPLEIMG = "simpleimg"; public static final String AD_OPEN = "open"; public static final int OPEN = 001; public static final int STARTMEDIA = 002; public static final int ENDMEDIA = 003; public static final int VIDEOIMG = 004; public static final int CORNERIMG = 005; public static final int SIMPLEIMG = 006; public static final String MIAOZHEN = "miaozhen"; public static final String ADMASTER = "admaster"; public static final String CONNECTION_TYPE = "connection_type"; public static final String DEV = "dev"; public static final String KEY = "key"; public static final String I_ = "i"; public static final String U_ = "u"; public static final String T_ = "t"; public static final String IP_ = "ip"; public static final String V_ = "v"; public static final String S_ = "s"; public static final String BASEURL = "baseurl"; public static final String CONFIG_NAME = "AppADSDK.properties"; }
package com.example.myapplication.dg.module; import android.app.Dialog; import android.content.Context; import com.example.myapplication.IView; import com.example.myapplication.dg.ActivityScope; import com.example.myapplication.dg.DaggerNamed; import com.example.myapplication.enity.TestBean; import dagger.Module; import dagger.Provides; /** * ****************************** * * @author YOULU-wwb * date: 2020/1/11 9:56 * description: * ****************************** */ @Module public class ExamModule { @ActivityScope @Provides TestBean testBean(){ return new TestBean(); } //传参方式1 // IView iView; // public ExamModule(IView iView) { // this.iView = iView; // } // // @Provides // IView iView() { // return iView; // } Context context; public ExamModule(Context context) { this.context = context; } @Provides Context context(){ return context; } @DaggerNamed("LoginDialog") @Provides Dialog loginDialog(Context context){ Dialog dialog = new Dialog(context); dialog.setTitle("登录提示"); // dialog.setOnCancelListener("取消"); return dialog; } }
package shared.communication; import java.util.ArrayList; import java.util.List; import shared.clientCommunicator.ClientCommunicator; import shared.model.SingleSearchResult; public class Search_Result { private List<SingleSearchResult> result_list = new ArrayList<SingleSearchResult>(); private Boolean result; public void add_result(int batchID, String imageURL, int recordNum, int fieldID) { SingleSearchResult result = new SingleSearchResult(batchID, imageURL, recordNum, fieldID); result_list.add(result); } /** * @return the result */ public Boolean getResult() { return result; } /** * @param result the result to set */ public void setResult(Boolean result) { this.result = result; } /** * @return the result_list */ public List<SingleSearchResult> getResult_list() { return result_list; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { if(result) { StringBuilder sb = new StringBuilder(); for(SingleSearchResult a : result_list) { sb.append(a.getBatchID()); sb.append("\n"); sb.append(ClientCommunicator.URL_PREFIX); sb.append("/"); sb.append(a.getImageURL()); sb.append("\n"); sb.append(a.getRecordNum()); sb.append("\n"); sb.append(a.getFieldID()); sb.append("\n"); } return sb.toString(); } else { return "FAILED\n"; } } }
package com.fleet.postgresql.controller; import com.fleet.postgresql.entity.User; import com.fleet.postgresql.service.UserService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @author April Han */ @RestController @RequestMapping("/user") public class UserController { @Resource UserService userService; @RequestMapping("/insert") public void insert(@RequestBody User user) { userService.insert(user); } @RequestMapping("/get") public User get(Long id) { return userService.get(id); } }
package com.andyadc.seckill.infrastructure.lock.redisson; import com.andyadc.seckill.infrastructure.lock.DistributedLock; import com.andyadc.seckill.infrastructure.lock.factory.DistributedLockFactory; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * 基于 Redisson 的分布式锁实现服务 */ @Component @ConditionalOnProperty(name = "distributed.lock.type", havingValue = "redisson") public class RedissonLockFactory implements DistributedLockFactory { private static final Logger logger = LoggerFactory.getLogger(RedissonLockFactory.class); private final RedissonClient redissonClient; public RedissonLockFactory(@Qualifier("redissonClient") RedissonClient redissonClient) { this.redissonClient = redissonClient; } @Override public DistributedLock get(String key) { RLock rLock = redissonClient.getLock(key); return new DistributedLock() { @Override public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException { return rLock.tryLock(waitTime, leaseTime, unit); } @Override public void lock(long leaseTime, TimeUnit unit) { rLock.lock(leaseTime, unit); } @Override public void unlock() { if (isLocked() && isHeldByCurrentThread()) { rLock.unlock(); } } @Override public boolean isLocked() { return rLock.isLocked(); } @Override public boolean isHeldByThread(long threadId) { return rLock.isHeldByThread(threadId); } @Override public boolean isHeldByCurrentThread() { return rLock.isHeldByCurrentThread(); } }; } }
package com.project.auth.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; /* * This Java Class will work as Resource Server... * Resources like URLs, users, etc... all those will be configured here * You can have various types of way to provide this using inMemory, Database, LDAP, etc... * */ @Configuration @EnableResourceServer public class ResourceServerConfig extends WebSecurityConfigurerAdapter { private static final Logger logger = LoggerFactory.getLogger( ResourceServerConfig.class ); private static final String logPrefix = "<<<<< ResourceServerConfig >>>>> "; @Autowired AuthenticationManager authenticationManager; @Override protected void configure(HttpSecurity http) throws Exception { logger.info( logPrefix + " Configure HTTPSecurity where you will say what are the URLs can be access " + "with and without authencation & authorization..." ); http.requestMatchers() .antMatchers( "/login", "/oauth/authorize" ) .and() .authorizeRequests().anyRequest().authenticated() .and() .formLogin() .permitAll(); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.parentAuthenticationManager( authenticationManager ) .inMemoryAuthentication() .withUser( "pramukh" ) .password( "swami" ) .roles( "ADMIN" ); } }
package br.com.bytebank.banco.modelo; import br.com.bytebank.banco.exception.PosicaoInvalidaListaDeContaException; public class ListaDeConta { private Object[] listaConta; private int posicaoLivre; public ListaDeConta( ) { listaConta = new Conta[10]; posicaoLivre = 0; } public void adiciona(Conta conta) { listaConta[posicaoLivre] = conta; posicaoLivre++; } public int getQuantidadeDeElementos() { return posicaoLivre; } public Object getConta(int posicao) throws PosicaoInvalidaListaDeContaException { try { return listaConta[posicao]; } catch (Exception e) { return null; } } }
/** * Contains the types of object that any menu uses and stores its data. Dish and * Ingredient. * */ package staff.menu;
package ru.otus.l141.sort; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; public class ForkJoinSorterBenchmark { public static void main(String[] args) throws Exception { Options opt = new OptionsBuilder() .include(ForkJoinSorterBenchmark.class.getSimpleName()) .warmupIterations(1) .measurementIterations(5) .forks(1) .build(); new Runner(opt).run(); } @State(Scope.Thread) public static class BenchmarkExecutionPlan { @Param({ "1000000" }) public int size; @Param({ "1", "2" }) public int iterations; @Param({ "1", "2", "4" }) public int threads; public List<Integer> values; @Setup(Level.Invocation) public void setUp() { values = new ArrayList<>(size); for(int i = 1; i <= size; i++) { values.add(i); } Collections.shuffle(values); } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public void timeParallelSortRunner(BenchmarkExecutionPlan plan) throws ExecutionException, InterruptedException { Sorter sorter = new ForkJoinSorterImpl(); for (int i = 0; i < plan.iterations; i++) { sorter.sort(plan.values, plan.threads); } } }
package com.yoeki.kalpnay.hrporatal.Profile.Model.user_info; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class BasicUserInfo { @SerializedName("PesonalNumber") @Expose private String pesonalNumber; @SerializedName("Code") @Expose private String code; @SerializedName("Designation") @Expose private String designation; @SerializedName("Title") @Expose private String title; @SerializedName("UserName") @Expose private String userName; @SerializedName("Gender") @Expose private String gender; @SerializedName("MartialStatus") @Expose private String martialStatus; @SerializedName("DOB") @Expose private String dOB; @SerializedName("StartingDate") @Expose private String startingDate; public String getPesonalNumber() { return pesonalNumber; } public void setPesonalNumber(String pesonalNumber) { this.pesonalNumber = pesonalNumber; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getMartialStatus() { return martialStatus; } public void setMartialStatus(String martialStatus) { this.martialStatus = martialStatus; } public String getDOB() { return dOB; } public void setDOB(String dOB) { this.dOB = dOB; } public String getStartingDate() { return startingDate; } public void setStartingDate(String startingDate) { this.startingDate = startingDate; } }
package apppackage; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.touch.TapOptions; import io.appium.java_client.touch.offset.ElementOption; import io.appium.java_client.touch.offset.PointOption; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.interactions.touch.TouchActions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import Utilities.Common; import Utilities.GlobalKeys; import Utilities.GlobalKeys; /** * Base class for all the pages. * */ public abstract class MobilePage { protected AppiumDriver<MobileElement> browser; protected final int defaultElementLoadWaitTime = 20; protected abstract boolean isValidPage(); protected abstract void waitForPageLoad(); /** * Constructor for Page class * @param browser * @param report */ protected MobilePage(AppiumDriver browser) { this.browser=browser; PageFactory.initElements(browser, this); waitForPageLoad(); //verifyApplicationInCorrectPage(); } /** * Verify Application in Correct Page. * @param Nil * @return Nil */ private void verifyApplicationInCorrectPage() { if (!isValidPage()) { String stepName="Navigation to Page"; String message="The application is not in the expected page , current page: " + browser.getTitle() +" Page."; } } /** * Get the browser object specified in the property * @param browserName * @return */ public static AppiumDriver getAppiumDriver(String browserName) { AppiumDriver<MobileElement> driver = null; if(!(Common.getConfigProperty("ExecutionHost").trim().toLowerCase().contains("cloud"))){ String platForm = Common.getConfigProperty("PlatFormName").toString().trim(); String deviceName = Common.getConfigProperty("DeviceName").toString().trim(); String platformVersion = Common.getConfigProperty("PlatformVersion").toString().trim(); GlobalKeys.extent.addSystemInfo("Browser", browserName); GlobalKeys.extent.addSystemInfo("URL", Common.getConfigProperty("URL")); GlobalKeys.extent.addSystemInfo("Platform", platForm); if(platForm.contains("Android")){ Common.writeToLogFile("INFO", "Opening " + browserName + " Application..."); try { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability("deviceName", deviceName); caps.setCapability("udid", deviceName); // Give Device ID of your mobile phone caps.setCapability("platformName", platForm); caps.setCapability("platformVersion", platformVersion); caps.setCapability("browserName", browserName); caps.setCapability("noReset", true); driver = new AndroidDriver<MobileElement>(new URL("http://" + GlobalKeys.host + ":" + GlobalKeys.port + "/wd/hub"), caps); //driver.get(Common.getConfigProperty("URL")); } catch (TimeoutException e) { Common.testStepFailed("Page fail to load within in " + Common.getConfigProperty("pageLoadWaitTime") + " seconds"); } catch (Exception e) { Common.writeToLogFile("ERROR", "Browser: Open Failure/Navigation cancelled, please check the application window."); Common.writeToLogFile("Error", e.toString()); Common.testReporter("Red", e.toString()); Common.testStepFailed("Open App : AppName"); } }else{ Common.writeToLogFile("INFO", "Opening " + browserName + " Application..."); try { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability("platformName", platForm); caps.setCapability("udid", deviceName); caps.setCapability("deviceName", "iPhone 6 Plus"); caps.setCapability("browserName", browserName); caps.setCapability("app", "io.appium.SafariLauncher"); caps.setCapability("automationName", "XCUITest"); caps.setCapability("wdaConnectionTimeout", 6000); driver = new IOSDriver(new URL("http://" + GlobalKeys.host + ":" + GlobalKeys.port + "/wd/hub"), caps); } catch (TimeoutException e) { Common.testStepFailed("Page fail to load within in " + Common.getConfigProperty("pageLoadWaitTime") + " seconds"); } catch (Exception e) { Common.writeToLogFile("ERROR", "Browser: Open Failure/Navigation cancelled, please check the application window."); Common.writeToLogFile("Error", e.toString()); Common.testReporter("Red", e.toString()); Common.testStepFailed("Open App : AppName"); } } }else{ try { DesiredCapabilities caps = new DesiredCapabilities(); //caps.setCapability("appiumVersion", "1.9.1"); caps.setCapability("deviceName", "Galaxy S8"); caps.setCapability("platformName", "Android"); caps.setCapability("platformVersion", "8.0"); caps.setCapability("browserName", "Chrome"); caps.setCapability("name", "Cloud Android Test"); //final String URL = "https://prakashshetty1:PsXkVipzUbHwdBYky8ee@hub-cloud.browserstack.com/wd/hub"; final String URL = "http://prakash%40suntechnologies.com:u554805f385a6bcd@hub.crossbrowsertesting.com:80/wd/hub"; driver = (AppiumDriver<MobileElement>) new RemoteWebDriver(new URL(URL), caps); /* caps.setCapability("os_version", "11.0"); caps.setCapability("device", "Galaxy S7"); caps.setCapability("real_mobile", "true"); caps.setCapability("browserstack.local", "false");*/ } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return driver; } /** * Check if the element is present in the page * @param element MobileElement need to check * @return True if present */ protected boolean isElementPresent(WebElement element){ try{ return element.isDisplayed(); }catch(NoSuchElementException ex){ return false; }catch(Exception ex2){ return false; } } /** * To generate Random Number * @param int min and max numbers * @return random Number in Integer */ public static int randInt(int min, int max) { // Usually this can be a field rather than a method variable Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; } /** * Check if the element is displayed in the page * @param element MobileElement need to check * @return True if present */ protected boolean isElementDisplayed(MobileElement element, String str){ try{ boolean blnDisplay = element.isDisplayed(); Common.testStepPassed(str+" is Displayed"); return blnDisplay; }catch(NoSuchElementException ex){ Common.testStepFailed(str+" is Not Displayed"); return false; } } /** * Check if the element is present in the page * @param xpath of MobileElement need to check * @return True if present */ public boolean isElementPresent(By by){ try{ return browser.findElement(by).isDisplayed(); }catch(NoSuchElementException ex){ return false; }catch(Exception ex2){ return false; } } /*** * Method to select recentPopupSelect_without_window_nameWebdriver * @return : Null ***/ public void recentPopupSelect_without_window_nameWebdriver() { String mainwindow; mainwindow = browser.getWindowHandle(); sleep(2000); Iterator<String> popwindow = browser.getWindowHandles().iterator(); while (popwindow.hasNext()) { String window = popwindow.next(); browser.switchTo().window(window); } } /*** * Method to click on a link(MobileElement button) * @param : we MobileElement to be clicked * @param : elem Name of the MobileElement ***/ public void clickOn(WebElement we,String elem) { try{ waitForElement(we); if (isElementPresent(we)){ //moveToElement(we); we.click(); Common.testStepPassed("Clicked on WebElement-"+ elem ); }else{ Common.testStepFailed(elem+" Element is not displayed"); } } catch (Exception ex) { Common.testStepFailed("Unable to click on Element-"+ elem +", Exception is->"+ex.getMessage()); } } /** * Method to jsclick on a link(MobileElement link) * @param : we MobileElement to be Clicked * @param : elem Name of the webElement */ protected void jsClick(MobileElement we,String elem) { try{ scrollPageDown(we); ((JavascriptExecutor) browser).executeScript("arguments[0].click();",we); Common.testStepPassed("Clicked on -"+ elem +"- Element"); }catch (RuntimeException ex) { Common.testStepFailed("Uanble to click on -"+ elem +"- Element"); } } /*** * Method to enter text in a textbox * @param : Webelement * @param : Name of the Webelement * @param : text to be entered * @return : true if entered ***/ public boolean enterText(WebElement we,String elemName,String text){ boolean blnFlag; blnFlag = false; try{ waitForElement(we); if(isElementPresent(we)){ //we.clear(); we.sendKeys(text); Common.testStepPassed("Entered value - "+text+" in the text field- "+ elemName); hideKeyboard(); blnFlag = true; }else{ Common.testStepFailed(elemName+" element is not present"); } } catch (Exception ex) { Common.testStepFailed("Unable to enter text in the text field->"+ elemName + ", Exception is->"+ex.getMessage()); } return blnFlag; } public String getAttribute(WebElement we,String attribute){ try{ waitForElement(we); if(isElementPresent(we)){ return we.getAttribute(attribute); }else{ return null; } }catch (Exception ex) { Common.testStepFailed("Exception caught->"+ex.getMessage()); return null; } } public void hideKeyboard(){ try{ browser.hideKeyboard(); }catch(Exception ex){ //do nothing } } /*** * Method to enter text in a textbox * @param : Webelement * @param : Name of the Webelement * @param : text to be entered * @return : true if entered ***/ public boolean enterText(MobileElement we,String elemName,String text,int waitTime){ boolean blnFlag; blnFlag = false; try{ waitForElement(we,waitTime); if(isElementPresent(we)){ we.clear(); we.sendKeys(text); Common.testStepPassed("Entered value - "+text+" in the text field- "+ elemName); blnFlag = true; }else{ Common.testStepFailed(elemName+" element is not displayed"); } } catch (Exception ex) { Common.testStepFailed("Unable to enter text in the text field->"+ elemName); } return blnFlag; } /*** * Method to clear text in a textbox * @param : Element Name * @return : ***/ public void clearText(MobileElement we){ try{ if(isElementPresent(we)){ we.clear(); } }catch(Exception ex){ Common.testStepFailed("Unable to clear text in the text field"); } } /*** * Method to switch to child window * @param : pageTitle Title of the Child window * @return : true if navigation is success ***/ public boolean navigateToNewWindow(String pageTitle) { boolean loopstatus = false; int timeout = GlobalKeys.pageLoadWaitTime; for (int i = 1; i <= timeout; i++) { loopstatus = false; if (i == timeout) { Common.testStepFailed("Unable to Navigate to the page -"+pageTitle); } Set<String> AllHandle = browser.getWindowHandles(); for (String han : AllHandle) { browser.switchTo().window(han); String getTitle = browser.getTitle(); if (getTitle.trim().equalsIgnoreCase(pageTitle)) { loopstatus = true; break; } } if (loopstatus) { Common.testStepPassed("Navigated to the page -"+pageTitle+"- successfully"); break; } sleep(1000); } return loopstatus; } /*** * Method to switch to child window * @param : pageTitle Title of the Child window * @return : true if navigation is success ***/ public boolean navigateToSecondWindow() { boolean loopstatus = false; String getTitle = null; int timeout = GlobalKeys.pageLoadWaitTime; String strParentTitle = browser.getTitle(); for (int i = 1; i <= timeout; i++) { loopstatus = false; if (i == timeout) { Common.testStepFailed("Unable to Navigate to the new window-"); } Set<String> AllHandle = browser.getWindowHandles(); for (String han : AllHandle) { browser.switchTo().window(han); getTitle = browser.getTitle(); if (!getTitle.trim().equalsIgnoreCase(strParentTitle)) { loopstatus = true; break; } } if (loopstatus) { Common.testStepPassed("Navigated to the page -"+getTitle+"- successfully"); browser.manage().window().maximize(); break; } sleep(1000); } return loopstatus; } /*** * Method to switch to parent window * @param : parentWindow Window handle of the parent window ***/ public void navigatoToParentWindow(String parentWindow) { browser.switchTo().window(parentWindow); } /*** * Javascript to hover over MobileElement * @param elem Webelement to hover over */ public void jsmoveToElement(MobileElement elem){ String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}"; JavascriptExecutor js = (JavascriptExecutor) browser; js.executeScript(mouseOverScript, elem); } /*** * Method to close a webpage * @return : Null ***/ public void closeCurrentPage(){ String str=browser.getTitle(); try { browser.close(); Set<String> windows=browser.getWindowHandles(); for(String window:windows){ browser.switchTo().window(window); String getTitle = browser.getTitle(); if (!getTitle.trim().equalsIgnoreCase(str)) { break; } } sleep(5000); Common.testStepPassed("Closed the current page with title->"+str); } catch (Exception e) { Common.testStepFailed("Unable to Close the current page with title->"+str); } } //*****************************************************************************************************************// //Alert pop ups //*****************************************************************************************************************// /*** * Method to accept and close alert and return the text within the alert * @param : * @return : ***/ public String closeAlertAndReturnText(){ String alertMessage=null; try{ WebDriverWait wait = new WebDriverWait(browser, GlobalKeys.elementLoadWaitTime); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = browser.switchTo().alert(); alertMessage=alert.getText(); Common.testStepPassed("alertMessage displayed is->"+alertMessage); alert.accept(); Common.testStepPassed("Alert is closed successfully"); }catch(Exception Ex){ Common.testStepFailed("Unable to Close Alert, Error Message is->"+Ex.getMessage()); } return alertMessage; } /*** * Method to Cancel the alert * @param : * @return : ***/ public void alertCancel(){ try{ WebDriverWait wait = new WebDriverWait(browser, GlobalKeys.elementLoadWaitTime); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = browser.switchTo().alert(); alert.dismiss(); Common.testStepPassed("Clicked on Alert Cancel successfully"); }catch(Exception ex){ Common.testStepFailed("Unable to Cancel Alert, Error Message is->"+ex.getMessage()); } } /*** * Method to verify if alert is Present * @param : * @return : ***/ public boolean isAlertWindowPresent() { try { browser.switchTo().alert(); return true; } catch (Exception E) { } return false; } //*****************************************************************************************************************// //waits //*****************************************************************************************************************// /** * Method to wait for element to load in the page * @param MobileElement * @return true or false */ protected Boolean waitForElement(By by) { try { new WebDriverWait(browser,GlobalKeys.elementLoadWaitTime). until(ExpectedConditions.presenceOfElementLocated(by)); } catch (Exception ex) { return false; } return true; } protected Boolean waitForElementInvisible(By by) { try { new WebDriverWait(browser,GlobalKeys.elementLoadWaitTime). until(ExpectedConditions.invisibilityOfElementLocated(by)); } catch (Exception ex) { return false; } return true; } /** * Method to wait for element to load in the page for default time specified in framework configuration * @param MobileElement * @return true or false */ protected Boolean waitForElement(WebElement we) { try { new WebDriverWait(browser, GlobalKeys.elementLoadWaitTime).until(ExpectedConditions .elementToBeClickable(we)); return true; } catch (RuntimeException ex) { return false; } } /** * Method to wait for element to load in the page for particular time specified * @param MobileElement * @return true or false */ protected Boolean waitForElement(MobileElement we,int waitTime) { try { new WebDriverWait(browser, waitTime).until(ExpectedConditions .elementToBeClickable(we)); return true; } catch (RuntimeException ex) { return false; } } /** * Method to wait for Alert present in the page * @param * @return true or false */ protected Boolean waitForAlert(){ try{ new WebDriverWait(browser, GlobalKeys.elementLoadWaitTime).until(ExpectedConditions.alertIsPresent()); return true; }catch(Exception Ex){ return false; } } /*** * Method to get current time in minutes * @param : Element Name * @return : * Modified By : ***/ public int getTimeInMin(String time) { //String time=new SimpleDateFormat("HH:mm").format(new Date()); String[] splitTime=time.split(":"); int hr=Integer.parseInt(splitTime[0]); int mn=Integer.parseInt(splitTime[1].substring(0,2)); if(hr>12){ hr=hr-12; } int timStamp=(hr*60)+mn; return timStamp; } /*** * Method to check for an alert for 5 seconds * @param : Element Name * @return : * Modified By : ***/ public boolean isAlertPresent(){ try{ WebDriverWait wait = new WebDriverWait(browser, GlobalKeys.elementLoadWaitTime); wait.until(ExpectedConditions.alertIsPresent()); return true; }catch(Exception e){ return false; } } /*** * Method to wait for the any of 2 elements to be displayed * @param : we1,we2 * @return : * @author : Prakash Shetty * Modified By : ***/ public boolean waitForAnyElement(MobileElement we1,MobileElement we2){ try{ for(int i=0;i<GlobalKeys.elementLoadWaitTime;i++){ if(isElementPresent(we1)||isElementPresent(we2)){ break; }else{ sleep(1000); } } return true; }catch(Exception Ex){ return false; } } /*** * Method to wait for the any of 2 elements to be displayed * @param : we1,we2 * @return : * @author : Prakash Shetty * Modified By : ***/ public boolean waitForTwoElements(MobileElement we1,MobileElement we2){ try{ for(int i=0;i<GlobalKeys.elementLoadWaitTime;i++){ if(isElementPresent(we1)||isElementPresent(we2)){ break; }else{ sleep(1000); } } return true; }catch(Exception Ex){ return false; } } /*** * Method to wait for the any of 2 elements to be displayed * @param : we1,we2,we3 * @return : * @author : Prakash Shetty * Modified By : ***/ public boolean waitForThreeElements(MobileElement we1,MobileElement we2,MobileElement we3){ try{ for(int i=0;i<GlobalKeys.elementLoadWaitTime;i++){ if(isElementPresent(we1)||isElementPresent(we2)||isElementPresent(we3)){ break; }else{ sleep(1000); } } return true; }catch(Exception Ex){ return false; } } /** * method to make a thread sleep for customized time in milliseconds * @param milliseconds */ protected void sleep(int milliseconds){ try { Thread.sleep(milliseconds); } catch (InterruptedException e) { e.printStackTrace(); } } public void selectRadioButton(By by,String value) { boolean blnSelect; blnSelect = false; try{ List<MobileElement> radioList=browser.findElements(by); for(MobileElement element : radioList){ String strActValue = element.getAttribute("value"); if(strActValue.equalsIgnoreCase(value)){ element.click(); Common.testStepPassed("Radio button selected is->"+value); blnSelect = true; break; } } if(!blnSelect){ Common.testStepFailed("Radio button with specified value does not exist->"+value); } }catch(Exception ex){ Common.testStepFailed("Exception Caught,Message is->"+ex.getMessage()); } } /*** * Method to wait for the any of 2 elements to be displayed * @param : By,By * @return : * @author : Prakash Shetty * Modified By : ***/ public boolean waitForAnyElement(By we1,By we2){ try{ for(int i=0;i<GlobalKeys.elementLoadWaitTime;i++){ if(isElementPresent(we1)||isElementPresent(we2)){ break; }else{ sleep(1000); } } return true; }catch(Exception Ex){ return false; } } /*** * Method to hover over an element * @param : weMainMenuElement,weSubMenuElement * @return : * Modified By : ***/ public void clickOnSubMenu(MobileElement weMain,MobileElement weSub ){ String strElem=null; try{ Actions action = new Actions(browser); action.moveToElement(weMain).click().perform(); Common.testStepPassed("Hover over the Main menu item successfully"); }catch(Exception Ex){ Common.testStepFailed("Unable to hover Over main menu Item"); } try{ waitForElement(weSub); strElem = weSub.getText(); weSub.click(); Common.testStepPassed("Clicked on the Sub menu item successfully"); }catch(Exception ex){ Common.testStepFailed("Unable to Click on the sub menu item"); } } /*** * Method to hover over an element * @param : MobileElement we * @return : * Modified By : ***/ public void moveToElement(MobileElement we){ try { /*Actions action = new Actions(browser); action.moveToElement(we).build().perform();*/ scrollPageDown(we); } catch (Exception e) { Common.testStepFailed("Error Occurred while Move to Element --> "+e.getMessage()); } } public void moveToElement(By by){ try { /*Actions action = new Actions(browser); action.moveToElement(we).build().perform();*/ scrollPageDown(by); } catch (Exception e) { Common.testStepFailed("Error Occurred while Move to Element --> "+e.getMessage()); } } /*** * Method to drag and drop from source element to destination element * @param : weSource,weDestination * @return : * Modified By : ***/ public void dragAndDrop(MobileElement weSource, MobileElement weDestination) { try { new Actions(browser).dragAndDrop(weSource, weDestination).perform(); Common.writeToLogFile("Info", "Drag and drop successful"); Common.testReporter("Green", "Drag Source element and drop on Destination Element"); } catch (Exception e) { Common.writeToLogFile("Error", "Error during drag and drop"); Common.testStepFailed("Error : Drag Source element and drop on Destination Element"); } } /*** * Method to Select value from dropdown by visible text * @param : we,strElemName,strVisibleText * @return : * Modified By : ***/ public void selectByVisisbleText(MobileElement we,String strElemName,String strVisibleText){ try{ Select sel = new Select( we); sel.selectByVisibleText(strVisibleText); Common.testStepPassed("selected value -"+strVisibleText +" from dropdown->"+strElemName); }catch(Exception Ex){ Common.testStepFailed("Unable to select value from the dropdown "+Ex.getMessage()); } } /*** * Method to Select value from dropdown by index * @param : we,strElemName,index * @return : * Modified By : ***/ public void selectByIndex(WebElement we,String strElemName,int index){ try{ Select sel = new Select( we); sel.selectByIndex(index); Common.testStepPassed("Selected "+index +"option from dropdown->"+strElemName); }catch(Exception Ex){ Common.testStepFailed("Unable to select value from the dropdown "+Ex.getMessage()); } } /*** * Method to Select value from dropdown by index * @param : we,strElemName,strValue * @return : * Modified By : ***/ public void selectByValue(MobileElement we,String strElemName,String strValue){ try{ Select sel = new Select( we); sel.selectByValue(strValue); Common.testStepPassed("Selected "+strValue +"option from dropdown->"+strElemName); }catch(Exception Ex){ Common.testStepFailed("Unable to select value from the dropdown "+Ex.getMessage()); } } /*** * Method to get the Selected value from dropdown * @param : weDropdown * @return : selectText * Modified By : ***/ public String getTextSelectedOption(MobileElement weDropDown){ waitForElement(weDropDown); String selectText=""; try { Select select = new Select(weDropDown); selectText = select.getFirstSelectedOption().getText().toString(); }catch(Exception ex){ Common.testStepFailed("Unable to get the selected value from dropdown->"+ex.getMessage()); } return selectText; } /*** * Method to verify if the MobileElement has the expected text * @param : we,expectedText * @return : * Modified By : ***/ public void verifyElementText(MobileElement we, String expectedText) { waitForElement(we); if (isElementPresent(we)){ for (int i = 1; i <= GlobalKeys.elementLoadWaitTime; i++){ try { if (we.getText().trim().equalsIgnoreCase(expectedText.trim())){ Common.testStepPassed("Element contains the Expected Text->" + expectedText); }else{ Common.testStepFailed("Element does not contain the expected text" + expectedText); } }catch (Exception e){ sleep(1000); } if (i == GlobalKeys.elementLoadWaitTime){ Common.testStepFailed("Element not found within " + GlobalKeys.elementLoadWaitTime + " timeouts"); } } } } /*** * Method to get the ElementLoadWaitTime * @param : * @return : ElementLoadWaitTime * Modified By : ***/ public int getElementLoadWaitTime(){ try{ String waitTime = Common.getConfigProperty("ElementLoadWaitTime"); int i = Integer.parseInt(waitTime); if(i<1){ return defaultElementLoadWaitTime; }else{ return i; } }catch(Exception ex){ return defaultElementLoadWaitTime; } } /*** * Method to wait till the page contains expected text * @param : txt * @return : * Modified By : ***/ public void waitForText(String txt) { waitForText(txt, GlobalKeys.textLoadWaitTime); } /*** * Method to wait till the page contains expected text * @param : txt,timeout * @return : * Modified By : ***/ public void waitForText(String txt, int timeout){ for (int second = 0; second < timeout; second++){ if (second == timeout - 1) { Common.testStepFailed("The text '" + txt + "' is not found within " + GlobalKeys.textLoadWaitTime + " seconds timeout"); break; } try{ if (browser.getPageSource().contains(txt)) { Common.writeToLogFile("INFO", "Text: '" + txt + "' is present"); } } catch (Exception localException){ try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } } public String getText(WebElement we){ if(isElementPresent(we)){ return we.getText(); } return null; } /*** * Method to close the browser with title provided * @param : windowTitle * @return : * Modified By : ***/ public void closeChildBrowser(String windowTitle) { try { for (String winHandle : browser.getWindowHandles()){ browser.switchTo().window(winHandle); if (browser.getTitle().equalsIgnoreCase(windowTitle)){ browser.close(); Common.testStepPassed("Closed the browser with page title->"+windowTitle); break; } } }catch (Exception e){ Common.testStepFailed("Unable to Close Browser"); } } /*** * Method to wait until element is invisible * @param : * @return : void * @author : suntechUser(userId) Modified By : ***/ protected Boolean waitUntilElementInvisible(String path) { try { new WebDriverWait(browser, GlobalKeys.elementLoadWaitTime).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(path))); return true; } catch (RuntimeException ex) { return false; } } /*** * Method to Switch to Frame * @param : * @return : void * @author : suntechUser(userId) Modified By : ***/ public void selectFrame(MobileElement we){ try { UnSelectFrame(); waitForElement(we); if (isElementPresent(we)){ browser.switchTo().frame(we); Common.testStepPassed("Switched to Frame-"+ we ); } else{ Common.testStepFailed(we+" frame not found"); } } catch(Exception e) { Common.testStepFailed("Exception Caught, Message is->"+e.getMessage()); } } /*** * Method to switch to default content * @param : * @return : * Modified By : ***/ public void UnSelectFrame() { try { Common.writeToLogFile("Info", "Switching to default content frame "); browser.switchTo().defaultContent(); } catch (Exception e) { Common.testStepFailed("Error in swiching to default content frame"); } } /*** * Method to select the checkbox * @param : cbElement * @return : * Modified By : ***/ public void selectCheckBox(MobileElement cbElement) { waitForElement(cbElement); if (isElementPresent(cbElement)) { try { if (!cbElement.isSelected()) { cbElement.click(); } Common.testStepPassed("Checked on the checkbox"); } catch (Exception e) { Common.testStepFailed("Unable to check the checkbox->"+e.getMessage()); } } } /*** * Method to UnSelect the checkbox * @param : cbElement * @return : * Modified By : ***/ public void unSelectCheckBox(MobileElement cbElement) { waitForElement(cbElement); if (isElementPresent(cbElement)) { try { if (cbElement.isSelected()) { cbElement.click(); } Common.testStepPassed("Unchecked the checkbox"); } catch (Exception e) { Common.testStepFailed("Unable to check the checkbox->"+e.getMessage()); } } } /*** * Method to verify the checkbox if checked * @param : cbElement * @return : * Modified By : ***/ public boolean verifyCheckBoxIsChecked(MobileElement cbElement) { waitForElement(cbElement); if (isElementPresent(cbElement)) { try{ if (cbElement.isSelected()){ return true; }else{ return false; } }catch (Exception e){ Common.testStepFailed("Unable to verify the checkbox->"+e.getMessage()); return false; } }else{ Common.testStepFailed("Unable to verify the checkbox"); return false; } } public void hoverMenu(MobileElement menu,String subMenuId) { try { Actions actions =new Actions(browser); actions.moveToElement(menu).perform(); By locator=By.id(subMenuId); browser.findElement(locator).click(); Common.testStepPassed("Clicked on Sub menu successfully"); } catch(Exception ex) { Common.testStepFailed("Hover Failed!!"); } } public boolean verifyPage(String pageTitle) { if(browser.getTitle().contains(pageTitle)) { Common.testStepPassed("Successfully Navigated to "+pageTitle); return true; } else { Common.testStepFailed("Unexpected Navigation!! Expected Navigation to "+pageTitle); return false; } } public void scrollPageDown(By by) { try { MobileElement we= browser.findElement(by); ((JavascriptExecutor) browser).executeScript("arguments[0].scrollIntoView(true);", we); sleep(2000); } catch (Exception e) { Common.testStepFailed("Exception caught while scrolling Page down "+e.getMessage()); } } public void scrollPageDown(MobileElement we) { try { ((JavascriptExecutor) browser).executeScript("arguments[0].scrollIntoView(true);", we); sleep(2000); } catch (Exception e) { Common.testStepFailed("Exception caught while scrolling Page down "+e.getMessage()); } } /*** * Method to double click on a web element * @param : we,strElemName,strVisibleText * @return : * Modified By : ***/ public void doubleClick(MobileElement we, String elem){ try{ Actions action = new Actions(browser); waitForElement(we); if (isElementPresent(we)){ action.moveToElement(we).doubleClick().perform(); Common.testStepPassed("Double Clicked on MobileElement-"+ elem ); }else{ Common.testStepFailed(elem+" Element is not displayed"); } } catch (Exception e) { Common.testStepFailed("Unable to douoble click - "+e.getMessage()); } } /*** * Method to check for an alert for 5 seconds * @param : Element Name * @return : * Modified By : ***/ public boolean AlertPresent(){ try{ WebDriverWait wait = new WebDriverWait(browser, 10); wait.until(ExpectedConditions.alertIsPresent()); return true; }catch(Exception e){ return false; } } /*** * Method to retrieve Sale number * @param : Element Name * @return : * Modified By : ***/ public String saleNumber; public String getSaleNumber(String str){ String s1 = str; String[] ref=s1.split("-"); String s2 = ref[1].trim().substring(0, 6); //s1.substring(10,17); s2.trim(); System.out.println("here:"+ s2); return s2; } /*** * Method to retrieve Allowance number * @param : Element Name * @return : * Modified By : ***/ public static String allowanceNumber; public String getAllowanceNumber(String str){ String s1 = str; String s2 = s1.substring(6); s2.trim(); System.out.println("here:"+ s2); allowanceNumber=s2; return s2; } public void navigatetobackscreen(String Pagename) { try { browser.navigate().back(); Common.testStepPassed("Navigated to the back page"+Pagename); } catch (Exception e) { // TODO: handle exception Common.testStepFailed("Could not navigate to new page"); } } public void navigatetoforwardscreen(String Pagename) { try { browser.navigate().forward(); Common.testStepPassed("Navigated to the forwared page"+Pagename); } catch (Exception e) { // TODO: handle exception Common.testStepFailed("Could not navigate to new forward page"); } } public static String selectedDate; /*** * Method to select future delivery date * @param : * @return : void * @author : suntechUser(userId) Modified By : * @Testcases: TC_10 ***/ /*** * Method to get selected delivery date * @param : * @return : void * @author : suntechUser(userId) Modified By : ***/ public String getSelectedDate(String selDate){ try{ String[]sdate = selDate.split(","); int k=1,l=2; if(sdate.length<=2){ k=0; l=1; } String s1=sdate[k].trim(); String[] mmdd = s1.split(" "); String mm=monthToInt(mmdd[0]); String dd ; int idate = Integer.parseInt(mmdd[1]); if(idate<10){ dd="0"+idate; }else{ dd=mmdd[1]; } String s2 = sdate[l].trim(); String yy=s2.substring(2,4); selectedDate = mm+"/"+dd+"/"+yy; Common.testStepInfo("Selected date is : "+selectedDate); }catch (Exception e) { Common.testStepFailed("Exception Caught, Message is->"+e.getMessage()); } return selectedDate; } /*** * Method to converted month name to month value * @param : * @return : void * @author : suntechUser(userId) Modified By : ***/ public String monthToInt(String month){ int i; String mm=""; String months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; for ( i = 0; i < 12; i++) { if (months[i].equalsIgnoreCase(month.trim())) { i=i+1; System.out.println("month is "+i) ; break; } } if(i<10){ mm="0"+i; }else { mm=Integer.toString(i); } return mm; } /**** Method to compare Two Strings * @param : * @return : void * @author : suntechUser(userId) * @Modified By : ****/ public boolean compareTwoStrings(String str1, String str2){ try { if(str1.equalsIgnoreCase(str2)){ return true; }else{ } } catch (Exception e) { Common.testStepFailed("Error occurred while comparing Two Strings --> "+e.getMessage()); } return false; } /**** Method to wait for element not present * @param : * @return : void * @author : suntechUser(userId) * @Modified By : ****/ public void waitForElementNotPresent(MobileElement element)throws Exception{ for (int second = 0;;second ++) { try {// try catch block is used handle 'Permission Denied Error' when waiting for element if (second>=120) { break; //Common.testStepPassed("Element was found after waiting for 2 Minute"); } if (!isElementPresent(element)) { break; } } catch (Exception e) { } } } /**** Method to generate random string * @param : length of string to be generated * @return : void * @author : suntechUser(userId) * @Modified By : ****/ public String generateRandomString(int len, String type){ Random rng = new Random(); String characters=null; if(type.equalsIgnoreCase("numeric")){ characters="1237890456"; } else if(type.equalsIgnoreCase("alpha")){ characters="abcdefghijklmnoNOPQRSTUVWXYZpqrstuvwxyzABCDEFGHIJKLM"; } else if(type.equalsIgnoreCase("alphanumeric")){ characters="abc1238974560defghijklmno1238974560NOPQRSTUVWXYZpqrst1238974560uvwxyz1238974560ABCDEFGHIJ1238974560KLM"; } char[] text = new char[len]; for (int i = 0; i < len; i++) { text[i] = characters.charAt(rng.nextInt(characters.length())); } return new String(text); } public WebElement webElement(String object) { String elementLocator = object;// "xpath>>//input[@name='username']"; By byLocator = null; WebElement element = null; try { String locatorType = elementLocator.split(">>")[0]; String locator = elementLocator.split(">>")[1]; if (locatorType.toLowerCase().contains("xpath")) { byLocator = By.xpath(locator); } else if (locatorType.toLowerCase().contains("css")) { byLocator = By.cssSelector(locator); } else if (locatorType.toLowerCase().contains("id")) { byLocator = By.id(locator); } else if (locatorType.toLowerCase().contains("class")) { byLocator = By.className(locator); } element = browser.findElement(byLocator); } catch (Exception ex) { Common.testStepFailed("Uanble to locate element-" + ex); } return element; } public List<MobileElement> webElements(String object) { String elementLocator = object;// "xpath>>//input[@name='username']"; By byLocator = null; List<MobileElement> elements = null; try { String locatorType = elementLocator.split(">>")[0]; String locator = elementLocator.split(">>")[1]; if (locatorType.toLowerCase().contains("xpath")) { byLocator = By.xpath(locator); } else if (locatorType.toLowerCase().contains("css")) { byLocator = By.cssSelector(locator); } else if (locatorType.toLowerCase().contains("id")) { byLocator = By.id(locator); } else if (locatorType.toLowerCase().contains("class")) { byLocator = By.className(locator); } elements = browser.findElements(byLocator); } catch (Exception ex) { Common.testStepFailed("Uanble to locate element-" + ex); } return elements; } public void waitForPageElementLoad(String object) { try { String elementLocator = object;// "xpath>>//input[@name='username']"; By byLocator = null; String locatorType = elementLocator.split(">>")[0]; String locator = elementLocator.split(">>")[1]; if (locatorType.toLowerCase().contains("xpath")) { byLocator = By.xpath(locator); } else if (locatorType.toLowerCase().contains("css")) { byLocator = By.cssSelector(locator); } else if (locatorType.toLowerCase().contains("id")) { byLocator = By.id(locator); } else if (locatorType.toLowerCase().contains("class")) { byLocator = By.className(locator); } new WebDriverWait(browser, 30).until(ExpectedConditions.presenceOfElementLocated(byLocator)); } catch (Exception e) { System.out.println(e.getMessage()); } } public void alertAccept() { try { WebDriverWait wait = new WebDriverWait(browser, GlobalKeys.elementLoadWaitTime); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = browser.switchTo().alert(); alert.accept(); Common.testStepPassed("Clicked on Alert Ok/Accept successfully"); } catch (Exception ex) { Common.testStepFailed("Unable to Acdept Alert, Error Message is->" + ex.getMessage()); } } public String getText(String object) { String elementLocator = object;// "xpath>>//input[@name='username']"; String elementText = null; By byLocator = null; try { String locatorType = elementLocator.split(">>")[0]; String locator = elementLocator.split(">>")[1]; if (locatorType.toLowerCase().contains("xpath")) { byLocator = By.xpath(locator); } else if (locatorType.toLowerCase().contains("css")) { byLocator = By.cssSelector(locator); } else if (locatorType.toLowerCase().contains("id")) { byLocator = By.id(locator); } else if (locatorType.toLowerCase().contains("class")) { byLocator = By.className(locator); } elementText = browser.findElement(byLocator).getText().trim(); } catch (Exception e) { Common.testStepFailed(e.toString()); } return elementText; } public void clickOnTableItem(WebElement tbl,int keyColIndex,String keyColValue,int selectColumnIndex){ try { List<WebElement> rows = tbl.findElements(By.tagName("tr")); int rowCount = rows.size(); for(int i=0;i<=rowCount;i++){ rows = tbl.findElements(By.tagName("tr")); String rowValue = rows.get(i).getText(); if(rowValue.contains(keyColValue)){ } } } catch (Exception e) { Common.testStepFailed("Exception caught->"+e.getMessage()); } } public void clickElementWithEnterKey(WebElement we, String clickedElement) { try { waitForElement(we); if (isElementPresent(we)) { /*Actions actions = new Actions(browser); actions.moveToElement(we).build().perform();*/ we.sendKeys(Keys.TAB); we.sendKeys(Keys.ENTER); Common.testStepPassed("Clicked on MobileElement-" + clickedElement); } else { Common.testStepFailed(clickedElement + " Element is not displayed"); } } catch (Exception e) { Common.testStepFailed("Error Occurred While Clicking"+clickedElement+" in clickElementWithEnterKey -->"+e.getMessage()); } } public void tap(WebElement we){ try{ TouchActions action = new TouchActions(browser); action.singleTap(we).perform(); }catch(Exception ex){ Common.testStepFailed("Exception caught "+ex.getMessage()); } } public void doubletap(WebElement we){ try{ TouchActions action = new TouchActions(browser); action.doubleTap(we).perform(); }catch(Exception ex){ Common.testStepFailed("Exception caught "+ex.getMessage()); } } public void movedown(){ try{ TouchActions action = new TouchActions(browser); action.down(10, 10); action.move(50, 50); action.perform(); }catch(Exception ex){ Common.testStepFailed("Exception caught "+ex.getMessage()); } } public void moveup(){ try{ TouchActions action = new TouchActions(browser); action.down(10, 10); action.move(50, 50); action.perform(); }catch(Exception ex){ Common.testStepFailed("Exception caught "+ex.getMessage()); } } public void longpress(WebElement we){ try{ TouchActions action = new TouchActions(browser); action.longPress(we); action.perform(); }catch(Exception ex){ Common.testStepFailed("Exception caught "+ex.getMessage()); } } public void scroll(WebElement we){ try{ TouchActions action = new TouchActions(browser); action.scroll(we, 10, 100); action.perform(); }catch(Exception ex){ Common.testStepFailed("Exception caught "+ex.getMessage()); } } public void flick(){ try{ TouchActions action = new TouchActions(browser); action.down(10, 10); action.move(50, 50); action.perform(); }catch(Exception ex){ Common.testStepFailed("Exception caught "+ex.getMessage()); } } }
package org.incredible.certProcessor; import org.incredible.builders.*; import org.incredible.certProcessor.CertModel; import org.incredible.certProcessor.signature.SignatureHelper; import org.incredible.pojos.CertificateExtension; import org.incredible.pojos.RankAssessment; import org.incredible.pojos.ob.Criteria; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.HashMap; import java.util.Properties; import java.util.UUID; import org.incredible.pojos.ob.VerificationObject; import org.incredible.pojos.ob.exeptions.InvalidDateFormatException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CertificateFactory { private static String uuid; private static Logger logger = LoggerFactory.getLogger(CertificateFactory.class); final String resourceName = "application.properties"; private static SignatureHelper signatureHelper; public CertificateExtension createCertificate(CertModel certModel, String context, HashMap<String, String> properties) throws InvalidDateFormatException { uuid = properties.get("DOMAIN_PATH") + UUID.randomUUID().toString(); CertificateExtensionBuilder certificateExtensionBuilder = new CertificateExtensionBuilder(context); CompositeIdentityObjectBuilder compositeIdentityObjectBuilder = new CompositeIdentityObjectBuilder(context); BadgeClassBuilder badgeClassBuilder = new BadgeClassBuilder(context); AssessedEvidenceBuilder assessedEvidenceBuilder = new AssessedEvidenceBuilder(properties.get("ASSESSED_DOMAIN")); IssuerBuilder issuerBuilder = new IssuerBuilder(context); SignatureBuilder signatureBuilder = new SignatureBuilder(); Criteria criteria = new Criteria(); criteria.setNarrative("For exhibiting outstanding performance"); criteria.setId(uuid); RankAssessment rankAssessment = new RankAssessment(); rankAssessment.setValue(8); rankAssessment.setMaxValue(1); //todo decide hosted or signed badge based on config String[] type = new String[]{properties.get("VERIFICATION_TYPE")}; VerificationObject verificationObject = new VerificationObject(); verificationObject.setType(type); /** * recipent object * **/ compositeIdentityObjectBuilder.setName(certModel.getRecipientName()).setId(certModel.getRecipientPhone()) .setHashed(false). setType(new String[]{"phone"}); issuerBuilder.setId(properties.get("ISSUER_URL")).setName(certModel.getIssuer().getName()); /** * badge class object * **/ badgeClassBuilder.setName(certModel.getCourseName()).setDescription(certModel.getCertificateDescription()) .setId(properties.get("BADGE_URL")).setCriteria(criteria) .setImage(certModel.getCertificateLogo()). setIssuer(issuerBuilder.build()); /** * assessed evidence object **/ AssessmentBuilder assessmentBuilder = new AssessmentBuilder(context); assessmentBuilder.setValue(21); assessedEvidenceBuilder.setAssessedBy("https://dgt.example.gov.in/iti-assessor.json").setId(uuid) .setAssessedOn(certModel.getAssessedOn()).setAssessment(assessmentBuilder.build()); /** * * Certificate extension object */ certificateExtensionBuilder.setId(uuid).setRecipient(compositeIdentityObjectBuilder.build()) .setBadge(badgeClassBuilder.build()).setEvidence(assessedEvidenceBuilder.build()) .setIssuedOn(certModel.getIssuedDate()).setExpires(certModel.getExpiry()) .setValidFrom(certModel.getValidFrom()).setVerification(verificationObject); // /** // * to assign signature value // */ // initSignatureHelper(certModel.getSignatoryList()); // /** certificate before signature value **/ // String toSignCertificate = certificateExtensionBuilder.build().toString(); // // String signatureValue = getSignatureValue(toSignCertificate); // // signatureBuilder.setCreated(Instant.now().toString()).setCreator("https://dgt.example.gov.in/keys/awarding_body.json") // .setSignatureValue(signatureValue); // certificateExtensionBuilder.setSignature(signatureBuilder.build()); // // logger.info("signed certificate is valid {}", verifySignature(toSignCertificate, signatureValue)); logger.info("certificate extension => {}", certificateExtensionBuilder.build()); return certificateExtensionBuilder.build(); } public Properties readPropertiesFile() { ClassLoader loader = CertificateFactory.class.getClassLoader(); Properties properties = new Properties(); try (InputStream resourceStream = loader.getResourceAsStream(resourceName)) { properties.load(resourceStream); } catch (IOException e) { e.printStackTrace(); logger.info("Exception while reading application.properties {}", e.getMessage()); } return properties; } public static boolean verifySignature(String certificate, String signatureValue) { boolean isValid = false; try { isValid = signatureHelper.verify(certificate.getBytes(), signatureValue); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } return isValid; } private static void initSignatureHelper(KeyPair keyPair) { try { signatureHelper = new SignatureHelper("SHA1withRSA", keyPair); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } private static String getSignatureValue(String toSignCertificate) { try { String signatureValue = signatureHelper.sign(toSignCertificate.getBytes()); return signatureValue; } catch (SignatureException | UnsupportedEncodingException | InvalidKeyException e) { e.printStackTrace(); return null; } } }
/** */ package MindmapDSL.impl; import MindmapDSL.*; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class MindmapDSLFactoryImpl extends EFactoryImpl implements MindmapDSLFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static MindmapDSLFactory init() { try { MindmapDSLFactory theMindmapDSLFactory = (MindmapDSLFactory)EPackage.Registry.INSTANCE.getEFactory("http://spray.eclipselabs.org/examples/Mindmap"); if (theMindmapDSLFactory != null) { return theMindmapDSLFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MindmapDSLFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MindmapDSLFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MindmapDSLPackage.NAMED_ELEMENT: return createNamedElement(); case MindmapDSLPackage.MINDMAP: return createMindmap(); case MindmapDSLPackage.MAP_ELEMENTS: return createMapElements(); case MindmapDSLPackage.START_ELEMENT: return createStartElement(); case MindmapDSLPackage.ELEMENT: return createElement(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NamedElement createNamedElement() { NamedElementImpl namedElement = new NamedElementImpl(); return namedElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Mindmap createMindmap() { MindmapImpl mindmap = new MindmapImpl(); return mindmap; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MapElements createMapElements() { MapElementsImpl mapElements = new MapElementsImpl(); return mapElements; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StartElement createStartElement() { StartElementImpl startElement = new StartElementImpl(); return startElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Element createElement() { ElementImpl element = new ElementImpl(); return element; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MindmapDSLPackage getMindmapDSLPackage() { return (MindmapDSLPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static MindmapDSLPackage getPackage() { return MindmapDSLPackage.eINSTANCE; } } //MindmapDSLFactoryImpl
/* * 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 users; import repository.UserRepository; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.faces.application.FacesMessage; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import javax.faces.context.FacesContext; import repository.StatusAndPhotosRepository; /** * * @author Elif */ @ManagedBean(name = "user") @ApplicationScoped public class User { String firstName; String lastName; String email; String phoneNumber; String password; String gender; String status; String nickname; String live; public String getLive() { return live; } public void setLive(String live) { this.live = live; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User() { } public User(String firstName, String lastName, String email, String phoneNumber, String password, String gender, String nickname) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.phoneNumber = phoneNumber; this.password = password; this.gender = gender; this.nickname = nickname; } public User(String firstName, String lastName, String nickname) { this.firstName = firstName; this.lastName = lastName; this.nickname = nickname; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String register() { if (new UserRepository().save(this) == true) { new StatusAndPhotosRepository().uploadProfilePhoto_db("C:\\dev\\nypProje\\web\\resources\\profilePhotos\\nonPic.png", new UserRepository().findUserId(this.email)); return "loginPage?faces-redirect=true"; } else { return "registerPage?faces-redirect=true"; } } public String login() { UserRepository ur = new UserRepository(); ArrayList<User> users = ur.getUsersfromTable(); for (User user : users) { if ((user.email).equals(this.email)) { if ((user.password).equals(this.password)) { return "mainPage?faces-redirect=true"; } } } FacesMessage msg = new FacesMessage("E-mail or password is wrong, please enter again!", "ERROR MSG"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); FacesContext.getCurrentInstance().addMessage(null, msg); return "loginPage?faces-redirect=true"; } public void deleteStatusAndPhotos() { int id = new UserRepository().findUserId(email); if (new UserRepository().delete_database_statusAndPhotos(id)) { return; } else { FacesMessage msg = new FacesMessage("Your status is not deleted !", "ERROR MSG"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); FacesContext.getCurrentInstance().addMessage(null, msg); } } public void deleteProfilePhoto() { int userId = new UserRepository().findUserId(this.email); if (new StatusAndPhotosRepository().delete_profilePhoto(userId)) { FacesMessage msg = new FacesMessage("The photo is deleted, successfuly !", "ERROR MSG"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); FacesContext.getCurrentInstance().addMessage(null, msg); } } public String deleteAccount() { UserRepository ur = new UserRepository(); if (ur.deleteAccount(this) == true) { deleteStatusAndPhotos(); deleteInfo(); deleteProfilePhoto(); return "loginPage?faces-redirect=true"; } else { return null; } } public String returnChangePasswordPage() { return "changePasswordPage?faces-redirect=true"; } public ArrayList<User> getUsersList() { return (new UserRepository().getUsersfromTable()); } /* public ArrayList<String> getStatusList(){ return(new UserRepository().getStatusList()); } */ public String changePassword() { UserRepository ur = new UserRepository(); if (ur.changePassword(this) == true) { return "mainPage?faces-redirect=true"; } else { return "changePasswordPage?faces-redirect=true"; } } public void save_status() { int id = new UserRepository().findUserId(getEmail()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date timeDate = new Date(); String s_timeDate = dateFormat.format(timeDate); if (new UserRepository().save_database_status(id, status, s_timeDate)) { return; } else { FacesMessage msg = new FacesMessage("You cannot share empty status !", "ERROR MSG"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); FacesContext.getCurrentInstance().addMessage(null, msg); } } public String information(String a) { UserRepository ur = new UserRepository(); return (ur.getInformation(this, a)); } public void deleteInfo() { if (new UserRepository().deleteInformation(new UserRepository().findUserId(email))) { return; } else { System.out.println("silinemdi"); } } public ArrayList<User> getNotifications(String email) { UserRepository ur = new UserRepository(); ArrayList<User> users = ur.getFollowersFromTable(email); ArrayList<User> reverseusers = new ArrayList<>(); for (int i = users.size() - 1; i >= 0; i--) { reverseusers.add(users.get(i)); } return reverseusers; } public ArrayList<User> getUsersToUni(String email) { ArrayList<User> users = new UserRepository().getUserToUniversity(email); return users; } public ArrayList<User> getUsersToHighSch(String email) { ArrayList<User> users = new UserRepository().getUserToHighschool(email); return users; } public String showUserInfo() { User us = new UserRepository().getUser(this.email); this.firstName = us.getFirstName(); this.lastName = us.getLastName(); this.gender = us.getGender(); this.nickname = us.getNickname(); this.phoneNumber = us.getPhoneNumber(); return "userInfo"; } public ArrayList<User> getFollowing(String email) { UserRepository ur = new UserRepository(); ArrayList<User> users = ur.getFollowingFromTable(email); return users; } public ArrayList<User> getFollowers(String email) { UserRepository ur = new UserRepository(); ArrayList<User> users = ur.getFollowersFromTable(email); return users; } }
package com.Xls2Json.model; public class RMOD { String mrbtsid; String rModId; String prodCode; String moduleLocation; String climateControlProfiling; public String getMrbtsid() { return mrbtsid; } public void setMrbtsid(String string) { this.mrbtsid = string; } public String getrModId() { return rModId; } public void setrModId(String rModId) { this.rModId = rModId; } public String getProdCode() { return prodCode; } public void setProdCode(String prodCode) { this.prodCode = prodCode; } public String getModuleLocation() { return moduleLocation; } public void setModuleLocation(String moduleLocation) { this.moduleLocation = moduleLocation; } @Override public String toString() { return "RMOD [mrbtsid=" + mrbtsid + ", rModId=" + rModId + ", prodCode=" + prodCode + ", moduleLocation=" + moduleLocation + ", climateControlProfiling=" + climateControlProfiling + "]"; } public String getClimateControlProfiling() { return climateControlProfiling; } public void setClimateControlProfiling(String climateControlProfiling) { this.climateControlProfiling = climateControlProfiling; } }
package objects.forms; public class NewUserForm { String login; String password; String email; public String getLogin() { return login; } public String getPassword() { return password; } public String getEmail() { return email; } }
package com.example.ahmed.octopusmart.View.Widget; import android.content.Context; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.Transformation; import android.widget.Scroller; import java.lang.reflect.Field; public class WrapContentWithAnimationViewPager extends ViewPager { private Boolean mAnimStarted = false; public WrapContentWithAnimationViewPager(Context context) { super(context); setMyScroller(); } public WrapContentWithAnimationViewPager(Context context, AttributeSet attrs) { super(context, attrs); setMyScroller(); } // // @Override // public boolean onInterceptTouchEvent(MotionEvent event) { // // Never allow swiping to switch between pages // return false; // } // // @Override // public boolean onTouchEvent(MotionEvent event) { // // Never allow swiping to switch between pages // return true; // } //down one is added for smooth scrolling private void setMyScroller() { try { Class<?> viewpager = ViewPager.class; Field scroller = viewpager.getDeclaredField("mScroller"); scroller.setAccessible(true); scroller.set(this, new MyScroller(getContext())); } catch (Exception e) { e.printStackTrace(); } } public class MyScroller extends Scroller { public MyScroller(Context context) { super(context, new DecelerateInterpolator()); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duration) { super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/); } } private int mCurrentPagePosition = 0; private boolean inti_pos =true; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Log.e("no_swip_pa", inti_pos +" " + mCurrentPagePosition + " " + mAnimStarted) ; if (mCurrentPagePosition ==0 && inti_pos ){ View child = getChildAt(mCurrentPagePosition); if (child != null) { child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int h = child.getMeasuredHeight(); heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY); } } if (mCurrentPagePosition != 0 ) inti_pos = false ; super.onMeasure(widthMeasureSpec, heightMeasureSpec); if(!mAnimStarted && null != getAdapter()) { int height = 0; View child = ((FragmentPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView(); if (child != null) { child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); height = child.getMeasuredHeight(); if (height < getMinimumHeight()) { height = getMinimumHeight(); } } // Not the best place to put this animation, but it works pretty good. int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) { final int targetHeight = height; final int currentHeight = getLayoutParams().height; final int heightChange = targetHeight - currentHeight; Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if (interpolatedTime >= 1) { getLayoutParams().height = targetHeight; } else { int stepHeight = (int) (heightChange * interpolatedTime); getLayoutParams().height = currentHeight + stepHeight; } requestLayout(); } @Override public boolean willChangeBounds() { return true; } }; a.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mAnimStarted = true; } @Override public void onAnimationEnd(Animation animation) { mAnimStarted = false; } @Override public void onAnimationRepeat(Animation animation) { } }); a.setDuration(1000); startAnimation(a); mAnimStarted = true; } else { heightMeasureSpec = newHeight; } } } public void reMeasureCurrentPage(int position) { mCurrentPagePosition = position; requestLayout(); } }
package com.libedi.jpa.compositekey.identify; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * ChildId : 자식 ID 식별자 클래스 * * @author Sang-jun, Park * @since 2019. 05. 29 */ @Embeddable @NoArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor @EqualsAndHashCode public class ChildId_Identity_EmbeddedId implements Serializable { private static final long serialVersionUID = -4522688475693289929L; private String parentId; // 부모 엔티티의 PK에 해당. @MapsId("parentId") 로 매핑. @Column(name = "CHILD_ID") private String id; }
package com.shopping.li.shopping.logUtil; import android.util.Log; /** * Created by li on 2018/2/23. */ public class LogUtil { public static boolean showlog=true; public static final int VERBOSE = 1; public static final int DEBUG = 2; public static final int INFO = 3; public static final int WARN = 4; public static final int ERROR = 5; public static final int NOTHING = 6; public static int level =VERBOSE ; public static void v(String tag,String msg){ if (showlog && (level<=VERBOSE)){ Log.v(tag,msg); } } public static void d(String tag,String msg){ if (showlog && (level<=VERBOSE)){ Log.d(tag,msg); } } public static void i(String tag,String msg){ if (showlog && (level<=VERBOSE)){ Log.i(tag,msg); } } public static void w(String tag,String msg){ if (showlog && (level<=VERBOSE)){ Log.w(tag,msg); } } public static void e(String tag,String msg){ if (showlog && (level<=VERBOSE)){ Log.e(tag,msg); } } }
package br.com.sciensa.corujaoapi.endpoints; import java.text.Normalizer; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.threeten.bp.OffsetDateTime; import br.com.sciensa.corujaoapi.model.Movie; import br.com.sciensa.corujaoapi.repository.MovieRepository; @RestController @RequestMapping("v1") public class MovieEndPoint { @Autowired MovieRepository repository; @Autowired MovieRepository movieRepository; @PostMapping(value = "/movies") public ResponseEntity<Movie> addMovie(@Valid @RequestBody Movie movie){ movie = addCreatedAndUpdated(movie); return new ResponseEntity<Movie>(repository.save(movie), HttpStatus.CREATED); }; @GetMapping(value = "/movies/{movieId}") public ResponseEntity<Optional<Movie>> getMovie(@PathVariable("movieId") Long movieId){ return new ResponseEntity<Optional<Movie>>(repository.findById(movieId), HttpStatus.OK); }; @GetMapping(value = "/movies") public ResponseEntity<Page<Movie>> listMovies(@Valid @RequestParam(value = "page", required = false, defaultValue="1") Integer page, @Valid @RequestParam(value = "size", required = false, defaultValue="10") Integer size, @Valid @RequestParam(value = "search", required = false) String search, Pageable pageable){ if(search != null) { return searchTitle(search, pageable); } return new ResponseEntity<Page<Movie>>(repository.findAll(pageable), HttpStatus.OK); }; @PutMapping(value = "/movies/{movieId}") public ResponseEntity<?> updateMovie(@PathVariable("movieId") Long movieId, @Valid @RequestBody Movie movie){ return new ResponseEntity<Movie>(update(movieId, movie), HttpStatus.CREATED); }; @DeleteMapping(value = "/movies/{movieId}") public ResponseEntity<Movie> removeMovie(@PathVariable("movieId") Long movieId) { movieRepository.deleteById(movieId); MultiValueMap<String, String> header = new LinkedMultiValueMap<String, String>(); header.add("Mensagem", "Filme removido com sucesso"); return new ResponseEntity<Movie>(header, HttpStatus.NO_CONTENT); } private ResponseEntity<Page<Movie>> searchTitle(String search, Pageable pageable) { Iterable<Movie> movies = repository.findAll(); List<Movie> moviesFiltrados = new ArrayList<Movie>(); movies.forEach(movie -> { if (removeAcento(movie.getTitle().toLowerCase()).contains(removeAcento(search.toLowerCase()))) moviesFiltrados.add(movie); }); // convertendo List para page Page<Movie> page = new PageImpl<>(moviesFiltrados, pageable, moviesFiltrados.size()); return new ResponseEntity<Page<Movie>>(page, HttpStatus.OK); } private static String removeAcento(String str) { str = Normalizer.normalize(str, Normalizer.Form.NFD); str = str.replaceAll("[^\\p{ASCII}]", ""); return str; } private @Valid Movie addCreatedAndUpdated(@Valid Movie movie) { movie.setCreatedAt(OffsetDateTime.now()); movie.setUpdatedAt(OffsetDateTime.now()); return movie; } private Movie update(Long movieId, Movie movie) { Optional<Movie> movieWillUpdate = repository.findById(movieId); movieWillUpdate.ifPresent(movieOpt -> { movieOpt.setTitle(movie.getTitle()); movieOpt.setReleaseYear(movie.getReleaseYear()); movieOpt.setGenres(movie.getGenres()); movieOpt.setCast(movie.getCast()); movieOpt.setDirector(movie.getDirector()); movieOpt.setUpdatedAt(OffsetDateTime.now()); }); Movie movieEntity = movieWillUpdate.get(); movieEntity = repository.save(movieEntity); return movieEntity; } }
package com.nearsoft.upiita.api.service; import com.nearsoft.upiita.api.model.Director; import com.nearsoft.upiita.api.repository.DirectorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class DirectorService { @Autowired private DirectorRepository directorRepository; public List<Director> getAll() { return (List<Director>) directorRepository.findAll(); } }
package com.wlc.ds.sort; /** * 希尔排序 * 思想,根据选定步长,将数组划分成几个部分,然后对每个部分进行插入排序, * 之后将排序好的每个部分放回原数组对应位置 * 步长减小,循环调用直到步长为1 * @author lanchun * */ public class ShellSort implements ISort { @Override public void sort(int[] a) { for (int gap = a.length / 2; gap > 0; gap = gap - 2) { shellInsert2(a, gap); } } public void shellInsert2(int[] a,int gap){ int j; for(int i = gap;i < a.length;i++){ int temp = a[i]; for(j = i-gap;j>=0;j-=gap){ if(temp < a[j]){ a[j+gap] = a[j]; }else break; } a[j+gap] = temp; } } }
package com.tongji.android.recorder_app.Model; import java.io.Serializable; import java.util.Date; import java.util.List; /** * Created by 重书 on 2016/6/3. */ public class Habit implements Serializable { public static int TYPE_DATE = 0; public static int TYPE_DURATION = 3; public static int TYPE_DOORNOT = 2; public static int TYPE_DEGREE = 1; public String id; public String habitName; public int score; public int type; public String feature; public boolean isChecked; public Habit(String id, String habitName,int score,int type, String feature) { this.id = id; this.habitName = habitName; this.score = score; this.type=type; this.isChecked= false; this.feature = feature; } @Override public String toString() { return habitName; } }
package com.qgbase.biz.huodong.service; import com.qgbase.biz.huodong.domain.HdUser; import com.qgbase.biz.huodong.repository.HdUserRespository; import com.qgbase.common.TBaseBo; import com.qgbase.common.dao.CommonDao; import com.qgbase.common.domain.OperInfo; import com.qgbase.util.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * Created by Mark on 2019-10-29 * * 主要用于:门店用户 业务处理,此代码为自动生成 */ @Component public class HdUserService extends TBaseBo<HdUser>{ @Autowired CommonDao commonDao; @Autowired HdUserRespository hdUserRespository; @Override public HdUser createObj() { return new HdUser(); } @Override public Class getEntityClass() { return HdUser.class; } @Override public HdUser newObj(OperInfo oper) throws Exception { HdUser obj = super.newObj(oper); //这里对新创建的对象进行初始化 ,比如 obj.setIsUsed(1); //写下你的处理方法 obj.setIsActive(1); return obj; } @Override public String checkAddorUpdate(HdUser obj, OperInfo oper, boolean isNew) throws Exception { //这里对 新增和修改 保存前进行检查,检查失败返回错误信息 //写下你的处理方法 return super.checkAddorUpdate(obj, oper, isNew); } @Override public String checkDelete(HdUser obj, OperInfo oper) throws Exception { //这里对 删除前进行检查,检查失败返回错误信息 //写下你的处理方法 return super.checkDelete(obj, oper); } public HdUser getByWeixinId(String weixinid,OperInfo oper) throws Exception{ return hdUserRespository.getFirstByUserWeixinid(weixinid); } }
package com.podarbetweenus.Activities; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.podarbetweenus.Adapter.MessageAdpater; import com.podarbetweenus.BetweenUsConstant.Constant; import com.podarbetweenus.Entity.DateDropdownValueDetails; import com.podarbetweenus.Entity.LoginDetails; import com.podarbetweenus.Entity.ViewMessageResult; import com.podarbetweenus.R; import com.podarbetweenus.Services.DataFetchService; import com.podarbetweenus.Services.ListResultReceiver; import com.podarbetweenus.Utility.AppController; import com.podarbetweenus.Utility.BadgeView; import com.podarbetweenus.Utility.LoadMoreListView; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; /** * Created by Administrator on 9/28/2015. */ public class ViewMessageActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener,ListResultReceiver.Receiver { //UI variables //EditText EditText ed_select_date; //TextView TextView tv_sender_name,tv_date,tv_msg,tv_no_record; //LinaerLayout LinearLayout lay_back_investment; //ListView ListView list_messages; //ProgressDialog ProgressDialog progressDialog; private ListView listView = null; private ArrayAdapter arrayAdapter = null; BadgeView badge; DataFetchService dft; LoginDetails login_details; MessageAdpater message_adapter; Notification notification; private ListResultReceiver mReceiver; public ArrayList<DateDropdownValueDetails> date_dropdownlist = new ArrayList<DateDropdownValueDetails>(); public ArrayList<ViewMessageResult> message_result = new ArrayList<ViewMessageResult>(); public ArrayList<ViewMessageResult> message_result_loadMore = new ArrayList<ViewMessageResult>(); ArrayList<String> msgStatusList = new ArrayList<String>(); String date,msg,sender_name,msd_ID,clt_id,board_name,usl_id,check="0",versionName,month_id,latest_month_id,latest_month,message,attachment_path,attachment_name, school_name,message_subject,toUslId,pmuId,month_year,msgStatus,announcementCount,behaviourCount,currentmonth,isStudentresource; String url ="http://www.betweenus.in/PODARAPP/PodarApp.svc/GetViewMessageData"; int pageNo= 1,pageSize = 300,preLast,viewmessageListSize,notificationId,msgStatusSize,notificationID = 1; public String Loadmore=""; boolean mHasRequestedMore; boolean isLoading = false; String DropdownMethodName = "GetDateDropdownValue"; String ViewMessageMethodName = "GetViewMessageData"; String LastViewMessageData = "GetLastViewMessageData"; String[] select_date; ArrayList<String> strings_date ; LoadMoreListView list; AlarmManager alarmManager; AlarmReceiver alaram_receiver; ArrayList<ViewMessageResult> results; public static SharedPreferences resultpreLoginData; int versionCode; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.template_expandable_view_message); findViews(); init(); getIntentId(); tv_no_record.setVisibility(View.GONE); list_messages.setVisibility(View.GONE); AppController.LatestMonth_View_Messages = "true"; AppController.dropdownSelected = "false"; onNewIntent(getIntent()); Calendar now = Calendar.getInstance(); Date date = now.getTime(); SimpleDateFormat format = new SimpleDateFormat("M"); currentmonth = format.format(date); if(AppController.LatestMonth_View_Messages.equalsIgnoreCase("true")) { CallDropdownWebservice(msd_ID,clt_id, AppController.Board_name); } AppController.setPendingNotificationsCount(0); } private void registerReceiver() { /*create filter for exact intent what we want from other intent*/ IntentFilter intentFilter =new IntentFilter(AlarmReceiver.ACTION_TEXT_CAPITALIZED); intentFilter.addCategory(Intent.CATEGORY_DEFAULT); /* create new broadcast receiver*/ alaram_receiver=new AlarmReceiver(); /* registering our Broadcast receiver to listen action*/ registerReceiver(alaram_receiver, intentFilter); } public void addBadge(Context context, int count) { Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE"); intent.putExtra("badge_count", count); intent.putExtra("badge_count_package_name", context.getPackageName()); intent.putExtra("badge_count_class_name", this.getClass().getName()); context.sendBroadcast(intent); } private void CallDropdownWebservice(String msd_ID, String clt_id, String board_name) { try { if (dft.isInternetOn() == true) { if (!progressDialog.isShowing()) { progressDialog.show(); } } else { progressDialog.dismiss(); } dft.getdatedeopdown(msd_ID, clt_id, board_name, DropdownMethodName, Request.Method.POST, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } try { login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class); if (login_details.Status.equalsIgnoreCase("1")) { strings_date = new ArrayList<String>(); try { for (int i = 0; i < login_details.DateDropdownValueDetails.size(); i++) { strings_date.add(login_details.DateDropdownValueDetails.get(i).MonthYear.toString()); select_date = new String[strings_date.size()]; select_date = strings_date.toArray(select_date); if (AppController.LatestMonth_View_Messages.equalsIgnoreCase("true")) { latest_month_id = login_details.DateDropdownValueDetails.get(0).monthid; latest_month = login_details.DateDropdownValueDetails.get(0).MonthYear; month_year = login_details.DateDropdownValueDetails.get(i).MonthYear; AppController.month_year = month_year; AppController.month_id = latest_month_id; ViewMessageActivity.Set_Monthid(AppController.month_id, ViewMessageActivity.this); //Webservcie call for View Messages callViewMessagesWebservice(AppController.clt_id, AppController.usl_id, AppController.msd_ID, AppController.month_id, check, "" + pageNo, "" + pageSize); } } } catch (Exception e) { e.printStackTrace(); } selectDate(select_date); AppController.LatestMonth_View_Messages = "false"; } else if (login_details.Status.equalsIgnoreCase("0")) { } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Show error or whatever... Log.d("LoginActivity", "ERROR.._---" + error.getCause()); } }); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onResume() { super.onResume(); try { AppController.school_name = school_name; AppController.Board_name = board_name; AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; Log.e("OnResum", "onResume()"); /* we register BroadcastReceiver here*/ registerReceiver(); if (AppController.dropdownSelected.equalsIgnoreCase("false") & AppController.ListClicked.equalsIgnoreCase("true")) { //Webservcie call for View Messages callViewMessagesWebservice(AppController.clt_id, AppController.usl_id, AppController.msd_ID, AppController.month_id, check, "" + pageNo, "" + pageSize); //CallDropdownWebservice(msd_ID,clt_id,board_name); } else if (AppController.ListClicked.equalsIgnoreCase("true")) { callViewMessagesWebservice(AppController.clt_id, AppController.usl_id, AppController.msd_ID, month_id, check, "" + pageNo, "" + pageSize); } } catch (Exception e){ e.printStackTrace(); } } @Override protected void onPause() { Log.i("onPause", "onPause()"); /* we should unregister BroadcastReceiver here*/ unregisterReceiver(alaram_receiver); super.onPause(); } private void selectDate( final String[] select_date) { try { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); View convertView = (View) inflater.inflate(R.layout.dialog_list, null); alertDialog.setView(convertView); alertDialog.setTitle("Select Month"); final ListView select_list = (ListView) convertView.findViewById(R.id.select_list); alertDialog.setItems(select_date, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { // Do something with the selection ed_select_date.setText(select_date[item]); dialog.dismiss(); String selecteddate = select_date[item]; Log.e("DATE", selecteddate); month_id = getIDfromMonth(selecteddate); AppController.selectedMonth = month_id; Log.e("MONTH _ID", month_id); //Webservcie call for View Messages callViewMessagesWebservice(AppController.clt_id, AppController.usl_id, AppController.msd_ID, month_id, check, "" + pageNo, "" + pageSize); } }); if (AppController.LatestMonth_View_Messages.equalsIgnoreCase("false")) { alertDialog.show(); } } catch (Exception e) { e.printStackTrace(); } } public void callViewMessagesWebservice(String clt_id,String usl_id,String msd_ID,String month_id,String check,String pageNo,String pageSize) { try { if (dft.isInternetOn() == true) { if (!progressDialog.isShowing()) { progressDialog.show(); } } else { progressDialog.dismiss(); } dft.getviewMessages(clt_id, usl_id, msd_ID, month_id, check, pageNo, pageSize, ViewMessageMethodName, Request.Method.POST, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class); if (login_details.Status.equalsIgnoreCase("1")) { if (AppController.dropdownSelected.equalsIgnoreCase("false")) { ed_select_date.setText(latest_month); } tv_no_record.setVisibility(View.GONE); list_messages.setVisibility(View.VISIBLE); setUIData(); if (progressDialog.isShowing()) { progressDialog.dismiss(); } list_messages.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { AppController.SendMessageLayout = "true"; try { if (login_details.ViewMessageResult.get(position).pmu_readunreadstatus.equalsIgnoreCase("1")) { AppController.UnreadMessage = "true"; if (position == 0) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(notificationID); } } else { AppController.UnreadMessage = "false"; } } catch (Exception e) { e.printStackTrace(); } message = login_details.ViewMessageResult.get(position).pmg_Message; attachment_name = login_details.ViewMessageResult.get(position).pmg_file_name; attachment_path = login_details.ViewMessageResult.get(position).pmg_file_path; sender_name = login_details.ViewMessageResult.get(position).Fullname; date = login_details.ViewMessageResult.get(position).pmg_date; message_subject = login_details.ViewMessageResult.get(position).pmg_subject; toUslId = login_details.ViewMessageResult.get(position).usl_ID; pmuId = login_details.ViewMessageResult.get(position).pmu_ID; Intent detail_message = new Intent(ViewMessageActivity.this, DetailMessageActivity.class); Intent intent = getIntent(); String clt_id = intent.getStringExtra("clt_id"); String msd_ID = intent.getStringExtra("msd_ID"); String usl_id = intent.getStringExtra("usl_id"); announcementCount = intent.getStringExtra("annpuncement_count"); behaviourCount = intent.getStringExtra("behaviour_count"); isStudentresource = intent.getStringExtra("isStudentResource"); AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.school_name = school_name; detail_message.putExtra("clt_id", AppController.clt_id); detail_message.putExtra("msd_ID", AppController.msd_ID); detail_message.putExtra("usl_id", AppController.usl_id); detail_message.putExtra("School_name", AppController.school_name); detail_message.putExtra("Message", message); detail_message.putExtra("board_name", AppController.Board_name); detail_message.putExtra("Attachment Name", attachment_name); detail_message.putExtra("Attachment Path", attachment_path); detail_message.putExtra("Sender Name", sender_name); detail_message.putExtra("Date", date); detail_message.putExtra("Message Subject", message_subject); detail_message.putExtra("ToUslId", toUslId); detail_message.putExtra("version_name", AppController.versionName); detail_message.putExtra("annpuncement_count", announcementCount); detail_message.putExtra("behaviour_count", behaviourCount); detail_message.putExtra("PmuId", pmuId); detail_message.putExtra("isStudentResource", isStudentresource); startActivity(detail_message); } }); } else if (login_details.Status.equalsIgnoreCase("0")) { if (AppController.dropdownSelected.equalsIgnoreCase("true")) { tv_no_record.setText("No Records Found"); tv_no_record.setVisibility(View.VISIBLE); list_messages.setVisibility(View.GONE); } else if (AppController.dropdownSelected.equalsIgnoreCase("false")) { //call top10 records webservice String check = "0", pageNo = "1", pageSize = "300"; callLastViewMessagesWebservice(AppController.clt_id, AppController.usl_id, AppController.msd_ID, AppController.month_id, check, "" + pageNo, "" + pageSize); } } if (AppController.dropdownSelected.equalsIgnoreCase("true") || AppController.SentEnterDropdown.equalsIgnoreCase("true")) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Show error or whatever... Log.d("LoginActivity", "ERROR.._---" + error.getCause()); } }); } catch (Exception e) { e.printStackTrace(); } } private void setUIData() { if (progressDialog.isShowing()) { progressDialog.show(); } viewmessageListSize= login_details.ViewMessageResult.size(); if(AppController.dropdownSelected.equalsIgnoreCase("false")){ Log.e("ViewMessage List Size", String.valueOf(viewmessageListSize)); AppController.viewMessageListSize = viewmessageListSize; // AppController.Notification_send = "true"; } message_result_loadMore = login_details.ViewMessageResult; message_adapter = new MessageAdpater(ViewMessageActivity.this, message_result_loadMore,notificationId); list_messages.setAdapter(message_adapter); } public void callLastViewMessagesWebservice(String clt_id,String usl_id,String msd_ID,String month_id,String check,String pageNo,String pageSize) { try { if (dft.isInternetOn() == true) { if (!progressDialog.isShowing()) { progressDialog.show(); } } else { progressDialog.dismiss(); } dft.getviewMessages(clt_id, usl_id, msd_ID, month_id, check, pageNo, pageSize, LastViewMessageData, Request.Method.POST, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class); tv_no_record.setText("Loading..."); if (login_details.Status.equalsIgnoreCase("1")) { tv_no_record.setVisibility(View.GONE); list_messages.setVisibility(View.VISIBLE); // ViewMessageActivity.this.getListView().setVisibility(View.VISIBLE); setUIData(); if (progressDialog.isShowing()) { progressDialog.dismiss(); } list_messages.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { AppController.SendMessageLayout = "true"; if (login_details.ViewMessageResult.get(position).pmu_readunreadstatus.equalsIgnoreCase("1")) { AppController.UnreadMessage = "true"; if (position == 0) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(notificationID); } } else { AppController.UnreadMessage = "false"; } message = login_details.ViewMessageResult.get(position).pmg_Message; attachment_name = login_details.ViewMessageResult.get(position).pmg_file_name; attachment_path = login_details.ViewMessageResult.get(position).pmg_file_path; sender_name = login_details.ViewMessageResult.get(position).Fullname; date = login_details.ViewMessageResult.get(position).pmg_date; message_subject = login_details.ViewMessageResult.get(position).pmg_subject; toUslId = login_details.ViewMessageResult.get(position).usl_ID; pmuId = login_details.ViewMessageResult.get(position).pmu_ID; Intent detail_message = new Intent(ViewMessageActivity.this, DetailMessageActivity.class); Intent intent = getIntent(); String clt_id = intent.getStringExtra("clt_id"); String msd_ID = intent.getStringExtra("msd_ID"); String usl_id = intent.getStringExtra("usl_id"); announcementCount = intent.getStringExtra("annpuncement_count"); behaviourCount = intent.getStringExtra("behaviour_count"); isStudentresource = intent.getStringExtra("isStudentResource"); AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.school_name = school_name; detail_message.putExtra("clt_id", AppController.clt_id); detail_message.putExtra("msd_ID", AppController.msd_ID); detail_message.putExtra("usl_id", AppController.usl_id); detail_message.putExtra("School_name", AppController.school_name); detail_message.putExtra("Message", message); detail_message.putExtra("Attachment Name", attachment_name); detail_message.putExtra("Attachment Path", attachment_path); detail_message.putExtra("Sender Name", sender_name); detail_message.putExtra("Date", date); detail_message.putExtra("isStudentResource", isStudentresource); detail_message.putExtra("Message Subject", message_subject); detail_message.putExtra("ToUslId", toUslId); detail_message.putExtra("annpuncement_count", announcementCount); detail_message.putExtra("behaviour_count", behaviourCount); detail_message.putExtra("board_name", AppController.Board_name); detail_message.putExtra("PmuId", pmuId); detail_message.putExtra("version_name", AppController.versionName); startActivity(detail_message); } catch (Exception e) { e.printStackTrace(); } } }); } else if (login_details.Status.equalsIgnoreCase("0")) { tv_no_record.setVisibility(View.VISIBLE); list_messages.setVisibility(View.GONE); tv_no_record.setText("No Records Found"); } if (AppController.dropdownSelected.equalsIgnoreCase("false") || AppController.SentEnterDropdown.equalsIgnoreCase("true")) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } } else if (AppController.dropdownSelected.equalsIgnoreCase("false") || AppController.SentEnterDropdown.equalsIgnoreCase("false")) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Show error or whatever... Log.d("LoginActivity", "ERROR.._---" + error.getCause()); } }); } catch (Exception e) { e.printStackTrace(); } } private String getIDfromMonth(String selecteddate) { String id = "0"; for(int i=0;i<login_details.DateDropdownValueDetails.size();i++) { if(login_details.DateDropdownValueDetails.get(i).MonthYear.equalsIgnoreCase(selecteddate)){ id= login_details.DateDropdownValueDetails.get(i).monthid; latest_month_id = null; } } return id; } @Override public void onNewIntent(Intent intent) { Bundle extras = intent.getExtras(); extras.containsKey("clt_id"); extras.containsKey("msd_ID"); extras.containsKey("usl_id"); extras.containsKey("board_name"); clt_id = extras.getString("clt_id"); msd_ID = extras.getString("msd_ID"); usl_id = extras.getString("usl_id"); board_name = extras.getString("board_name"); AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.Board_name = board_name; } private void findViews() { //EditTExt ed_select_date = (EditText) findViewById(R.id.ed_select_date); //TextView tv_sender_name = (TextView) findViewById(R.id.tv_sender_name); tv_msg = (TextView) findViewById(R.id.tv_msg); tv_date = (TextView) findViewById(R.id.tv_date); tv_no_record = (TextView) findViewById(R.id.tv_no_record); //ListView list_messages = (ListView) findViewById(R.id.list_messages); } private void getIntentId(){ Intent intent = getIntent(); board_name = intent.getStringExtra("board_name"); clt_id = intent.getStringExtra("clt_id"); msd_ID = intent.getStringExtra("msd_ID"); usl_id = intent.getStringExtra("usl_id"); school_name = intent.getStringExtra("School_name"); versionName = intent.getStringExtra("version_name"); versionCode = intent.getIntExtra("version_code", 0); announcementCount = intent.getStringExtra("annpuncement_count"); behaviourCount = intent.getStringExtra("behaviour_count"); isStudentresource = intent.getStringExtra("isStudentResource"); AppController.versionName = versionName; AppController.versionCode = versionCode; AppController.dropdownSelected = intent.getStringExtra("DropDownSelected"); AppController.school_name = school_name; AppController.Board_name = board_name; AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; Bundle bundle=intent.getExtras(); results = (ArrayList<ViewMessageResult>)bundle.getSerializable("results"); notificationId = getIntent().getExtras().getInt("notificationID"); Log.e("Notification id_Dash...",String.valueOf(notificationId)); } private void init(){ dft = new DataFetchService(this); login_details = new LoginDetails(); progressDialog = Constant.getProgressDialog(this); ed_select_date.setOnClickListener(this); } @Override public void onClick(View v) { try { if (v == ed_select_date) { AppController.dropdownSelected = "true"; CallDropdownWebservice(msd_ID, clt_id, AppController.Board_name); } else if (v == lay_back_investment) { if (AppController.SiblingActivity.equalsIgnoreCase("true")) { Intent back = new Intent(ViewMessageActivity.this, Profile_Sibling.class); AppController.OnBackpressed = "false"; AppController.parentMessageSent = "false"; AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.school_name = school_name; AppController.Board_name = board_name; back.putExtra("clt_id", AppController.clt_id); back.putExtra("msd_ID", AppController.msd_ID); back.putExtra("usl_id", AppController.usl_id); back.putExtra("School_name", AppController.school_name); back.putExtra("board_name", AppController.Board_name); back.putExtra("version_name", AppController.versionName); back.putExtra("verion_code", AppController.versionCode); back.putExtra("isStudentResource", isStudentresource); startActivity(back); } else { Intent back = new Intent(ViewMessageActivity.this, ProfileActivity.class); AppController.OnBackpressed = "false"; AppController.parentMessageSent = "false"; AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.school_name = school_name; AppController.Board_name = board_name; back.putExtra("clt_id", AppController.clt_id); back.putExtra("msd_ID", AppController.msd_ID); back.putExtra("usl_id", AppController.usl_id); back.putExtra("School_name", AppController.school_name); back.putExtra("board_name", AppController.Board_name); back.putExtra("version_name", AppController.versionName); back.putExtra("verion_code", AppController.versionCode); back.putExtra("isStudentResource", isStudentresource); startActivity(back); } } } catch (Exception e){ e.printStackTrace(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { AppController.ListClicked = "true"; AppController.SendMessageLayout = "true"; if(login_details.ViewMessageResult.get(position).pmu_readunreadstatus.equalsIgnoreCase("1")){ AppController.UnreadMessage = "true"; if(position==0) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(notificationID); } } else{ AppController.UnreadMessage = "false"; } message = login_details.ViewMessageResult.get(position).pmg_Message; attachment_name = login_details.ViewMessageResult.get(position).pmg_file_name; attachment_path = login_details.ViewMessageResult.get(position).pmg_file_path; sender_name = login_details.ViewMessageResult.get(position).Fullname; date = login_details.ViewMessageResult.get(position).pmg_date; message_subject = login_details.ViewMessageResult.get(position).pmg_subject; toUslId = login_details.ViewMessageResult.get(position).usl_ID; pmuId = login_details.ViewMessageResult.get(position).pmu_ID; Intent detail_message = new Intent(ViewMessageActivity.this, DetailMessageActivity.class); Intent intent = getIntent(); String clt_id = intent.getStringExtra("clt_id"); String msd_ID = intent.getStringExtra("msd_ID"); String usl_id = intent.getStringExtra("usl_id"); announcementCount = intent.getStringExtra("annpuncement_count"); behaviourCount = intent.getStringExtra("behaviour_count"); isStudentresource = intent.getStringExtra("isStudentResource"); AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.school_name = school_name; detail_message.putExtra("clt_id", AppController.clt_id); detail_message.putExtra("msd_ID", AppController.msd_ID); detail_message.putExtra("usl_id", AppController.usl_id); detail_message.putExtra("School_name", AppController.school_name); detail_message.putExtra("board_name", AppController.Board_name); detail_message.putExtra("Message", message); detail_message.putExtra("isStudentResource",isStudentresource); detail_message.putExtra("Attachment Name", attachment_name); detail_message.putExtra("Attachment Path", attachment_path); detail_message.putExtra("Sender Name", sender_name); detail_message.putExtra("Date", date); detail_message.putExtra("Message Subject",message_subject); detail_message.putExtra("ToUslId",toUslId); detail_message.putExtra("annpuncement_count",announcementCount); detail_message.putExtra("behaviour_count",behaviourCount); detail_message.putExtra("version_name", AppController.versionName); detail_message.putExtra("verion_code", AppController.versionCode); detail_message.putExtra("PmuId",pmuId); startActivity(detail_message); } catch (Exception e) { e.printStackTrace(); } } public static void Set_Monthid(String month_id,Context context) { resultpreLoginData = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = resultpreLoginData.edit(); editor.putString("Month", month_id); editor.commit(); } public static String get_MonthId(Context context){ resultpreLoginData = PreferenceManager.getDefaultSharedPreferences(context); Log.e("LoginActivity", resultpreLoginData.getString("Month", "")); return resultpreLoginData.getString("Month", ""); } @Override public void onBackPressed() { super.onBackPressed(); try { if (AppController.SiblingActivity.equalsIgnoreCase("true")) { Intent back = new Intent(ViewMessageActivity.this, Profile_Sibling.class); AppController.OnBackpressed = "false"; AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.school_name = school_name; AppController.Board_name = board_name; AppController.parentMessageSent = "false"; back.putExtra("clt_id", AppController.clt_id); back.putExtra("msd_ID", AppController.msd_ID); back.putExtra("usl_id", AppController.usl_id); back.putExtra("board_name", AppController.Board_name); back.putExtra("School_name", AppController.school_name); back.putExtra("version_name", AppController.versionName); back.putExtra("verion_code", AppController.versionCode); back.putExtra("isStudentResource", isStudentresource); startActivity(back); } else { Intent back = new Intent(ViewMessageActivity.this, ProfileActivity.class); AppController.OnBackpressed = "false"; AppController.parentMessageSent = "false"; AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.Board_name = board_name; AppController.school_name = school_name; back.putExtra("clt_id", AppController.clt_id); back.putExtra("msd_ID", AppController.msd_ID); back.putExtra("usl_id", AppController.usl_id); back.putExtra("board_name", AppController.Board_name); back.putExtra("School_name", AppController.school_name); back.putExtra("version_name", AppController.versionName); back.putExtra("verion_code", AppController.versionCode); back.putExtra("isStudentResource", isStudentresource); startActivity(back); } // finish(); } catch (Exception e){ e.printStackTrace(); } } @Override public void onReceiveResult(int resultCode, Bundle resultData) { } public class AlarmReceiver extends BroadcastReceiver { /** * action string for our broadcast receiver to get notified */ public final static String ACTION_TEXT_CAPITALIZED = "com.android.guide.exampleintentservice.intent.action.ACTION_TEXT_CAPITALIZED"; @Override public void onReceive(Context context, Intent intent) { /// AppController.Notification_send = "true"; try { Bundle bundle = intent.getExtras(); results = (ArrayList<ViewMessageResult>) bundle.getSerializable("results"); viewmessageListSize = AppController.results.size(); AppController.viewMessageListSize = viewmessageListSize; if (latest_month_id.equalsIgnoreCase(currentmonth)) { ed_select_date.setText(latest_month); message_adapter = new MessageAdpater(ViewMessageActivity.this, AppController.results, notificationId); list_messages.setAdapter(message_adapter); } else if (!month_id.equalsIgnoreCase(currentmonth)) { message_adapter = new MessageAdpater(ViewMessageActivity.this, login_details.ViewMessageResult, notificationId); list_messages.setAdapter(message_adapter); } else if (month_id.equalsIgnoreCase(currentmonth)) { message_adapter = new MessageAdpater(ViewMessageActivity.this, AppController.results, notificationId); list_messages.setAdapter(message_adapter); } } catch (Exception e) { e.printStackTrace(); } try { list_messages.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { AppController.ListClicked = "true"; AppController.SendMessageLayout = "true"; try { if (login_details.ViewMessageResult.get(position).pmu_readunreadstatus.equalsIgnoreCase("1")) { AppController.UnreadMessage = "true"; if (position == 0) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(notificationID); } } else { AppController.UnreadMessage = "false"; } message = login_details.ViewMessageResult.get(position).pmg_Message; attachment_name = login_details.ViewMessageResult.get(position).pmg_file_name; attachment_path = login_details.ViewMessageResult.get(position).pmg_file_path; sender_name = login_details.ViewMessageResult.get(position).Fullname; date = login_details.ViewMessageResult.get(position).pmg_date; message_subject = login_details.ViewMessageResult.get(position).pmg_subject; toUslId = login_details.ViewMessageResult.get(position).usl_ID; pmuId = login_details.ViewMessageResult.get(position).pmu_ID; Intent detail_message = new Intent(ViewMessageActivity.this, DetailMessageActivity.class); Intent intent = getIntent(); String clt_id = intent.getStringExtra("clt_id"); String msd_ID = intent.getStringExtra("msd_ID"); String usl_id = intent.getStringExtra("usl_id"); isStudentresource = intent.getStringExtra("isStudentResource"); announcementCount = intent.getStringExtra("annpuncement_count"); behaviourCount = intent.getStringExtra("behaviour_count"); AppController.clt_id = clt_id; AppController.msd_ID = msd_ID; AppController.usl_id = usl_id; AppController.school_name = school_name; detail_message.putExtra("clt_id", AppController.clt_id); detail_message.putExtra("msd_ID", AppController.msd_ID); detail_message.putExtra("usl_id", AppController.usl_id); detail_message.putExtra("School_name", AppController.school_name); detail_message.putExtra("Message", message); detail_message.putExtra("Attachment Name", attachment_name); detail_message.putExtra("Attachment Path", attachment_path); detail_message.putExtra("Sender Name", sender_name); detail_message.putExtra("isStudentResource", isStudentresource); detail_message.putExtra("Date", date); detail_message.putExtra("Message Subject", message_subject); detail_message.putExtra("ToUslId", toUslId); detail_message.putExtra("PmuId", pmuId); detail_message.putExtra("board_name", AppController.Board_name); detail_message.putExtra("version_name", AppController.versionName); detail_message.putExtra("verion_code", AppController.versionCode); detail_message.putExtra("annpuncement_count", announcementCount); detail_message.putExtra("behaviour_count", behaviourCount); startActivity(detail_message); } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } } }
package com.temple.comfort.entities; public class AgentType { private int agentTypeID; private String agentType; public AgentType(){ } public void setAgentType(String agentType){ this.agentType = agentType; } public void setAgentTypeID(int id){ this.agentTypeID = id; } public String getAgentType(){ return agentType; } public int getAgentTypeID(){ return agentTypeID; } }
package service; import java.util.ArrayList; import forms.AraziİslemHareketleri; public interface RaporlarService { public ArrayList<AraziİslemHareketleri> raporlarListesi(); }
package com.tgl.bean; import java.util.Date; public class User { private int id; private String name; private String pwd; private int age; private String date; private int useType; private String tel; private String Authentication; private int AuthenticationId; private String imageUrl; public void setId(int id){ this.id = id; } public int getId(){ return this.id; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setPwd(String pwd){ this.pwd = pwd; } public String getPwd(){ return this.pwd; } public void setAge(int age){ this.age = age; } public int getAge(){ return this.age; } public void setDate(String date){ this.date = date; } public String getDate(){ return this.date; } public void setUseType(int useType){ this.useType = useType; } public int getUseType(){ return this.useType; } public void setTel(String tel){ this.tel = tel; } public String getTel(){ return this.tel; } public void setAuthentication(String Authentication){ this.Authentication = Authentication; } public String getAuthentication(){ return this.Authentication; } public void setAuthenticationId(int AuthenticationId){ this.AuthenticationId = AuthenticationId; } public int getAuthenticationId(){ return this.AuthenticationId; } public void setImageUrl(String imageUrl){ this.imageUrl = imageUrl; } public String getImageUrl(){ return this.imageUrl; } }
package com.ybh.front.model; import java.util.Date; public class online_aws { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.id * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private Integer id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.username * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String username; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.title * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String title; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.posttime * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private Date posttime; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.status * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String status; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.thread * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private Integer thread; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.type1 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String type1; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.agent1 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String agent1; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.agent2 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String agent2; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.ip * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String ip; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.admuser * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String admuser; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.admpass * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String admpass; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.ftpname * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String ftpname; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.url * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private String url; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column FreeHost_online_aws.firstposttime * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ private Date firstposttime; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.id * * @return the value of FreeHost_online_aws.id * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.id * * @param id the value for FreeHost_online_aws.id * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.username * * @return the value of FreeHost_online_aws.username * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getUsername() { return username; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.username * * @param username the value for FreeHost_online_aws.username * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setUsername(String username) { this.username = username == null ? null : username.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.title * * @return the value of FreeHost_online_aws.title * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getTitle() { return title; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.title * * @param title the value for FreeHost_online_aws.title * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setTitle(String title) { this.title = title == null ? null : title.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.posttime * * @return the value of FreeHost_online_aws.posttime * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public Date getPosttime() { return posttime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.posttime * * @param posttime the value for FreeHost_online_aws.posttime * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setPosttime(Date posttime) { this.posttime = posttime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.status * * @return the value of FreeHost_online_aws.status * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.status * * @param status the value for FreeHost_online_aws.status * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setStatus(String status) { this.status = status == null ? null : status.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.thread * * @return the value of FreeHost_online_aws.thread * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public Integer getThread() { return thread; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.thread * * @param thread the value for FreeHost_online_aws.thread * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setThread(Integer thread) { this.thread = thread; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.type1 * * @return the value of FreeHost_online_aws.type1 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getType1() { return type1; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.type1 * * @param type1 the value for FreeHost_online_aws.type1 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setType1(String type1) { this.type1 = type1 == null ? null : type1.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.agent1 * * @return the value of FreeHost_online_aws.agent1 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getAgent1() { return agent1; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.agent1 * * @param agent1 the value for FreeHost_online_aws.agent1 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setAgent1(String agent1) { this.agent1 = agent1 == null ? null : agent1.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.agent2 * * @return the value of FreeHost_online_aws.agent2 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getAgent2() { return agent2; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.agent2 * * @param agent2 the value for FreeHost_online_aws.agent2 * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setAgent2(String agent2) { this.agent2 = agent2 == null ? null : agent2.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.ip * * @return the value of FreeHost_online_aws.ip * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getIp() { return ip; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.ip * * @param ip the value for FreeHost_online_aws.ip * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setIp(String ip) { this.ip = ip == null ? null : ip.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.admuser * * @return the value of FreeHost_online_aws.admuser * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getAdmuser() { return admuser; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.admuser * * @param admuser the value for FreeHost_online_aws.admuser * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setAdmuser(String admuser) { this.admuser = admuser == null ? null : admuser.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.admpass * * @return the value of FreeHost_online_aws.admpass * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getAdmpass() { return admpass; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.admpass * * @param admpass the value for FreeHost_online_aws.admpass * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setAdmpass(String admpass) { this.admpass = admpass == null ? null : admpass.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.ftpname * * @return the value of FreeHost_online_aws.ftpname * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getFtpname() { return ftpname; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.ftpname * * @param ftpname the value for FreeHost_online_aws.ftpname * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setFtpname(String ftpname) { this.ftpname = ftpname == null ? null : ftpname.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.url * * @return the value of FreeHost_online_aws.url * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getUrl() { return url; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.url * * @param url the value for FreeHost_online_aws.url * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setUrl(String url) { this.url = url == null ? null : url.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column FreeHost_online_aws.firstposttime * * @return the value of FreeHost_online_aws.firstposttime * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public Date getFirstposttime() { return firstposttime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column FreeHost_online_aws.firstposttime * * @param firstposttime the value for FreeHost_online_aws.firstposttime * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setFirstposttime(Date firstposttime) { this.firstposttime = firstposttime; } }
package pl.dostrzegaj.soft.flicloader; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.scribe.exceptions.OAuthConnectionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.flickr4java.flickr.Flickr; import com.flickr4java.flickr.FlickrException; import com.flickr4java.flickr.FlickrRuntimeException; import com.flickr4java.flickr.RequestContext; import com.flickr4java.flickr.auth.Auth; import com.flickr4java.flickr.photosets.PhotosetsInterface; import com.flickr4java.flickr.uploader.UploadMetaData; import com.flickr4java.flickr.uploader.Uploader; import com.google.common.base.Throwables; import com.google.common.collect.Lists; class FlickrAccountImpl implements UserAccount { private static final Logger LOGGER = LoggerFactory.getLogger(FlickrAccountImpl.class); private Flickr f; private Auth auth; private int SEND_RETRIES = 5; private int RETRY_BASE = 2; private long SEND_RETRY_DELAY = TimeUnit.SECONDS.toMillis(1); public FlickrAccountImpl( Flickr f, Auth auth) { this.f = f; this.auth = auth; RequestContext.getRequestContext() .setAuth(auth); } @Override public String createPhotoFolder( String title, String primaryPhotoId) { PhotosetsInterface i = f.getPhotosetsInterface(); try { return i.create(title, "", primaryPhotoId) .getId(); } catch (FlickrException e) { throw Throwables.propagate(e); } } @Override public Optional<UploadedPhoto> uploadPhoto( PhotoFile photo, UploadConfig config) { Uploader uploader = f.getUploader(); UploadMetaData metaData = new UploadMetaData(); metaData.setPublicFlag(config.getIsPublic()); metaData.setFriendFlag(config.getIsFriend()); metaData.setFamilyFlag(config.getIsFamily()); String basefilename = photo.getFile() .getName(); // "image.jpg"; String title = basefilename; if (basefilename.lastIndexOf('.') > 0) { title = basefilename.substring(0, basefilename.lastIndexOf('.')); } metaData.setTitle(title); metaData.setFilename(basefilename); Optional<UploadedPhoto> uploadedPhoto = Optional.empty(); try { for (int i = 1 ; i <= SEND_RETRIES ; ++i) { try { String photoId = uploader.upload(photo.getFile(), metaData); uploadedPhoto = Optional.of(new UploadedPhoto(photoId, photo.getRelativePath())); break; } catch (OAuthConnectionException | FlickrRuntimeException oce) { handleRetriableException(i, oce); LOGGER.debug("During uploadPhotos", oce); } } } catch (FlickrException e) { LOGGER.debug("Error during flickr uplaoding of :" + photo.getFile() .toString(), e); LOGGER.error("Error during flickr uplaoding of :" + photo.getFile() .toString()); } LOGGER.debug("File {} ({}) uploaded.", title, basefilename); return uploadedPhoto; } void sleepSome( int i) { try { Thread.sleep(Math.round(pow(RETRY_BASE, i) * SEND_RETRY_DELAY)); } catch (InterruptedException ie) { Thread.currentThread() .interrupt(); Throwables.propagate(ie); } } long pow( int a, int b) { long result = 1; for (int i = 1 ; i <= b ; i++) { result *= a; } return result; } @Override public void movePhotoToFolder( final UploadedPhoto uploadedPhoto, final PhotoFolderId folder) { moveWithRetries(folder, uploadedPhoto); } private void moveWithRetries( PhotoFolderId folder, UploadedPhoto uploadedPhoto) { for (int i = 1 ; i <= SEND_RETRIES ; ++i) { try { f.getPhotosetsInterface() .addPhoto(folder.getId(), uploadedPhoto.getId()); return; } catch (FlickrRuntimeException | IllegalArgumentException fre) { handleRetriableException(i, fre); } catch (FlickrException e) { if ("0".equals(e.getErrorCode())) { handleRetriableException(i, e); } else { Throwables.propagate(e); } } } } private void handleRetriableException( int i, Exception fre) { LOGGER.debug("During movePhotosToFolder got exception. Will sleep and retry", fre); LOGGER.warn("Got exception while processing folder calling flickr. Will wait and retry. Details can be found in detailed upload log"); if (i == SEND_RETRIES) { Throwables.propagate(fre); } sleepSome(i); } }
package com.witt.thread; public class TestBank { public static void main(String[] args) { Customer customer = new Customer(new Account()); Thread t1 = new Thread(customer); Thread t2 = new Thread(customer); t1.start(); t2.start(); } } class Customer implements Runnable { private Account account; public Customer(Account account) { this.account = account; } @Override public void run() { for (int i = 0; i < 3; i++) { account.deposit(1000); } } } class Account { private double balance; // depositor public synchronized void deposit(double atm) { balance += atm; try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + balance); } }
package com.pangpang6.books.guava.base; import com.google.common.base.Strings; import org.junit.Test; /** * Created by jiangjiguang on 2017/12/12. */ public class StringsTest { @Test public void commonPrefixTest(){ String ss = Strings.commonPrefix("asa", "asssss"); System.out.println(ss); } @Test public void commonSuffixTest(){ String ss = Strings.commonSuffix("asa", "asssssa"); System.out.println(ss); } @Test public void baseTest(){ System.out.println(Strings.emptyToNull("11")); } }
package rental; import java.io.Serializable; import java.sql.Timestamp; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.*; @NamedQueries(value={ @NamedQuery( name = "CompanyNames", query="SELECT c.name FROM CarRentalCompany c"), @NamedQuery( name = "Companies", query="SELECT c FROM CarRentalCompany c"), @NamedQuery( name = "CompanyByName", query="SELECT c FROM CarRentalCompany c WHERE c.name LIKE :companyName"), @NamedQuery( name = "CarTypes", query= "SELECT t.typeName FROM CarRentalCompany c INNER JOIN c.carTypes t WHERE c.name LIKE :companyName"), @NamedQuery( name = "NumberReservationsForType", query= "SELECT COUNT(y) FROM CarRentalCompany c INNER JOIN c.cars r INNER JOIN r.reservations y WHERE c.name LIKE :companyName AND r.type.typeName LIKE :typeName"), @NamedQuery( //niet af! name = "Reservations", query = "SELECT y FROM CarRentalCompany c INNER JOIN c.cars r INNER JOIN r.reservations y "), @NamedQuery( name = "ReservationsAndCartypesForCompany", query = "SELECT y, r.type FROM CarRentalCompany c INNER JOIN c.cars r INNER JOIN r.reservations y WHERE c.name LIKE :companyName"), @NamedQuery( name = "ClientForEachReservation", query = "SELECT y.renter FROM CarRentalCompany c INNER JOIN c.cars r INNER JOIN r.reservations y") }) @Entity public class CarRentalCompany implements Serializable { private static final Logger logger = Logger.getLogger(CarRentalCompany.class.getName()); @Id private String name; @OneToMany(cascade = CascadeType.ALL,targetEntity=Car.class) private List<Car> cars; @OneToMany(cascade = CascadeType.ALL,targetEntity=CarType.class) private Set<CarType> carTypes; private List<String> regions; @Version private Timestamp updateTime; public CarRentalCompany(){ this.carTypes = new HashSet<>(); } CarRentalCompany(String name, List<String> regions, List<Car> cars) { this.carTypes = new HashSet<>(); logger.log(Level.INFO, "<{0}> Car Rental Company {0} starting up...", name); this.name = name; this.cars = cars; this.regions = regions; this.updateCarTypes(); } public void setRegions(List<String> regions) { this.regions = regions; } public List<String> getRegions() { return regions; } public CarRentalCompany(String name, List<Car> cars) { this.carTypes = new HashSet<>(); logger.log(Level.INFO, "<{0}> Car Rental Company {0} starting up...", name); this.name = name; this.cars = cars; this.updateCarTypes(); } public String getName() { return name; } public void setName(String newName) { this.name = newName; } public void addCars(List<Car> newCars){ for (Car c : newCars){ this.cars.add(c); } } public void updateCarTypes(){ for (Car car : this.cars) { this.carTypes.add(car.getType()); } } public Collection<CarType> getAllTypes() { return carTypes; } public CarType getType(String carTypeName) { for(CarType type:carTypes){ if(type.getName().equals(carTypeName)) return type; } throw new IllegalArgumentException("<" + carTypeName + "> No cartype of name " + carTypeName); } public boolean isAvailable(String carTypeName, Date start, Date end) { logger.log(Level.INFO, "<{0}> Checking availability for car type {1}", new Object[]{name, carTypeName}); return getAvailableCarTypes(start, end).contains(getType(carTypeName)); } public Set<CarType> getAvailableCarTypes(Date start, Date end) { Set<CarType> availableCarTypes = new HashSet<CarType>(); for (Car car : cars) { if (car.isAvailable(start, end)) { availableCarTypes.add(car.getType()); } } return availableCarTypes; } //********* //* CARS * //********* public Car getCar(int uid) { for (Car car : cars) { if (car.getId() == uid) { return car; } } throw new IllegalArgumentException("<" + name + "> No car with uid " + uid); } public Set<Car> getCars(CarType type) { Set<Car> out = new HashSet<Car>(); for (Car car : cars) { if (car.getType().equals(type)) { out.add(car); } } return out; } public Set<Car> getCars(String type) { Set<Car> out = new HashSet<Car>(); for (Car car : cars) { if (type.equals(car.getType().getName())) { out.add(car); } } return out; } private List<Car> getAvailableCars(String carType, Date start, Date end) { List<Car> availableCars = new LinkedList<Car>(); for (Car car : cars) { if (car.getType().getName().equals(carType) && car.isAvailable(start, end)) { availableCars.add(car); } } return availableCars; } //**************** //* RESERVATIONS * //**************** public Quote createQuote(ReservationConstraints constraints, String guest) throws ReservationException { logger.log(Level.INFO, "<{0}> Creating tentative reservation for {1} with constraints {2}", new Object[]{name, guest, constraints.toString()}); if (!this.regions.contains(constraints.getRegion()) || !isAvailable(constraints.getCarType(), constraints.getStartDate(), constraints.getEndDate())) { throw new ReservationException("<" + name + "> No cars available to satisfy the given constraints."); } CarType type = getType(constraints.getCarType()); double price = calculateRentalPrice(type.getRentalPricePerDay(), constraints.getStartDate(), constraints.getEndDate()); return new Quote(guest, constraints.getStartDate(), constraints.getEndDate(), getName(), constraints.getCarType(), price); } // Implementation can be subject to different pricing strategies private double calculateRentalPrice(double rentalPricePerDay, Date start, Date end) { return rentalPricePerDay * Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24D)); } public Reservation confirmQuote(Quote quote) throws ReservationException { logger.log(Level.INFO, "<{0}> Reservation of {1}", new Object[]{name, quote.toString()}); List<Car> availableCars = getAvailableCars(quote.getCarType(), quote.getStartDate(), quote.getEndDate()); if (availableCars.isEmpty()) { throw new ReservationException("Reservation failed, all cars of type " + quote.getCarType() + " are unavailable from " + quote.getStartDate() + " to " + quote.getEndDate()); } Car car = availableCars.get((int) (Math.random() * availableCars.size())); Reservation res = new Reservation(quote, car.getId()); car.addReservation(res); return res; } public Set<Reservation> getReservationsBy(String renter) { logger.log(Level.INFO, "<{0}> Retrieving reservations by {1}", new Object[]{name, renter}); Set<Reservation> out = new HashSet<Reservation>(); for(Car c : cars) { for(Reservation r : c.getReservations()) { if(r.getCarRenter().equals(renter)) out.add(r); } } return out; } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.api; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.core.AccessDeniedException; import com.openkm.core.DatabaseException; import com.openkm.core.PathNotFoundException; import com.openkm.core.RepositoryException; import com.openkm.module.AuthModule; import com.openkm.module.ModuleManager; import com.openkm.principal.PrincipalAdapterException; public class OKMAuth implements AuthModule { private static Logger log = LoggerFactory.getLogger(OKMAuth.class); private static OKMAuth instance = new OKMAuth(); private OKMAuth() { } public static OKMAuth getInstance() { return instance; } @Override public void login() throws RepositoryException, DatabaseException { log.debug("login()"); AuthModule am = ModuleManager.getAuthModule(); am.login(); log.debug("login: void"); } @Override public String login(String user, String pass) throws AccessDeniedException, RepositoryException, DatabaseException { log.debug("login({}, {})", user, pass); AuthModule am = ModuleManager.getAuthModule(); String token = am.login(user, pass); log.debug("login: {}", token); return token; } @Override public void logout(String token) throws RepositoryException, DatabaseException { log.debug("logout({})", token); AuthModule am = ModuleManager.getAuthModule(); am.logout(token); log.debug("logout: void"); } @Override public void grantUser(String token, String nodePath, String user, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("grantUser({}, {}, {}, {})", new Object[] { token, nodePath, user, permissions }); AuthModule am = ModuleManager.getAuthModule(); am.grantUser(token, nodePath, user, permissions, recursive); log.debug("grantUser: void"); } @Override public void revokeUser(String token, String nodePath, String user, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("revokeUser({}, {}, {}, {})", new Object[] { token, nodePath, user, permissions }); AuthModule am = ModuleManager.getAuthModule(); am.revokeUser(token, nodePath, user, permissions, recursive); log.debug("revokeUser: void"); } @Override public Map<String, Integer> getGrantedUsers(String token, String nodePath) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("getGrantedUsers({}, {})", token, nodePath); AuthModule am = ModuleManager.getAuthModule(); Map<String, Integer> grantedUsers = am.getGrantedUsers(token, nodePath); log.debug("getGrantedUsers: {}", grantedUsers); return grantedUsers; } @Override public void grantRole(String token, String nodePath, String role, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("grantRole({}, {}, {}, {})", new Object[] { token, nodePath, role, permissions }); AuthModule am = ModuleManager.getAuthModule(); am.grantRole(token, nodePath, role, permissions, recursive); log.debug("grantRole: void"); } @Override public void revokeRole(String token, String nodePath, String role, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("revokeRole({}, {}, {}, {})", new Object[] { token, nodePath, role, permissions }); AuthModule am = ModuleManager.getAuthModule(); am.revokeRole(token, nodePath, role, permissions, recursive); log.debug("revokeRole: void"); } @Override public Map<String, Integer> getGrantedRoles(String token, String nodePath) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("getGrantedRoles({})", nodePath); AuthModule am = ModuleManager.getAuthModule(); Map<String, Integer> grantedRoles = am.getGrantedRoles(token, nodePath); log.debug("getGrantedRoles: {}", grantedRoles); return grantedRoles; } @Override public List<String> getUsers(String token) throws PrincipalAdapterException { log.debug("getUsers({})", token); AuthModule am = ModuleManager.getAuthModule(); List<String> users = am.getUsers(token); log.debug("getUsers: {}", users); return users; } @Override public List<String> getRoles(String token) throws PrincipalAdapterException { log.debug("getRoles({})", token); AuthModule am = ModuleManager.getAuthModule(); List<String> roles = am.getRoles(token); log.debug("getRoles: {}", roles); return roles; } @Override public List<String> getUsersByRole(String token, String role) throws PrincipalAdapterException { log.debug("getUsersByRole({}, {})", token, role); AuthModule am = ModuleManager.getAuthModule(); List<String> users = am.getUsersByRole(token, role); log.debug("getUsersByRole: {}", users); return users; } @Override public List<String> getRolesByUser(String token, String user) throws PrincipalAdapterException { log.debug("getRolesByUser({}, {})", token, user); AuthModule am = ModuleManager.getAuthModule(); List<String> users = am.getRolesByUser(token, user); log.debug("getRolesByUser: {}", users); return users; } @Override public String getMail(String token, String user) throws PrincipalAdapterException { log.debug("getMail({}, {})", token, user); AuthModule am = ModuleManager.getAuthModule(); String mail = am.getMail(token, user); log.debug("getMail: {}", mail); return mail; } @Override public String getName(String token, String user) throws PrincipalAdapterException { log.debug("getName({}, {})", token, user); AuthModule am = ModuleManager.getAuthModule(); String name = am.getName(token, user); log.debug("getName: {}", name); return name; } @Override public void changeSecurity(String token, String nodePath, Map<String, Integer> grantUsers, Map<String, Integer> revokeUsers, Map<String, Integer> grantRoles, Map<String, Integer> revokeRoles, boolean recursive) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("changeSecurity({}, {}, {}, {}, {}, {})", new Object[] { token, nodePath, grantUsers, revokeUsers, grantRoles, revokeRoles, recursive }); AuthModule am = ModuleManager.getAuthModule(); am.changeSecurity(token, nodePath, grantUsers, revokeUsers, grantRoles, revokeRoles, recursive); log.debug("changeSecurity: void"); } /* * ------------------------------------------------------------------ * These methods only works if using the OpenKM user database. * ------------------------------------------------------------------ */ @Override public void createUser(String token, String user, String password, String email, String name, boolean active) throws PrincipalAdapterException { log.debug("createUser({}, {}, {}, {}, {}, {})", new Object[] { token, user, password, active }); AuthModule am = ModuleManager.getAuthModule(); am.createUser(token, user, password, email, name, active); log.debug("createUser: void"); } @Override public void deleteUser(String token, String user) throws PrincipalAdapterException { log.debug("deleteUser({}, {})", new Object[] { token, user }); AuthModule am = ModuleManager.getAuthModule(); am.deleteUser(token, user); log.debug("deleteUser: void"); } @Override public void updateUser(String token, String user, String password, String email, String name, boolean active) throws PrincipalAdapterException { log.debug("updateUser({}, {}, {}, {}, {}, {})", new Object[] { token, user, password, email, name, active }); AuthModule am = ModuleManager.getAuthModule(); am.updateUser(token, user, password, email, name, active); log.debug("updateUser: void"); } @Override public void createRole(String token, String role, boolean active) throws PrincipalAdapterException { log.debug("createRole({}, {}, {})", new Object[] { token, role, active }); AuthModule am = ModuleManager.getAuthModule(); am.createRole(token, role, active); log.debug("createRole: void"); } @Override public void deleteRole(String token, String role) throws PrincipalAdapterException { log.debug("deleteRole({}, {})", new Object[] { token, role }); AuthModule am = ModuleManager.getAuthModule(); am.deleteRole(token, role); log.debug("deleteUser: void"); } @Override public void updateRole(String token, String role, boolean active) throws PrincipalAdapterException { log.debug("updateRole({}, {}, {})", new Object[] { token, role, active }); AuthModule am = ModuleManager.getAuthModule(); am.updateRole(token, role, active); log.debug("updateRole: void"); } @Override public void assignRole(String token, String user, String role) throws PrincipalAdapterException { log.debug("assignRole({}, {}, {})", new Object[] { token, user, role }); AuthModule am = ModuleManager.getAuthModule(); am.assignRole(token, user, role); log.debug("assignRole: void"); } @Override public void removeRole(String token, String user, String role) throws PrincipalAdapterException { log.debug("removeRole({}, {}, {})", new Object[] { token, user, role }); AuthModule am = ModuleManager.getAuthModule(); am.removeRole(token, user, role); log.debug("removeRole: void"); } }
/** * 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.hadoop.mapred; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.Collection; import java.util.Map; import org.apache.hadoop.mapred.TaskTracker.ShuffleServerMetrics; import org.apache.hadoop.metrics.ContextFactory; import org.apache.hadoop.metrics.MetricsContext; import org.apache.hadoop.metrics.spi.OutputRecord; import org.junit.Test; public class TestShuffleExceptionCount { public static class TestMapOutputServlet extends TaskTracker.MapOutputServlet { public void checkException(IOException ie, String exceptionMsgRegex, String exceptionStackRegex, ShuffleServerMetrics shuffleMetrics) { super.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); } } @Test public void testCheckException() throws IOException, InterruptedException, ClassNotFoundException, InstantiationException, IllegalAccessException { TestMapOutputServlet testServlet = new TestMapOutputServlet(); JobConf conf = new JobConf(); conf.setUser("testuser"); conf.setJobName("testJob"); conf.setSessionId("testSession"); // setup metrics context factory ContextFactory factory = ContextFactory.getFactory(); factory.setAttribute("mapred.class", "org.apache.hadoop.metrics.spi.NoEmitMetricsContext"); TaskTracker tt = new TaskTracker(); tt.setConf(conf); ShuffleServerMetrics shuffleMetrics = tt.new ShuffleServerMetrics(conf); // first test with only MsgRegex set but doesn't match String exceptionMsgRegex = "Broken pipe"; String exceptionStackRegex = null; IOException ie = new IOException("EOFException"); testServlet.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); MetricsContext context = factory.getContext("mapred"); shuffleMetrics.doUpdates(context); Map<String, Collection<OutputRecord>> records = context.getAllRecords(); Collection<OutputRecord> col = records.get("shuffleOutput"); OutputRecord outputRecord = col.iterator().next(); assertEquals(0, outputRecord.getMetric("shuffle_exceptions_caught") .intValue()); // test with only MsgRegex set that does match ie = new IOException("Broken pipe"); testServlet.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); shuffleMetrics.doUpdates(context); assertEquals(1, outputRecord.getMetric("shuffle_exceptions_caught") .intValue()); // test with neither set, make sure incremented exceptionStackRegex = null; exceptionMsgRegex = null; testServlet.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); shuffleMetrics.doUpdates(context); assertEquals(2, outputRecord.getMetric("shuffle_exceptions_caught") .intValue()); // test with only StackRegex set doesn't match exceptionStackRegex = ".*\\.doesnt\\$SelectSet\\.wakeup.*"; exceptionMsgRegex = null; ie.setStackTrace(constructStackTrace()); testServlet.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); shuffleMetrics.doUpdates(context); assertEquals(2, outputRecord.getMetric("shuffle_exceptions_caught") .intValue()); // test with only StackRegex set does match exceptionStackRegex = ".*\\.SelectorManager\\$SelectSet\\.wakeup.*"; testServlet.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); shuffleMetrics.doUpdates(context); assertEquals(3, outputRecord.getMetric("shuffle_exceptions_caught") .intValue()); // test with both regex set and matches exceptionMsgRegex = "Broken pipe"; ie.setStackTrace(constructStackTraceTwo()); testServlet.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); shuffleMetrics.doUpdates(context); assertEquals(4, outputRecord.getMetric("shuffle_exceptions_caught") .intValue()); // test with both regex set and only msg matches exceptionStackRegex = ".*[1-9]+BOGUSREGEX"; testServlet.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); shuffleMetrics.doUpdates(context); assertEquals(4, outputRecord.getMetric("shuffle_exceptions_caught") .intValue()); // test with both regex set and only stack matches exceptionStackRegex = ".*\\.SelectorManager\\$SelectSet\\.wakeup.*"; exceptionMsgRegex = "EOFException"; testServlet.checkException(ie, exceptionMsgRegex, exceptionStackRegex, shuffleMetrics); shuffleMetrics.doUpdates(context); assertEquals(4, outputRecord.getMetric("shuffle_exceptions_caught") .intValue()); } /* * Construction exception like: java.io.IOException: Broken pipe at * sun.nio.ch.EPollArrayWrapper.interrupt(Native Method) at * sun.nio.ch.EPollArrayWrapper.interrupt(EPollArrayWrapper.java:256) at * sun.nio.ch.EPollSelectorImpl.wakeup(EPollSelectorImpl.java:175) at * org.mortbay * .io.nio.SelectorManager$SelectSet.wakeup(SelectorManager.java:831) at * org.mortbay * .io.nio.SelectorManager$SelectSet.doSelect(SelectorManager.java:709) at * org.mortbay.io.nio.SelectorManager.doSelect(SelectorManager.java:192) at * org * .mortbay.jetty.nio.SelectChannelConnector.accept(SelectChannelConnector.java * :124) at * org.mortbay.jetty.AbstractConnector$Acceptor.run(AbstractConnector. * java:708) at * org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool * .java:582) */ private StackTraceElement[] constructStackTrace() { StackTraceElement[] stack = new StackTraceElement[9]; stack[0] = new StackTraceElement("sun.nio.ch.EPollArrayWrapper", "interrupt", "", -2); stack[1] = new StackTraceElement("sun.nio.ch.EPollArrayWrapper", "interrupt", "EPollArrayWrapper.java", 256); stack[2] = new StackTraceElement("sun.nio.ch.EPollSelectorImpl", "wakeup", "EPollSelectorImpl.java", 175); stack[3] = new StackTraceElement( "org.mortbay.io.nio.SelectorManager$SelectSet", "wakeup", "SelectorManager.java", 831); stack[4] = new StackTraceElement( "org.mortbay.io.nio.SelectorManager$SelectSet", "doSelect", "SelectorManager.java", 709); stack[5] = new StackTraceElement("org.mortbay.io.nio.SelectorManager", "doSelect", "SelectorManager.java", 192); stack[6] = new StackTraceElement( "org.mortbay.jetty.nio.SelectChannelConnector", "accept", "SelectChannelConnector.java", 124); stack[7] = new StackTraceElement( "org.mortbay.jetty.AbstractConnector$Acceptor", "run", "AbstractConnector.java", 708); stack[8] = new StackTraceElement( "org.mortbay.thread.QueuedThreadPool$PoolThread", "run", "QueuedThreadPool.java", 582); return stack; } /* * java.io.IOException: Broken pipe at * sun.nio.ch.EPollArrayWrapper.interrupt(Native Method) at * sun.nio.ch.EPollArrayWrapper.interrupt(EPollArrayWrapper.java:256) at * sun.nio.ch.EPollSelectorImpl.wakeup(EPollSelectorImpl.java:175) at * org.mortbay * .io.nio.SelectorManager$SelectSet.wakeup(SelectorManager.java:831) at * org.mortbay * .io.nio.SelectChannelEndPoint.updateKey(SelectChannelEndPoint.java:335) at * org * .mortbay.io.nio.SelectChannelEndPoint.blockWritable(SelectChannelEndPoint * .java:278) at * org.mortbay.jetty.AbstractGenerator$Output.blockForOutput(AbstractGenerator * .java:545) at * org.mortbay.jetty.AbstractGenerator$Output.flush(AbstractGenerator * .java:572) at * org.mortbay.jetty.HttpConnection$Output.flush(HttpConnection.java:1012) at * org * .mortbay.jetty.AbstractGenerator$Output.write(AbstractGenerator.java:651)at * org * .mortbay.jetty.AbstractGenerator$Output.write(AbstractGenerator.java:580) * at */ private StackTraceElement[] constructStackTraceTwo() { StackTraceElement[] stack = new StackTraceElement[11]; stack[0] = new StackTraceElement("sun.nio.ch.EPollArrayWrapper", "interrupt", "", -2); stack[1] = new StackTraceElement("sun.nio.ch.EPollArrayWrapper", "interrupt", "EPollArrayWrapper.java", 256); stack[2] = new StackTraceElement("sun.nio.ch.EPollSelectorImpl", "wakeup", "EPollSelectorImpl.java", 175); stack[3] = new StackTraceElement( "org.mortbay.io.nio.SelectorManager$SelectSet", "wakeup", "SelectorManager.java", 831); stack[4] = new StackTraceElement( "org.mortbay.io.nio.SelectChannelEndPoint", "updateKey", "SelectChannelEndPoint.java", 335); stack[5] = new StackTraceElement( "org.mortbay.io.nio.SelectChannelEndPoint", "blockWritable", "SelectChannelEndPoint.java", 278); stack[6] = new StackTraceElement( "org.mortbay.jetty.AbstractGenerator$Output", "blockForOutput", "AbstractGenerator.java", 545); stack[7] = new StackTraceElement( "org.mortbay.jetty.AbstractGenerator$Output", "flush", "AbstractGenerator.java", 572); stack[8] = new StackTraceElement("org.mortbay.jetty.HttpConnection$Output", "flush", "HttpConnection.java", 1012); stack[9] = new StackTraceElement( "org.mortbay.jetty.AbstractGenerator$Output", "write", "AbstractGenerator.java", 651); stack[10] = new StackTraceElement( "org.mortbay.jetty.AbstractGenerator$Output", "write", "AbstractGenerator.java", 580); return stack; } }
package info.narmontas.valuemover; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static info.narmontas.valuemover.MoveValues.*; import static org.junit.jupiter.api.Assertions.*; public class MoveValuesFromParentClassTest { private static ChildrenType inputObject; private ChildrenType outputObject; @BeforeAll public static void init() { inputObject = new ChildrenType(); inputObject.setId(11L); inputObject.setName("Test Name"); inputObject.setDescription("Test Description"); inputObject.setLevel(1); } @BeforeEach public void createOutputObject() { outputObject = new ChildrenType(); } @Test public void moveAll() { forType(ChildrenType.class) .takeValuesFrom(inputObject) .putValuesTo(outputObject) .moveAll(); assertEquals(inputObject.getId(), outputObject.getId()); assertEquals(inputObject.getName(), outputObject.getName()); assertEquals(inputObject.getDescription(), outputObject.getDescription()); assertEquals(inputObject.getLevel(), outputObject.getLevel()); } @Test public void moveAll_flat() { forFlatType(ChildrenType.class) .takeValuesFrom(inputObject) .putValuesTo(outputObject) .moveAll(); assertNotEquals(inputObject.getId(), outputObject.getId()); assertNotEquals(inputObject.getName(), outputObject.getName()); assertEquals(inputObject.getDescription(), outputObject.getDescription()); assertEquals(inputObject.getLevel(), outputObject.getLevel()); } }
package com.spower.business.notice.command; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import com.spower.basesystem.common.command.BaseCommandInfo; /** * OaNotice entity. @author MyEclipse Persistence Tools */ public class NoticeEditInfo extends BaseCommandInfo { // Fields private Long noticeId; private String title; private String displayType; private String publishType; private String content; private BigDecimal publishDepId; private Date createDate; private BigDecimal creatorId; private Date publishDate; private String status; private String smsFlag; private String mesFlag; private String attachFlag; private Long[] attachId; // Property accessors public Long getNoticeId() { return this.noticeId; } public void setNoticeId(Long noticeId) { this.noticeId = noticeId; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getDisplayType() { return this.displayType; } public void setDisplayType(String displayType) { this.displayType = displayType; } public String getPublishType() { return this.publishType; } public void setPublishType(String publishType) { this.publishType = publishType; } public String getContent() { return this.content; } public void setContent(String content) { this.content = content; } public BigDecimal getPublishDepId() { return this.publishDepId; } public void setPublishDepId(BigDecimal publishDepId) { this.publishDepId = publishDepId; } public Date getCreateDate() { return this.createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public BigDecimal getCreatorId() { return this.creatorId; } public void setCreatorId(BigDecimal creatorId) { this.creatorId = creatorId; } public Date getPublishDate() { return this.publishDate; } public void setPublishDate(Date publishDate) { this.publishDate = publishDate; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getSmsFlag() { return this.smsFlag; } public void setSmsFlag(String smsFlag) { this.smsFlag = smsFlag; } public String getMesFlag() { return this.mesFlag; } public void setMesFlag(String mesFlag) { this.mesFlag = mesFlag; } public Long[] getAttachId() { return attachId; } public void setAttachId(Long[] attachId) { this.attachId = attachId; } public String getAttachFlag() { return attachFlag; } public void setAttachFlag(String attachFlag) { this.attachFlag = attachFlag; } }
package util; import excecoes.Menssagem; import validacoes.EnumValidacoes; import validacoes.EnumValidacoesAgrupador; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Future; public class EstrategiaDeValidacao { public static Set<Menssagem> validar(Object object) throws Exception { for (EnumValidacoesAgrupador agrupador : EnumValidacoesAgrupador.values()) { if (agrupador.getClazz().equals(object.getClass())) { return executarValidacoes(object, agrupador); } } return null; } private static Set<Menssagem> executarValidacoes(Object object, EnumValidacoesAgrupador agrupador) throws Exception { ThreadPool threadPool = new ThreadPool(); Set<Future<Set<Menssagem>>> menssagensFuture = new HashSet<Future<Set<Menssagem>>>(); for (EnumValidacoes validacao : agrupador.getValidacoes()) { menssagensFuture.add((Future<Set<Menssagem>>) threadPool.executeAsync(new Worker(object, agrupador.getDadosCompartilhados(), validacao))); } threadPool.aguardarProcessamento(); Set<Menssagem> menssagens = new HashSet<Menssagem>(); for (Future<Set<Menssagem>> menssagem : menssagensFuture) { menssagens.addAll(menssagem.get()); } return menssagens; } }
package TestSpring; import TestSpring.News.News; import TestSpring.News.NewsRepository; import TestSpring.NewsType.NewsType; import TestSpring.NewsType.NewsTypeRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class LoadDatabase { @Bean CommandLineRunner initDatabaseType(NewsTypeRepository repositoryType) { return args -> { repositoryType.save(new NewsType("Nazvanie1", 1)); repositoryType.save(new NewsType("Nazvanie2", 2)); }; } @Bean CommandLineRunner initDatabase(NewsRepository repository) { return args -> { repository.save(new News("Vnimanie", "Korotkoe", "Dlinnoe", 1L)); repository.save(new News("Vnimanie1", "Korotkoe2", "Dlinnoe3", 2L)); }; } }
package com.tencent.mm.ui.base; import android.content.Context; import android.database.DataSetObserver; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ListAdapter; import android.widget.Scroller; import java.util.LinkedList; import java.util.Queue; public class MMHorList extends AdapterView<ListAdapter> { private boolean lAt = false; private int offset; private boolean tvA = false; private boolean tvB = false; protected Scroller tvC; private GestureDetector tvD; private OnItemSelectedListener tvE; private OnItemClickListener tvF; private ListAdapter tvG; private Runnable tvH = new 1(this); private boolean tvI = false; private boolean tvJ = false; private int tvK = 0; private int tvL = 0; private boolean tvM = false; private DataSetObserver tvN = new 2(this); private OnGestureListener tvO = new 3(this); private a tvt; private int tvu; private int tvv; private int tvw; private int tvx; private int tvy = 536870912; private Queue<View> tvz = new LinkedList(); public interface a { void bHl(); void bHm(); void bbm(); } public void setHorListLitener(a aVar) { this.tvt = aVar; } public void setCenterInParent(boolean z) { this.tvI = z; } public void setOverScrollEnabled(boolean z) { this.tvJ = z; } public void setItemWidth(int i) { this.tvK = i; } private void init() { this.tvC = new Scroller(getContext()); this.tvu = -1; this.tvv = 0; this.offset = 0; this.tvw = 0; this.tvx = 0; this.tvA = false; this.tvy = 536870912; this.tvD = new GestureDetector(getContext(), this.tvO); } public MMHorList(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); init(); } public void setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) { this.tvE = onItemSelectedListener; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.tvF = onItemClickListener; } public MMHorList(Context context, AttributeSet attributeSet) { super(context, attributeSet); init(); } public ListAdapter getAdapter() { return this.tvG; } public void setAdapter(ListAdapter listAdapter) { if (this.tvG == null) { listAdapter.registerDataSetObserver(this.tvN); } this.tvG = listAdapter; reset(); } private int getChildViewTotalWidth() { return this.tvG.getCount() * this.tvK; } protected void onLayout(boolean z, int i, int i2, int i3, int i4) { super.onLayout(z, i, i2, i3, i4); if (this.tvG != null) { int i5; int i6; this.tvB = true; if (this.tvA) { i5 = this.tvw; init(); removeAllViewsInLayout(); this.tvx = i5; if (this.tvI) { this.tvL = Math.max(0, (getWidth() - getChildViewTotalWidth()) / 2); this.offset = this.tvL; } this.tvA = false; } if (this.tvC.computeScrollOffset()) { this.tvx = this.tvC.getCurrX(); } if (!this.tvJ) { if (this.tvx < 0) { this.tvx = 0; this.tvC.forceFinished(true); } if (this.tvx > this.tvy) { this.tvx = this.tvy; this.tvC.forceFinished(true); } } else if (getChildViewTotalWidth() > getWidth()) { if (this.tvx < getWidth() * -1) { this.tvx = (getWidth() * -1) + 1; this.tvC.forceFinished(true); } if (this.tvx > this.tvy + getWidth()) { this.tvx = (this.tvy + getWidth()) - 1; this.tvC.forceFinished(true); } } else { if (this.tvx < (getWidth() * -1) + this.tvL) { this.tvx = ((getWidth() * -1) + this.tvL) + 1; this.tvC.forceFinished(true); } if (this.tvx > getWidth() - this.tvL) { this.tvx = (getWidth() - this.tvL) - 1; this.tvC.forceFinished(true); } } int i7 = this.tvw - this.tvx; View childAt = getChildAt(0); while (childAt != null && childAt.getRight() + i7 <= 0) { this.offset += childAt.getMeasuredWidth(); this.tvz.offer(childAt); removeViewInLayout(childAt); this.tvu++; childAt = getChildAt(0); this.tvB = true; } childAt = getChildAt(getChildCount() - 1); while (childAt != null && childAt.getLeft() + i7 >= getWidth()) { this.tvz.offer(childAt); removeViewInLayout(childAt); this.tvv--; childAt = getChildAt(getChildCount() - 1); this.tvB = true; } childAt = getChildAt(getChildCount() - 1); i5 = childAt != null ? childAt.getRight() : 0; while (true) { i6 = i5; if (i6 + i7 >= getWidth() || this.tvv >= this.tvG.getCount()) { childAt = getChildAt(0); } else { childAt = this.tvG.getView(this.tvv, (View) this.tvz.poll(), this); K(childAt, -1); i5 = childAt.getMeasuredWidth() + i6; if (this.tvv == this.tvG.getCount() - 1) { this.tvy = (this.tvw + i5) - getWidth(); } this.tvv++; } } childAt = getChildAt(0); i5 = childAt != null ? childAt.getLeft() : 0; while (true) { i6 = i5; if (i6 + i7 > 0 && this.tvu >= 0) { View view = this.tvG.getView(this.tvu, (View) this.tvz.poll(), this); K(view, 0); i5 = i6 - view.getMeasuredWidth(); this.tvu--; this.offset -= view.getMeasuredWidth(); } } if (getChildCount() > 0 && this.tvB) { this.offset += i7; i6 = this.offset; for (i5 = 0; i5 < getChildCount(); i5++) { View childAt2 = getChildAt(i5); int measuredWidth = childAt2.getMeasuredWidth(); childAt2.layout(i6, 0, i6 + measuredWidth, childAt2.getMeasuredHeight()); i6 += measuredWidth; } } this.tvw = this.tvx; if (!this.tvC.isFinished()) { post(this.tvH); } else if (this.tvt != null && this.tvM) { this.tvt.bbm(); this.tvM = false; } } } private void K(View view, int i) { this.tvB = true; LayoutParams layoutParams = view.getLayoutParams(); if (layoutParams == null) { layoutParams = new LayoutParams(-1, -1); } addViewInLayout(view, i, layoutParams, true); view.measure(MeasureSpec.makeMeasureSpec(getWidth(), Integer.MIN_VALUE), MeasureSpec.makeMeasureSpec(getHeight(), Integer.MIN_VALUE)); } public View getSelectedView() { return null; } public void setSelection(int i) { } protected void onMeasure(int i, int i2) { if (this.tvG != null && this.tvG.getCount() > 0) { View childAt = getChildAt(0); if (childAt != null) { super.onMeasure(i, MeasureSpec.makeMeasureSpec(childAt.getMeasuredHeight(), Integer.MIN_VALUE)); return; } } super.onMeasure(i, i2); } public boolean dispatchTouchEvent(MotionEvent motionEvent) { boolean onTouchEvent = this.tvD.onTouchEvent(motionEvent); if (motionEvent.getAction() == 0) { this.lAt = true; if (this.tvt != null) { this.tvt.bHl(); } } else if (motionEvent.getAction() == 3 || motionEvent.getAction() == 1) { if (this.tvJ) { if (getChildViewTotalWidth() > getWidth()) { if (this.tvw < 0) { this.tvC.forceFinished(true); this.tvC.startScroll(this.tvw, 0, 0 - this.tvw, 0); requestLayout(); } else if (this.tvw > this.tvy) { this.tvC.forceFinished(true); this.tvC.startScroll(this.tvw, 0, this.tvy - this.tvw, 0); requestLayout(); } } else if (this.tvw != this.tvL * -1) { this.tvC.forceFinished(true); this.tvC.startScroll(this.tvw, 0, 0 - this.tvw, 0); requestLayout(); } } this.lAt = false; if (this.tvt != null) { this.tvt.bHm(); } } return onTouchEvent; } protected final boolean crg() { this.tvC.forceFinished(true); return true; } public final void En(int i) { this.tvC.forceFinished(true); this.tvC.startScroll(this.tvw, 0, i - this.tvw, 0); this.tvM = true; requestLayout(); } public int getCurrentPosition() { return this.tvw; } public boolean getIsTouching() { return this.lAt; } public boolean onTouchEvent(MotionEvent motionEvent) { return false; } protected final boolean aC(float f) { this.tvC.fling(this.tvx, 0, (int) (-f), 0, 0, this.tvy, 0, 0); requestLayout(); return true; } private void reset() { init(); removeAllViewsInLayout(); requestLayout(); } }
package de.jmda.gen.java.impl; import de.jmda.gen.GeneratorException; import de.jmda.gen.java.MethodBodyGenerator; import de.jmda.gen.java.MethodModifiersGenerator; import de.jmda.gen.java.MethodNameGenerator; import de.jmda.gen.java.MethodParametersGenerator; import de.jmda.gen.java.ModifiersUtil; import de.jmda.gen.java.DeclaredStaticMethodGenerator; import de.jmda.gen.java.ThrowsClauseGenerator; import de.jmda.gen.java.TypeNameGenerator; public class DefaultDeclaredStaticMethodGenerator extends AbstractDeclaredMethodGenerator implements DeclaredStaticMethodGenerator { public DefaultDeclaredStaticMethodGenerator( MethodModifiersGenerator modifiersGenerator, TypeNameGenerator typeNameGenerator, MethodNameGenerator methodNameGenerator, MethodParametersGenerator methodParameterListGenerator, ThrowsClauseGenerator throwsClauseGenerator, MethodBodyGenerator methodBodyGenerator) { super( modifiersGenerator, typeNameGenerator, methodNameGenerator, methodParameterListGenerator, throwsClauseGenerator, notNull(methodBodyGenerator)); demandModifiersGenerator().setStatic(true); } public DefaultDeclaredStaticMethodGenerator() { this(null, null, null, null, null, null); } @Override public StringBuffer generate() throws GeneratorException { return validate(super.generate()); } /** * @param stringBuffer * @return <code>stringBuffer</code> * @throws GeneratorException if <code>stringBuffer</code> does not contain * {@link ModifiersUtil#STATIC} */ protected StringBuffer validate(StringBuffer stringBuffer) throws GeneratorException { if (false == ModifiersUtil.hasStaticModifier(stringBuffer)) { throw new GeneratorException( stringBuffer + " has to contain [" + ModifiersUtil.STATIC + "] " + "modifier"); } return stringBuffer; } }
package com.tencent.mm.plugin.account.bind.ui; import com.tencent.mm.plugin.account.friend.a.n; import com.tencent.mm.ui.base.h.d; import java.util.ArrayList; class GoogleFriendUI$4 implements d { final /* synthetic */ GoogleFriendUI eIi; final /* synthetic */ ArrayList eIj; final /* synthetic */ n eIk; GoogleFriendUI$4(GoogleFriendUI googleFriendUI, ArrayList arrayList, n nVar) { this.eIi = googleFriendUI; this.eIj = arrayList; this.eIk = nVar; } public final void bx(int i, int i2) { if (i2 != -1) { GoogleFriendUI.a(this.eIi, (n) this.eIj.get(i2), this.eIk); } } }