id
int64
file_name
string
file_path
string
content
string
size
int64
language
string
extension
string
total_lines
int64
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
repo_name
string
repo_stars
int64
repo_forks
int64
repo_open_issues
int64
repo_license
string
repo_extraction_date
string
exact_duplicates_redpajama
bool
near_duplicates_redpajama
bool
exact_duplicates_githubcode
bool
exact_duplicates_stackv2
bool
exact_duplicates_stackv1
bool
near_duplicates_githubcode
bool
near_duplicates_stackv1
bool
near_duplicates_stackv2
bool
length
int64
3,918,765
Verification.java
adellafrattina_ClimateMonitoring/climate-monitoring-client/src/main/java/client/Verification.java
/* Alessandro della Frattina 753073 VA Cristian Capiferri 752918 VA Francesco Lops 753175 VA Dariia Sniezhko 753057 VA */ package client; import java.util.Random; import climatemonitoring.core.Application; import climatemonitoring.core.Operator; import climatemonitoring.core.Result; import climatemonitoring.core.gui.Button; import climatemonitoring.core.gui.InputTextButton; import climatemonitoring.core.gui.Panel; import climatemonitoring.core.gui.Text; import climatemonitoring.core.headless.Console; import climatemonitoring.core.utility.Email; import imgui.ImGui; /** * To execute the verification code * * @author adellafrattina * @version 1.0-SNAPSHOT */ public class Verification { public void onHeadlessRender(Operator operator) { Email email = new Email("climatemonitoringappservice@mail.com", "Climate Monitoring"); email.setReceiverEmail(operator.getEmail()); email.setReceiverName(operator.getName() + " " + operator.getSurname()); email.setSubject("Climate Monitoring verification code"); Random r = new Random(); int codeGiven = r.nextInt(10000, 100000); email.setMessage("Your verification code is: " + codeGiven + "\nIt will expire in 2 minutes"); Result<Boolean> result = email.send(); result.join(); start = System.nanoTime(); Console.write("An email with the verification code has been sent to " + operator.getEmail() + "\nIt will expire in 2 minutes"); int codeReceived = Integer.parseInt(Console.read("Your verification code > ")); if (System.nanoTime() - start >= 120000000000L) errorMsg = "Time to enter verification code expired"; if (codeReceived != codeGiven) errorMsg = "The verification code entered is incorrect"; } public void onGUIRender(Operator operator) { clicked = false; if (setUpEmail) { Email email = new Email("climatemonitoringappservice@mail.com", "Climate Monitoring"); email.setReceiverEmail(operator.getEmail()); email.setReceiverName(operator.getName() + " " + operator.getSurname()); email.setSubject("Climate Monitoring verification code"); Random r = new Random(); code = r.nextInt(10000, 100000); email.setMessage("Your verification code is: " + code + "\nIt will expire in 2 minutes"); start = System.nanoTime(); emailSentResult = email.send(); setUpEmail = false; } if (emailSentResult != null && emailSentResult.ready()) { try { emailSentResult.get(); emailSentResult = null; } catch (Exception e) { e.printStackTrace(); Application.close(); } } else if (emailSentResult != null) { text.setOrigin(text.getWidth() / 2.0f, text.getHeight() / 2.0f); text.setPosition(ImGui.getWindowWidth() / 2.0f, ImGui.getWindowHeight() / 2.0f); text.render(); return; } verificationPanel.setSize(Application.getWidth() / 2.0f, Application.getHeight() / 2.0f); verificationPanel.setOrigin(verificationPanel.getWidth() / 2.0f, verificationPanel.getHeight() / 2.0f); verificationPanel.setPosition(Application.getWidth() / 2.0f, Application.getHeight() / 2.0f); verificationPanel.begin("Verification"); verificationText.setOriginX(verificationText.getWidth() / 2.0f); verificationText.setPositionX(verificationPanel.getWidth() / 2.0f); verificationText.render(); verificationEmailText.setOriginX(verificationEmailText.getWidth() / 2.0f); verificationEmailText.setPositionX(verificationPanel.getWidth() / 2.0f); verificationEmailText.setString(operator.getEmail()); verificationEmailText.render(); verificationExpirationText.setOriginX(verificationExpirationText.getWidth() / 2.0f); verificationExpirationText.setPositionX(verificationPanel.getWidth() / 2.0f); verificationExpirationText.render(); verificationInputText.setWidth(verificationPanel.getWidth() / 2.0f); verificationInputText.setOriginX(verificationInputText.getWidth() / 2.0f); verificationInputText.setPositionX(verificationPanel.getWidth() / 2.0f); verificationInputText.setNumbersOnly(true); verificationInputText.setNoSpaces(true); verificationInputText.setEnterReturnsTrue(true); if (tried) verificationInputText.setReadOnly(true); if (verificationInputText.render() || verificationInputText.isButtonPressed()) { if (!verificationInputText.getString().isEmpty()) { if (System.nanoTime() - start >= 120000000000L) errorMsg = "Time to enter verification code expired"; if (Integer.parseInt(verificationInputText.getString()) != code) errorMsg = "The verification code entered is incorrect"; clicked = true; tried = true; } } if (tried) { if (errorMsg != null) { text.setString(errorMsg); text.setOriginX(text.getWidth() / 2.0f); text.setPositionX(ImGui.getWindowWidth() / 2.0f); text.setColor(255, 0, 0, 255); text.render(); cancel.setOriginX(cancel.getWidth() / 2.0f); cancel.setPositionX(ImGui.getWindowWidth() / 2.0f); if (cancel.render()) { Handler.getView().resetStateData(new Registration()); Handler.getView().resetStateData(new CenterCreation()); Handler.getView().returnToPreviousState(); } } } verificationPanel.end(); } public boolean clicked() { return clicked; } public String getErrorMsg() { return errorMsg; } private boolean setUpEmail = true; private Result<Boolean> emailSentResult; private String errorMsg; private Text verificationText = new Text("An email with the verification code has been sent to"); private Text verificationEmailText = new Text(""); private Text verificationExpirationText = new Text("It will expire in 2 minutes"); private InputTextButton verificationInputText = new InputTextButton("Code"); private Panel verificationPanel = new Panel(); private int code = 0; private long start = 0; private Text text = new Text("Loading..."); private boolean clicked = false; private Button cancel = new Button("Cancel"); private boolean tried = false; }
5,928
Java
.java
144
37.777778
129
0.757761
adellafrattina/ClimateMonitoring
3
3
0
GPL-3.0
9/4/2024, 11:48:53 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
5,928
796,697
GlcdInstructionFlag.java
ribasco_glcd-emulator/src/main/java/com/ibasco/glcdemulator/emulator/GlcdInstructionFlag.java
/*- * ========================START================================= * Organization: Rafael Luis Ibasco * Project: GLCD Simulator * Filename: GlcdInstructionFlag.java * * --------------------------------------------------------- * %% * Copyright (C) 2018 - 2019 Rafael Luis Ibasco * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * =========================END================================== */ package com.ibasco.glcdemulator.emulator; /** * An interface representing an instruction of the display. * * @author Rafael Ibasco */ public interface GlcdInstructionFlag { /** * @return The unsigned byte representing the instruction flag */ int getCode(); /** * @return The description of the instruction flag */ String getDescription(); /** * Retrieve the {@link GlcdInstructionFlag} enum based on the instruction code provided. * * @param code * The instruction code * * @return The {@link GlcdInstructionFlag} enum that matches the instruction code provided */ GlcdInstructionFlag valueOf(int code); /** * Returns the bit position of the flag * * @param flag * The display instruction flag * * @return The bit position 0 to 7. -1 if not found. */ default int pos(int flag) { int pos = 0; for (int i = 0x1; (i != flag) && (pos < 8); i <<= 1) pos++; return pos >= 8 ? -1 : pos; } /** * Method to check if the value specified matches the current flag * * @param value * An integer representing an instruction * * @return True if the value specified contains the matching flag */ default boolean matches(int value) { int flagBitPos = pos(getCode()); if (flagBitPos <= -1) return false; byte lhs = (byte) (value >> flagBitPos); byte rhs = (byte) (getCode() >> flagBitPos); return lhs == rhs; } }
2,619
Java
.java
80
28.0125
94
0.604816
ribasco/glcd-emulator
83
7
3
GPL-3.0
9/4/2024, 7:08:56 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,619
3,505,538
Logic.java
openhealthcare_openMAXIMS/openmaxims_workspace/Core/src/ims/core/forms/dbimagedisplay/Logic.java
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Catalin Tomozei using IMS Development Environment (version 1.71 build 3729.19612) // Copyright (C) 1995-2010 IMS MAXIMS. All rights reserved. package ims.core.forms.dbimagedisplay; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import ims.admin.vo.AppImageVo; import ims.configuration.gen.ConfigFlag; import ims.configuration.EnvironmentConfig; import ims.core.vo.AppDBImageVo; import ims.core.vo.PatientImageVo; import ims.framework.utils.Base64; public class Logic extends BaseLogic { private static final long serialVersionUID = 1L; /** * setValue */ public void setValue(ims.core.patient.vo.PatientRefVo value) { //New Patient if (value == null) { form.imgDisplay().setValue(form.getImages().Core.NoPatientImage); return; } //Existing Patient else { form.imgDisplay().setVisible(true); try { String sessionID = engine.getSessionId(); int patientID = value.getID_Patient(); PatientImageVo patientImage = domain.getPatientImage(patientID); AppDBImageVo dbImageVo = patientImage.getDBPhoto(); //Existing Patient with no image if (dbImageVo == null) { form.imgDisplay().setValue(form.getImages().Core.NoPatientImage); return; } String encodedImage = dbImageVo.getImageData(); String type = dbImageVo.getImageType().getText(); decodeFromBase64(encodedImage, sessionID, type); } catch (IOException error) { engine.showMessage(error.getMessage()); } } } public void clearCache() { // TODO: Add your code here. } private String decodeFromBase64(String content, String sessionID, String imageType) throws IOException { byte[] decBytes = Base64.decode(content); if (decBytes == null || (decBytes != null && decBytes.length == 0)) { engine.showMessage("Base64 image size is zero"); return null; } //Get CurrentTimeMillis() segment String str = Long.toHexString(System.currentTimeMillis()); while (str.length () < 12) { str = '0' + str; } String image = EnvironmentConfig.getBaseUri() + ConfigFlag.GEN.FILE_UPLOAD_DIR.getValue() + str + "_" +sessionID + "." + imageType.toLowerCase(); ArrayList<String> patientPhotoTempFiles = form.getGlobalContext().Core.getPatientPhotoTempFilesIsNotNull() ? form.getGlobalContext().Core.getPatientPhotoTempFiles() : new ArrayList<String>(); patientPhotoTempFiles.add(image); form.getGlobalContext().Core.setPatientPhotoTempFiles(patientPhotoTempFiles); try { FileOutputStream fos = new FileOutputStream(image); fos.write(decBytes); fos.close(); AppImageVo vo = new AppImageVo(); if (ConfigFlag.GEN.APPLICATION_URL.getValue() == "") { vo.setImagePath(EnvironmentConfig.getAplicationURL() + (ConfigFlag.GEN.FILE_UPLOAD_DIR.getValue() + str + "_" +sessionID + "." + imageType.toLowerCase()).replace("\\", "/")); } else { vo.setImagePath(ConfigFlag.GEN.APPLICATION_URL.getValue() + (ConfigFlag.GEN.FILE_UPLOAD_DIR.getValue() + str + "_" +sessionID + "." + imageType.toLowerCase()).replace("\\", "/")); } form.imgDisplay().setValue(vo); form.getLocalContext().setDisplayedImage(vo); } catch(FileNotFoundException exception) { System.out.println("FileNotFoundException : " + exception); } catch(IOException ioexception) { System.out.println("IOException : " + ioexception); } return null; } public AppImageVo getValue() { return form.getLocalContext().getDisplayedImage(); } public void setDBImage(AppDBImageVo image) { if (image == null) { form.imgDisplay().setValue(form.getImages().Core.NoPatientImage); return; } try { String sessionID = engine.getSessionId(); String encodedImage = image.getImageData(); String type = image.getImageType().getText(); decodeFromBase64(encodedImage, sessionID, type); } catch (IOException error) { engine.showMessage(error.getMessage()); } } }
5,765
Java
.java
143
35.083916
195
0.606652
openhealthcare/openMAXIMS
3
1
0
AGPL-3.0
9/4/2024, 11:30:20 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
5,765
4,103,718
OsmInterface.java
meier_opensm-client-server/src/main/java/gov/llnl/lc/infiniband/opensm/plugin/OsmInterface.java
/************************************************************ * Copyright (c) 2015, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Timothy Meier, meier3@llnl.gov, All rights reserved. * LLNL-CODE-673346 * * This file is part of the OpenSM Monitoring Service (OMS) package. * * 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) version 2.1 dated February 1999. * * 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. * * OUR NOTICE AND TERMS AND CONDITIONS OF THE GNU GENERAL PUBLIC LICENSE * * Our Preamble Notice * * A. This notice is required to be provided under our contract with the U.S. * Department of Energy (DOE). This work was produced at the Lawrence Livermore * National Laboratory under Contract No. DE-AC52-07NA27344 with the DOE. * * B. Neither the United States Government nor Lawrence Livermore National * Security, LLC nor any of their employees, makes any warranty, express or * implied, or assumes any liability or responsibility for the accuracy, * completeness, or usefulness of any information, apparatus, product, or * process disclosed, or represents that its use would not infringe privately- * owned rights. * * C. Also, reference herein to any specific commercial products, process, or * services by trade name, trademark, manufacturer or otherwise does not * necessarily constitute or imply its endorsement, recommendation, or favoring * by the United States Government or Lawrence Livermore National Security, * LLC. The views and opinions of authors expressed herein do not necessarily * state or reflect those of the United States Government or Lawrence Livermore * National Security, LLC, and shall not be used for advertising or product * endorsement purposes. * * file: OsmInterface.java * * Created on: Jul 7, 2011 * Author: meier3 ********************************************************************/ package gov.llnl.lc.infiniband.opensm.plugin; import gov.llnl.lc.infiniband.opensm.plugin.data.OSM_Nodes; import gov.llnl.lc.infiniband.opensm.plugin.data.OSM_PluginInfo; import gov.llnl.lc.infiniband.opensm.plugin.data.OSM_Ports; import gov.llnl.lc.infiniband.opensm.plugin.data.OSM_Stats; import gov.llnl.lc.infiniband.opensm.plugin.data.OSM_Subnet; import gov.llnl.lc.infiniband.opensm.plugin.data.OSM_SysInfo; public interface OsmInterface { /************************************************************************** *** Method Name: *** getVersion **/ /** *** Returns a String that represents the version of the plugin. *** <p> *** *** @return the version String **************************************************************************/ public String getVersion(); /*-----------------------------------------------------------------------*/ /************************************************************************** *** Method Name: *** wait_for_event **/ /** *** Blocks until an event occurs, or the timeout expires. The nature of the *** event is indicated by the return value. *** <p> *** *** @see Method_related_to_this_method *** *** @param timeout the maximum number of milliseconds to wait before *** timing out. If zero, then wait forever. *** *** @return the nature of the interrupt **************************************************************************/ public int wait_for_event(int timeout); /*-----------------------------------------------------------------------*/ /************************************************************************** *** Method Name: *** getInterfaceName **/ /** *** Returns the actual name of the concrete object or class that implements this *** interface. *** <p> *** *** @return the name of the actual OsmInterface **************************************************************************/ public String getInterfaceName(); /************************************************************************** *** Method Name: *** getOsmNodes **/ /** *** Returns an object that represents all of the Nodes in the fabric *** interface. *** <p> *** *** @return an OSM_Nodes object **************************************************************************/ public OSM_Nodes getOsmNodes(); /************************************************************ * Method Name: * getPluginInfo **/ /** * Returns an object that contains static configuration and dynamic behavior * about the state and status of the plugin. * * @return an OSM_PluginInfo object ***********************************************************/ public OSM_PluginInfo getPluginInfo(); /************************************************************************** *** Method Name: *** getOsmPorts **/ /** *** Returns an object that represents all of the Ports in the fabric *** interface. *** <p> *** *** @return an OSM_Ports object **************************************************************************/ public OSM_Ports getOsmPorts(); /************************************************************************** *** Method Name: *** getOsmSubnet **/ /** *** Returns an object that represents most of the subnet in the fabric *** interface. *** <p> *** *** @return an OSM_Subnet object **************************************************************************/ public OSM_Subnet getOsmSubnet(); /************************************************************************** *** Method Name: *** getOsmStats **/ /** *** Returns an object that represents all of the Stats in the fabric *** interface. *** <p> *** *** @return an OSM_Stats object **************************************************************************/ public OSM_Stats getOsmStats(); /************************************************************************** *** Method Name: *** getOsmSysInfo **/ /** *** Returns an object that represents all of the SysInfo in the fabric *** interface. *** <p> *** *** @return an OSM_SysInfo object **************************************************************************/ public OSM_SysInfo getOsmSysInfo(); /************************************************************************** *** Method Name: *** invokeCommand **/ /** *** Invoke a native command and return the result status in the form of a *** string. The type of command to invoke is specified by an integer, and *** can be modified by command arguments provided through a single string. *** <p> *** *** @return the results of invoking the command, in string form **************************************************************************/ public String invokeCommand(int cmdNum, String cmdArgs); }
8,103
Java
.java
191
37.743455
84
0.513825
meier/opensm-client-server
2
0
0
GPL-2.0
9/5/2024, 12:02:50 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
8,103
188,835
FileDetailPanel.java
DoctorD1501_JAVMovieScraper/src/main/java/moviescraper/doctord/view/FileDetailPanel.java
package moviescraper.doctord.view; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractListModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import moviescraper.doctord.controller.EditGenresAction; import moviescraper.doctord.controller.EditTagsAction; import moviescraper.doctord.model.Movie; import moviescraper.doctord.model.dataitem.Actor; import moviescraper.doctord.model.dataitem.Genre; import moviescraper.doctord.model.dataitem.ID; import moviescraper.doctord.model.dataitem.OriginalTitle; import moviescraper.doctord.model.dataitem.Plot; import moviescraper.doctord.model.dataitem.ReleaseDate; import moviescraper.doctord.model.dataitem.Set; import moviescraper.doctord.model.dataitem.Studio; import moviescraper.doctord.model.dataitem.Tag; import moviescraper.doctord.model.dataitem.Title; import moviescraper.doctord.model.dataitem.Year; import moviescraper.doctord.model.preferences.MoviescraperPreferences; import moviescraper.doctord.view.AbstractFileDetailPanelEditGUI.Operation; import moviescraper.doctord.view.renderer.ActressListRenderer; import com.jgoodies.forms.factories.FormFactory; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.RowSpec; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import javax.swing.DropMode; import javax.swing.JComponent; import javax.swing.ListSelectionModel; import javax.swing.TransferHandler; public class FileDetailPanel extends JPanel { private static final String NO_FILE_SELECTED = "No File Selected"; private static final long serialVersionUID = 7088761619568387476L; private JTextField txtFieldMovieTitleText; private JTextField txtFieldOriginalTitleText; private JTextField txtFieldScrapedYearText; private JTextField txtFieldIDCurrentMovie; private JTextField txtFieldStudio; private JTextField txtFieldMovieSet; private JTextArea moviePlotTextField; private JList<Actor> actorList; private JTextField genreList; private JTextField tagList; protected Movie currentMovie = getEmptyMovie(); MoviescraperPreferences preferences; private ArtWorkPanel artWorkPanel; private final static int DEFAULT_TEXTFIELD_LENGTH = 35; public GUIMain guiMain; public int currentListIndexOfDisplayedMovie = 0; private JTextField txtFieldReleaseDateText; private static final int COLUMN_LABEL = 2; private static final int COLUMN_FORM_FIELD = 4; private static final int COLUMN_ARTWORK_PANEL = 6; private static final int ROW_CHANGE_MOVIE_BUTTONS = 2; private static final int ROW_ARTWORK_PANEL = 2; private static final int ROW_FILE_PATH = 4; private static final int ROW_TITLE = 6; private static final int ROW_ORIGINAL_TITLE = 8; private static final int ROW_YEAR = 10; private static final int ROW_RELEASE_DATE = 12; private static final int ROW_ID = 14; private static final int ROW_STUDIO = 16; private static final int ROW_MOVIE_SET = 18; private static final int ROW_PLOT = 20; private static final int ROW_GENRES = 22; private static final int ROW_TAGS = 24; private static final int ROW_ACTORS = 26; private JButton previousMovieButton; private JButton nextMovieButton; private JTextField pathTextField; private JLabel numberInListSelectedLabel; /** * Create the panel. */ public FileDetailPanel(MoviescraperPreferences preferences, GUIMain gui) { this.preferences = preferences; this.guiMain = gui; JPanel fileDetailsPanel = this; FormLayout formLayout = new FormLayout(new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, // 1 - empty space FormFactory.DEFAULT_COLSPEC, //2 - label for each of the form items FormFactory.RELATED_GAP_COLSPEC, //3 - empty space ColumnSpec.decode("fill:pref:grow"), // 4 - Form text items FormFactory.RELATED_GAP_COLSPEC, //5 - empty space FormFactory.DEFAULT_COLSPEC, // 6 - artwork panel FormFactory.RELATED_GAP_COLSPEC,//7 - empty space }, new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, //1 - empty space FormFactory.DEFAULT_ROWSPEC, //2 - navigation buttons and artwork panel FormFactory.RELATED_GAP_ROWSPEC, //3 - empty space FormFactory.DEFAULT_ROWSPEC, //4 - File Path FormFactory.RELATED_GAP_ROWSPEC, //5 - empty space FormFactory.DEFAULT_ROWSPEC, //6 - Title FormFactory.RELATED_GAP_ROWSPEC, //7 - empty space FormFactory.DEFAULT_ROWSPEC, //8 - original title FormFactory.RELATED_GAP_ROWSPEC, //9 - empty space FormFactory.DEFAULT_ROWSPEC, //10 - Year FormFactory.RELATED_GAP_ROWSPEC, //11 - empty space FormFactory.DEFAULT_ROWSPEC, //12 - Release Date FormFactory.RELATED_GAP_ROWSPEC, //13 - empty space FormFactory.DEFAULT_ROWSPEC, //14 - ID FormFactory.RELATED_GAP_ROWSPEC, //15 - empty space FormFactory.DEFAULT_ROWSPEC, //16 - Studio FormFactory.RELATED_GAP_ROWSPEC, //17 - empty space FormFactory.DEFAULT_ROWSPEC, //18 - Movie set FormFactory.RELATED_GAP_ROWSPEC, //19 - empty space FormFactory.DEFAULT_ROWSPEC, //20 - Plot FormFactory.RELATED_GAP_ROWSPEC, //21 - empty space FormFactory.DEFAULT_ROWSPEC, //22 - genres FormFactory.RELATED_GAP_ROWSPEC, //23 - empty space FormFactory.DEFAULT_ROWSPEC, //24 - tags FormFactory.RELATED_GAP_ROWSPEC, //25 - empty space RowSpec.decode("fill:pref:grow"), //26 - actors FormFactory.RELATED_GAP_ROWSPEC//27 - empty space }); fileDetailsPanel.setLayout(formLayout); //next and previous buttons previousMovieButton = new JButton("<< Previous Movie"); previousMovieButton.addActionListener(e -> handlePreviousMovieSelected()); numberInListSelectedLabel = new JLabel("0 / 0"); nextMovieButton = new JButton("Next Movie >>"); nextMovieButton.addActionListener(e -> handleNextMovieSelected()); JPanel movieNavigationButtonsPanel = new JPanel(); movieNavigationButtonsPanel.add(previousMovieButton); movieNavigationButtonsPanel.add(numberInListSelectedLabel); movieNavigationButtonsPanel.add(nextMovieButton); changeEnabledStatusOfPreviousAndNextButtons(); fileDetailsPanel.add(movieNavigationButtonsPanel, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_CHANGE_MOVIE_BUTTONS)); //Path JLabel lblPath = new JLabel("Path:"); pathTextField = new JTextField(NO_FILE_SELECTED, DEFAULT_TEXTFIELD_LENGTH); pathTextField.setEditable(false); updatePathTextField(); fileDetailsPanel.add(pathTextField, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_FILE_PATH)); fileDetailsPanel.add(lblPath, getLayoutPositionString(COLUMN_LABEL, ROW_FILE_PATH)); //Movie title JLabel lblTitle = new JLabel("Title:"); fileDetailsPanel.add(lblTitle, getLayoutPositionString(COLUMN_LABEL, ROW_TITLE)); txtFieldMovieTitleText = new JTextField("", DEFAULT_TEXTFIELD_LENGTH); txtFieldMovieTitleText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentMovie != null) { String newValue = (String) txtFieldMovieTitleText.getText(); if (newValue != null && newValue.length() > 0) { currentMovie.setTitle(new Title(newValue)); guiMain.enableFileWrite(); } else { guiMain.disableFileWrite(); } } } }); txtFieldMovieTitleText.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String newValue = (String) txtFieldMovieTitleText.getText(); if (newValue != null && newValue.length() > 0) { currentMovie.setTitle(new Title(newValue)); guiMain.enableFileWrite(); } else { guiMain.disableFileWrite(); } } @Override public void keyPressed(KeyEvent e) { } }); fileDetailsPanel.add(txtFieldMovieTitleText, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_TITLE)); JLabel lblOriginalTitle = new JLabel("Original Title:"); fileDetailsPanel.add(lblOriginalTitle, getLayoutPositionString(COLUMN_LABEL, ROW_ORIGINAL_TITLE)); txtFieldOriginalTitleText = new JTextField("", DEFAULT_TEXTFIELD_LENGTH); txtFieldOriginalTitleText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentMovie != null) { String newValue = (String) txtFieldOriginalTitleText.getText(); if (newValue != null) { currentMovie.setOriginalTitle(new OriginalTitle(newValue)); } } } }); txtFieldOriginalTitleText.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String newValue = (String) txtFieldOriginalTitleText.getText(); if (newValue != null) { currentMovie.setOriginalTitle(new OriginalTitle(newValue)); } } @Override public void keyPressed(KeyEvent e) { } }); fileDetailsPanel.add(txtFieldOriginalTitleText, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_ORIGINAL_TITLE)); JLabel lblYear = new JLabel("Year:"); fileDetailsPanel.add(lblYear, getLayoutPositionString(COLUMN_LABEL, ROW_YEAR)); txtFieldScrapedYearText = new JTextField("", 4); fileDetailsPanel.add(txtFieldScrapedYearText, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_YEAR)); txtFieldScrapedYearText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentMovie != null) { String newValue = (String) txtFieldScrapedYearText.getText(); if (newValue != null) { currentMovie.setYear(new Year(newValue)); } } } }); txtFieldScrapedYearText.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String newValue = (String) txtFieldScrapedYearText.getText(); if (newValue != null) { currentMovie.setYear(new Year(newValue)); } } @Override public void keyPressed(KeyEvent e) { } }); JLabel lblReleaseDate = new JLabel("Release Date:"); fileDetailsPanel.add(lblReleaseDate, getLayoutPositionString(COLUMN_LABEL, ROW_RELEASE_DATE)); txtFieldReleaseDateText = new JTextField("", 12); txtFieldReleaseDateText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentMovie != null) { String newValue = (String) txtFieldReleaseDateText.getText(); if (newValue != null) { currentMovie.setReleaseDate(new ReleaseDate(newValue)); } } } }); txtFieldReleaseDateText.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String newValue = (String) txtFieldReleaseDateText.getText(); if (newValue != null) { currentMovie.setReleaseDate(new ReleaseDate(newValue)); } } @Override public void keyPressed(KeyEvent e) { } }); fileDetailsPanel.add(txtFieldReleaseDateText, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_RELEASE_DATE)); JLabel lblID = new JLabel("ID:"); fileDetailsPanel.add(lblID, getLayoutPositionString(COLUMN_LABEL, ROW_ID)); txtFieldIDCurrentMovie = new JTextField("", DEFAULT_TEXTFIELD_LENGTH); txtFieldIDCurrentMovie.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentMovie != null) { String newValue = (String) txtFieldIDCurrentMovie.getText(); if (newValue != null) { currentMovie.setId(new ID(newValue)); } } } }); txtFieldIDCurrentMovie.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String newValue = (String) txtFieldIDCurrentMovie.getText(); if (newValue != null) { currentMovie.setId(new ID(newValue)); } } @Override public void keyPressed(KeyEvent e) { } }); fileDetailsPanel.add(txtFieldIDCurrentMovie, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_ID)); JLabel lblStudio = new JLabel("Studio:"); txtFieldStudio = new JTextField("", DEFAULT_TEXTFIELD_LENGTH); txtFieldStudio.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentMovie != null) { String newValue = (String) txtFieldStudio.getText(); if (newValue != null) { currentMovie.setStudio(new Studio(newValue)); } } } }); txtFieldStudio.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String newValue = (String) txtFieldStudio.getText(); if (newValue != null) { currentMovie.setStudio(new Studio(newValue)); } } @Override public void keyPressed(KeyEvent e) { } }); fileDetailsPanel.add(lblStudio, getLayoutPositionString(COLUMN_LABEL, ROW_STUDIO)); fileDetailsPanel.add(txtFieldStudio, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_STUDIO)); JLabel lblSet = new JLabel("Movie Set:"); fileDetailsPanel.add(lblSet, getLayoutPositionString(COLUMN_LABEL, ROW_MOVIE_SET)); txtFieldMovieSet = new JTextField("", DEFAULT_TEXTFIELD_LENGTH); txtFieldMovieSet.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentMovie != null) { String newValue = (String) txtFieldMovieSet.getText(); if (newValue != null) { currentMovie.setSet(new Set(newValue)); } } } }); txtFieldMovieSet.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String newValue = (String) txtFieldMovieSet.getText(); if (newValue != null) { currentMovie.setSet(new Set(newValue)); } } @Override public void keyPressed(KeyEvent e) { } }); fileDetailsPanel.add(txtFieldMovieSet, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_MOVIE_SET)); JLabel lblPlot = new JLabel("Plot:"); fileDetailsPanel.add(lblPlot, getLayoutPositionString(COLUMN_LABEL, ROW_PLOT)); moviePlotTextField = new JTextArea(3, 35); moviePlotTextField.setLineWrap(true); moviePlotTextField.setWrapStyleWord(true); moviePlotTextField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String newValue = (String) moviePlotTextField.getText(); if (newValue != null) { currentMovie.setPlot(new Plot(newValue)); } } @Override public void keyPressed(KeyEvent e) { } }); JScrollPane plotPanelScrollPane = new JScrollPane(moviePlotTextField, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); fileDetailsPanel.add(plotPanelScrollPane, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_PLOT)); JLabel lblActors = new JLabel("Actors:"); fileDetailsPanel.add(lblActors, getLayoutPositionString(COLUMN_LABEL, ROW_ACTORS)); actorList = new JList<>(new ActorItemListModel()); actorList.setDragEnabled(true); actorList.setDropMode(DropMode.INSERT); actorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); actorList.setTransferHandler(new ActorTransferHandler(actorList)); List<File> currentlySelectedActorsFolderList = new ArrayList<>(); if (gui != null) currentlySelectedActorsFolderList = gui.getCurrentlySelectedActorsFolderList(); actorList.setCellRenderer(new ActressListRenderer(currentlySelectedActorsFolderList)); actorList.setComponentPopupMenu(new FileDetailPanelPopup(new FileDetailPanelActorEditor(this))); actorList.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { actorList.setSelectedIndex(actorList.locationToIndex(e.getPoint())); } //double or triple click the actor list to open the editor on the item you clicked @Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2 || evt.getClickCount() == 3) { // Double-click detected FileDetailPanelActorEditor actorEditor = new FileDetailPanelActorEditor(FileDetailPanel.this); actorEditor.showGUI(Operation.EDIT); } } }); JScrollPane actorListScroller = new JScrollPane(actorList); actorListScroller.setPreferredSize(new Dimension(250, 250)); fileDetailsPanel.add(actorListScroller, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_ACTORS)); JLabel lblGenres = new JLabel("Genres:"); fileDetailsPanel.add(lblGenres, getLayoutPositionString(COLUMN_LABEL, ROW_GENRES)); genreList = new JTextField("", DEFAULT_TEXTFIELD_LENGTH); //the user clicks the field to edit it - we don't want them typing directly here genreList.addKeyListener(new KeyListenerIgnoreTyping()); genreList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { EditGenresAction editGenresAction = new EditGenresAction(FileDetailPanel.this); editGenresAction.actionPerformed(null); } }); fileDetailsPanel.add(genreList, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_GENRES)); JLabel lblTags = new JLabel("Tags:"); fileDetailsPanel.add(lblTags, getLayoutPositionString(COLUMN_LABEL, ROW_TAGS)); tagList = new JTextField("", DEFAULT_TEXTFIELD_LENGTH); //the user clicks the field to edit it - we don't want them typing directly here tagList.addKeyListener(new KeyListenerIgnoreTyping()); tagList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { EditTagsAction editTagsAction = new EditTagsAction(FileDetailPanel.this); editTagsAction.actionPerformed(null); } }); fileDetailsPanel.add(tagList, getLayoutPositionString(COLUMN_FORM_FIELD, ROW_TAGS)); artWorkPanel = new ArtWorkPanel(guiMain); //frmMoviescraper.getContentPane().add(artworkPanelScrollPane, BorderLayout.EAST); String beginRow = "1"; String rowsToSpan = Integer.toString((formLayout.getRowCount() - 1)); String rowSpanConstraintString = "," + beginRow + "," + rowsToSpan; fileDetailsPanel.add(artWorkPanel, getLayoutPositionString(COLUMN_ARTWORK_PANEL, ROW_ARTWORK_PANEL) + rowSpanConstraintString); } public void updatePathTextField() { int positionOfCurrentMovie = findPositionOfCurrentlySelectedMovie(); if (positionOfCurrentMovie >= 0 && guiMain.getCurrentlySelectedMovieFileList().size() > positionOfCurrentMovie) { File currentlyShowingFile = guiMain.getCurrentlySelectedMovieFileList().get(positionOfCurrentMovie); if (currentlyShowingFile != null && currentlyShowingFile.exists()) { pathTextField.setText(currentlyShowingFile.getAbsolutePath().toString()); pathTextField.setCaretPosition(0); } } else { pathTextField.setText(""); } } /** * Updates the view by setting the previous selected movie as the movie which is showing */ private void handlePreviousMovieSelected() { int positionOfCurrentMovie = findPositionOfCurrentlySelectedMovie(); if (positionOfCurrentMovie == -1) positionOfCurrentMovie = currentListIndexOfDisplayedMovie; int positionOfPreviousMovie = positionOfCurrentMovie - 1; if (positionOfCurrentMovie >= 0 && positionOfPreviousMovie < guiMain.movieToWriteToDiskList.size() && positionOfPreviousMovie >= 0) { Movie previousMovie = guiMain.movieToWriteToDiskList.get(positionOfPreviousMovie); //if (previousMovie != null) { currentListIndexOfDisplayedMovie = positionOfPreviousMovie; setNewMovie(previousMovie, false, false); //} } } /** * Updates the view by setting the next selected movie as the movie which is showing */ private void handleNextMovieSelected() { int positionOfCurrentMovie = findPositionOfCurrentlySelectedMovie(); if (positionOfCurrentMovie == -1) positionOfCurrentMovie = currentListIndexOfDisplayedMovie; int positionOfNextMovie = positionOfCurrentMovie + 1; if (positionOfCurrentMovie >= 0 && positionOfNextMovie < guiMain.movieToWriteToDiskList.size()) { Movie nextMovie = guiMain.movieToWriteToDiskList.get(positionOfNextMovie); //if (nextMovie != null) { currentListIndexOfDisplayedMovie = positionOfNextMovie; setNewMovie(nextMovie, false, false); //} } } //returns -1 if not found private int findPositionOfCurrentlySelectedMovie() { if (guiMain != null && guiMain.movieToWriteToDiskList != null && currentMovie != null) { for (int i = 0; i < guiMain.movieToWriteToDiskList.size(); i++) { if (guiMain.movieToWriteToDiskList.get(i) != null && guiMain.movieToWriteToDiskList.get(i).equals(currentMovie)) return i; } } return -1; } /** * Sets a new movie and updates a view * * @param newMovie the movie this fileDetailPanel will show * @param forcePosterUpdate whether to force a redownload from the poster defined in the Thumb url */ public void setNewMovie(Movie newMovie, boolean forcePosterUpdate) { setNewMovie(newMovie, forcePosterUpdate, false); } /** * Sets a new movie and updates a view * * @param newMovie the movie this fileDetailPanel will show * @param forcePosterUpdate whether to force a redownload from the poster defined in the Thumb url * @param modifyWriteToDiskList - whether to modify the gui object's disk list by adding the currently viewed item if the disk list is empty */ public void setNewMovie(Movie newMovie, boolean forcePosterUpdate, boolean modifyWriteToDiskList) { //System.out.println("Setting new movie: " + newMovie); if (newMovie != null) { setCurrentMovie(newMovie); updateView(forcePosterUpdate, modifyWriteToDiskList); } else { clearView(); updatePathTextField(); changeEnabledStatusOfPreviousAndNextButtons(); updateNumberInListSelectedLabel(); updateView(true, false); } } public void clearView() { artWorkPanel.clearPictures(); setTitleEditable(false); this.currentMovie = getEmptyMovie(); } /** * Updates the view for the current movie * * @param forcePosterUpdate - if force a refresh of the poster from the URL by downloading the file. If false, tries to * read from the local file first * @param newMovieWasSet - true if you are setting a new movie. clears the old one and refreshes all fields */ public void updateView(boolean forcePosterUpdate, boolean newMovieWasSet) { List<Movie> movieToWriteToDiskList = guiMain.getMovieToWriteToDiskList(); //do i need this? //currentListIndexOfDisplayedMovie = Math.max(findPositionOfCurrentlySelectedMovie(),0); if (newMovieWasSet && movieToWriteToDiskList.size() == 0) { movieToWriteToDiskList.add(currentMovie); } //begin if ((movieToWriteToDiskList == null || movieToWriteToDiskList.size() == 0) && !newMovieWasSet) { clearView(); } else if (movieToWriteToDiskList != null && movieToWriteToDiskList.get(currentListIndexOfDisplayedMovie) != null) { if (!newMovieWasSet) clearView(); if (!newMovieWasSet) this.setCurrentMovie(movieToWriteToDiskList.get(currentListIndexOfDisplayedMovie)); //All the titles from the various versions scraped of this movie from the different sites this.getCurrentMovie().getAllTitles().add(getCurrentMovie().getTitle()); String fileName = this.getCurrentMovie().getFileName(); if (fileName != null && fileName.trim().length() > 0) this.getCurrentMovie().getAllTitles().add(new Title(fileName)); if (this.getCurrentMovie().getAllTitles().size() > 0) this.setTitleEditable(true); //end } txtFieldMovieTitleText.setText(currentMovie.getTitle().getTitle()); txtFieldMovieTitleText.setCaretPosition(0); txtFieldOriginalTitleText.setText(currentMovie.getOriginalTitle().getOriginalTitle()); txtFieldOriginalTitleText.setCaretPosition(0); txtFieldScrapedYearText.setText(currentMovie.getYear().getYear()); txtFieldReleaseDateText.setText(currentMovie.getReleaseDate().getReleaseDate()); txtFieldIDCurrentMovie.setText(currentMovie.getId().getId()); txtFieldStudio.setText(currentMovie.getStudio().getStudio()); txtFieldStudio.setCaretPosition(0); txtFieldMovieSet.setText(currentMovie.getSet().getSet()); txtFieldMovieSet.setCaretPosition(0); moviePlotTextField.setText(currentMovie.getPlot().getPlot()); moviePlotTextField.setCaretPosition(0); genreList.setText(toGenreListFormat(currentMovie.getGenres())); genreList.setCaretPosition(0); tagList.setText(toTagListFormat(currentMovie.getTags())); tagList.setCaretPosition(0); //Actors and Genres are automatically generated actorList.updateUI(); artWorkPanel.updateView(forcePosterUpdate, guiMain); if (txtFieldMovieTitleText.getText().length() > 0) { guiMain.enableFileWrite(); } else { guiMain.disableFileWrite(); } updatePathTextField(); changeEnabledStatusOfPreviousAndNextButtons(); updateNumberInListSelectedLabel(); } private void changeEnabledStatusOfPreviousAndNextButtons() { List<Movie> movieList = guiMain.getMovieToWriteToDiskList(); System.out.println("Movie Size: " + movieList.size()); //no movies to scroll through if (movieList.size() == 0) { nextMovieButton.setEnabled(false); previousMovieButton.setEnabled(false); return; } if ((currentListIndexOfDisplayedMovie - 1) < 0) { previousMovieButton.setEnabled(false); } else previousMovieButton.setEnabled(true); if ((currentListIndexOfDisplayedMovie + 1) >= movieList.size()) { nextMovieButton.setEnabled(false); } else nextMovieButton.setEnabled(true); } //Updates the label which shows what movie number we are on: e.g. 1/5 private void updateNumberInListSelectedLabel() { int movieNumberIAmOn = currentListIndexOfDisplayedMovie + 1; int numberOfMovies = guiMain.getMovieToWriteToDiskList().size(); numberInListSelectedLabel.setText(movieNumberIAmOn + " / " + numberOfMovies); } public Movie getCurrentMovie() { return currentMovie; } public Movie getEmptyMovie() { return Movie.getEmptyMovie(); } public void setTitleEditable(boolean value) { txtFieldMovieTitleText.setEditable(value); } public ArtWorkPanel getArtWorkPanel() { return artWorkPanel; } public JList<Actor> getActorList() { return actorList; } public void setActorList(JList<Actor> actorList) { this.actorList = actorList; } public JTextField getGenreList() { return genreList; } public void setGenreList(JTextField genreList) { this.genreList = genreList; } public JTextField getTagList() { return tagList; } public void setTagList(JTextField tagList) { this.tagList = tagList; } public void setCurrentMovie(Movie currentMovie) { this.currentMovie = currentMovie; } public void hideArtworkPanel() { artWorkPanel.setVisible(false); } private final class KeyListenerIgnoreTyping implements KeyListener { @Override public void keyTyped(KeyEvent e) { e.consume(); } @Override public void keyPressed(KeyEvent e) { e.consume(); } @Override public void keyReleased(KeyEvent e) { e.consume(); } } public class GenreItemListModel extends DefaultListModel<Genre> { private static final long serialVersionUID = 973741706455659871L; @Override public Genre getElementAt(int index) { Genre genre = currentMovie.getGenres().get(index); return (genre != null) ? genre : new Genre(""); } @Override public int getSize() { return currentMovie.getGenres().size(); } } class ActorItemListModel extends AbstractListModel<Actor> { private static final long serialVersionUID = 276453659002862686L; @Override public Actor getElementAt(int index) { return currentMovie.getActors().get(index); } public Actor remove(int index) { return currentMovie.getActors().remove(index); } public void add(int index, Actor actor) { currentMovie.getActors().add(index, actor); } public int indexOf(Actor actor) { return currentMovie.getActors().indexOf(actor); } public boolean removeElement(Actor actor) { return currentMovie.getActors().remove(actor); } @Override public int getSize() { return currentMovie.getActors().size(); } } public static String toGenreListFormat(ArrayList<Genre> genres) { String genreText = ""; for (Genre currentGenre : genres) { genreText += currentGenre.getGenre(); genreText += " \\ "; } if (genreText.endsWith(" \\ ")) { genreText = genreText.substring(0, genreText.length() - 3); } return genreText; } public static String toTagListFormat(ArrayList<Tag> tags) { String tagText = ""; for (Tag currentTag : tags) { tagText += currentTag.getTag(); tagText += " \\ "; } if (tagText.endsWith(" \\ ")) { tagText = tagText.substring(0, tagText.length() - 3); } return tagText; } private String getLayoutPositionString(int columnNumber, int rowNumber) { return columnNumber + ", " + rowNumber; } static class ActorTransferHandler extends TransferHandler { private static final DataFlavor DATA_FLAVOUR = new DataFlavor(Actor.class, "Actor"); private final JList actorList; private boolean inDrag; ActorTransferHandler(JList actorList) { this.actorList = actorList; } @Override public int getSourceActions(JComponent c) { return TransferHandler.MOVE; } @Override protected Transferable createTransferable(JComponent c) { inDrag = true; return new Transferable() { @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DATA_FLAVOUR }; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.equals(DATA_FLAVOUR); } @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (flavor != DATA_FLAVOUR) { return new UnsupportedFlavorException(flavor); } return actorList.getSelectedValue(); } }; } @Override public boolean canImport(TransferSupport support) { if (!inDrag || !support.isDataFlavorSupported(DATA_FLAVOUR)) { return false; } JList.DropLocation dl = (JList.DropLocation) support.getDropLocation(); if (dl.getIndex() == -1) { return false; } else { return true; } } @Override public boolean importData(TransferSupport support) { if (!canImport(support)) { return false; } Transferable transferable = support.getTransferable(); try { Actor draggedActor = (Actor) transferable.getTransferData(DATA_FLAVOUR); JList.DropLocation dl = (JList.DropLocation) support.getDropLocation(); ActorItemListModel model = (ActorItemListModel) actorList.getModel(); int dropIndex = dl.getIndex(); if (model.indexOf(draggedActor) < dropIndex) { dropIndex--; } model.removeElement(draggedActor); model.add(dropIndex, draggedActor); return true; } catch (UnsupportedFlavorException e) { return false; } catch (IOException e) { e.printStackTrace(); return false; } } @Override protected void exportDone(JComponent source, Transferable data, int action) { super.exportDone(source, data, action); inDrag = false; this.actorList.repaint(); } } }
31,769
Java
.java
812
35.221675
151
0.759851
DoctorD1501/JAVMovieScraper
752
161
126
GPL-2.0
9/4/2024, 7:05:18 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
31,769
2,045,814
C_Strong_Password.java
sagnikghoshcr7_Competitive-Programming/Practice Questions/Codeforces/C_Strong_Password.java
// JAI SHREE RAM /* ░██████╗░█████╗░░██████╗░███╗░░██╗██╗██╗░░██╗░██████╗░██╗░░██╗░█████╗░░██████╗██╗░░██╗░█████╗░██████╗░███████╗ ██╔════╝██╔══██╗██╔════╝░████╗░██║██║██║░██╔╝██╔════╝░██║░░██║██╔══██╗██╔════╝██║░░██║██╔══██╗██╔══██╗╚════██║ ╚█████╗░███████║██║░░██╗░██╔██╗██║██║█████═╝░██║░░██╗░███████║██║░░██║╚█████╗░███████║██║░░╚═╝██████╔╝░░░░██╔╝ ░╚═══██╗██╔══██║██║░░╚██╗██║╚████║██║██╔═██╗░██║░░╚██╗██╔══██║██║░░██║░╚═══██╗██╔══██║██║░░██╗██╔══██╗░░░██╔╝░ ██████╔╝██║░░██║╚██████╔╝██║░╚███║██║██║░╚██╗╚██████╔╝██║░░██║╚█████╔╝██████╔╝██║░░██║╚█████╔╝██║░░██║░░██╔╝░░ ╚═════╝░╚═╝░░╚═╝░╚═════╝░╚═╝░░╚══╝╚═╝╚═╝░░╚═╝░╚═════╝░╚═╝░░╚═╝░╚════╝░╚═════╝░╚═╝░░╚═╝░╚════╝░╚═╝░░╚═╝░░╚═╝░░░ */ import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class C_Strong_Password { static Scanner sc = new Scanner(System.in); static FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static final Random random = new Random(); static final int mod = 1_000_000_007; static final int MAXN = 1000001; static StringBuilder sb = new StringBuilder(); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static long [] larr = new long[100001]; static int cnt = 0, tmpSum = 0; private static void sagnik() throws IOException { String s = fs.next(); List<List<Integer>> plist = new ArrayList<>(10); List<Integer> ind = new ArrayList<>(10); for (int i = 0; i < 10; i++) { plist.add(new ArrayList<>()); ind.add(0); } for (int i = 0; i < s.length(); i++) { int digit = s.charAt(i) - '0'; plist.get(digit).add(i); } int m = fs.nextInt(); String lr = fs.next(); String rr = fs.next(); int curr = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < 10; j++) while (ind.get(j) < plist.get(j).size() && plist.get(j).get(ind.get(j)) < curr) ind.set(j, ind.get(j) + 1); int flag = curr; for (int j = lr.charAt(i) - '0'; j <= rr.charAt(i) - '0'; j++) { if (ind.get(j) >= plist.get(j).size()) flag = s.length(); else flag = Math.max(flag, plist.get(j).get(ind.get(j))); } curr = flag + 1; } out.println(curr >= s.length() + 1 ? "YES" : "NO"); out.flush(); } public static void main(String[] args) throws IOException { int t = fs.nextInt(); while(t-->0) sagnik(); } // Make t = 1 baby // dont worry bout me, i'm not high private static int arrMax(int[] A) {return Arrays.stream(A).max().getAsInt();} private static int arrMin(int[] A) {return Arrays.stream(A).min().getAsInt();} private static int arrSum(int[] A) {return Arrays.stream(A).sum();} private static int countNumInArr(int[] A, int n) {return (int) Arrays.stream(A).filter(x -> x == n).count();} private static void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } private static void reverse(int[] A) {int s=0,e=A.length-1;while(s<e){swap(A,s,e);s++;e--;}} private static void reverse(int[] A, int s) {int e=A.length-1;while(s<e){swap(A,s,e);s++;e--;}} private static void reverse(int[] A, int s, int e) {while(s<e){swap(A,s,e);s++;e--;}} private static int countSetBits(int number){int count=0; while(number>0){++count; number &= number-1;} return count;} private static boolean isEven(int i) { return (i & 1) == 0; } private static boolean isVowel(char c) { return c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U';} private static boolean isPrime(int x) {if(x==1) return false; for(int i=2; i*i<=x; i++){if(x%i==0) return false;} return true;} public static boolean[] genSieve(int n) {boolean[] A = new boolean[n+1]; for(int i=0;i<n;i++) A[i] = true; for(int p=2; p*p <=n; p++) if(A[p]) for(int i = p*2; i<=n; i+=p) A[i] = false; return A;} private static int gcd(int a, int b) {if (b == 0) return a; return gcd(b, a % b);} private static int lcm(int a, int b) {return (a*b)/gcd(a, b);} private static int[] listToArr(List<Integer> x) {return x.stream().mapToInt(i -> i).toArray();} private static int[] setArray(int n) {int A[]=new int[n]; for(int i=0;i<n;i++) A[i]=sc.nextInt(); return A;} private static long[] lsetArray(int n) {long A[]=new long[n]; for(int i=0;i<n;i++) A[i]=sc.nextLong(); return A;} private static void prtList(List<Integer> x) {for(int i : x) {System.out.print(i+" ");}} private static void prtArr(int[] A) {System.out.println(Arrays.toString(A));} private static void prtArrWithSpce(int[] A) {for(int i=0;i<A.length;i++)System.out.print(A[i]+" ");} private static void prtArrWithSpce(int[] A, int s) {for(int i=s;i<A.length;i++)System.out.print(A[i]+" ");} private static void prtArrWithSpce(int[] A, int s, int e) {for(int i=s;i<=e;i++)System.out.print(A[i]+" ");} private static void debug(Object... o) {if(o.length != 0) System.err.println(Arrays.deepToString(o)); else System.err.println();} // DecimalFormat df = new DecimalFormat("#.###"); // DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(12); // System.out.println(df.format(input_Decimal_Here)); // fastIO cos why not public static class FastScanner { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer st = new StringTokenizer(""); private static String next() throws IOException {while(!st.hasMoreTokens()) try {st=new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();} return st.nextToken();} private static int[] setArray(int n) throws IOException {int[] a = new int[n]; for (int i=0; i<n; i++) a[i] = nextInt(); return a;} private static long[] lsetArray(int n) throws IOException {long a[] = new long[n]; for(int i=0; i<n; i++) a[i] = nextLong(); return a;} private static int nextInt() throws IOException {return Integer.parseInt(next());} private static Long nextLong() throws IOException {return Long.parseLong(next());} private static double nextDouble() throws IOException {return Double.parseDouble(next());} private static char nextChar() throws IOException {return next().toCharArray()[0];} private static String nextString() throws IOException {return next();} private static String nextLine() throws IOException {return br.readLine();} private static String nextToken() throws IOException {while (st == null || !st.hasMoreElements()) {try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} private static BigInteger nextBigInteger() throws IOException {return new BigInteger(next());} } }
8,580
Java
.java
104
63.201923
223
0.553904
sagnikghoshcr7/Competitive-Programming
11
3
0
GPL-3.0
9/4/2024, 8:27:28 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,260
4,888,335
WithholdingTax.java
chrisbjr_philippine-income-tax-android/Philippine Income Tax/src/main/java/ph/coreproc/android/philippineincometax/objects/WithholdingTax.java
package ph.coreproc.android.philippineincometax.objects; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.math.BigDecimal; @DatabaseTable(tableName = "withholding_tax") public class WithholdingTax { @DatabaseField(generatedId = true) private int id; @DatabaseField private int withholdingTaxTypeId; @DatabaseField private int dependents; @DatabaseField private String computationFrequency; @DatabaseField private double taxableIncomeFrom; @DatabaseField private double taxableIncomeTo; @DatabaseField private double baseTax; @DatabaseField private double percentOver; private double taxableIncome = 0; public WithholdingTax() { // ORMLite needs this } public WithholdingTax(String[] csvLine) { this.id = Integer.parseInt(csvLine[0]); this.withholdingTaxTypeId = Integer.parseInt(csvLine[1]); this.dependents = Integer.parseInt(csvLine[2]); this.computationFrequency = csvLine[3]; this.taxableIncomeFrom = Double.parseDouble(csvLine[4]); this.taxableIncomeTo = Double.parseDouble(csvLine[5]); this.baseTax = Double.parseDouble(csvLine[6]); this.percentOver = Double.parseDouble(csvLine[7]); } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getWithholdingTaxTypeId() { return withholdingTaxTypeId; } public void setWithholdingTaxTypeId(int withholdingTaxTypeId) { this.withholdingTaxTypeId = withholdingTaxTypeId; } public int getDependents() { return dependents; } public void setDependents(int dependents) { this.dependents = dependents; } public String getComputationFrequency() { return computationFrequency; } public void setComputationFrequency(String computationFrequency) { this.computationFrequency = computationFrequency; } public double getTaxableIncomeFrom() { return taxableIncomeFrom; } public void setTaxableIncomeFrom(double taxableIncomeFrom) { this.taxableIncomeFrom = taxableIncomeFrom; } public double getTaxableIncomeTo() { return taxableIncomeTo; } public void setTaxableIncomeTo(double taxableIncomeTo) { this.taxableIncomeTo = taxableIncomeTo; } public double getBaseTax() { return baseTax; } public void setBaseTax(double baseTax) { this.baseTax = baseTax; } public double getPercentOver() { return percentOver; } public void setPercentOver(double percentOver) { this.percentOver = percentOver; } public double getTaxableIncome() { return taxableIncome; } public void setTaxableIncome(double taxableIncome) { this.taxableIncome = taxableIncome; } public double getWithholdingTaxAmount() { return round( ((getTaxableIncome() - getTaxableIncomeFrom()) * (getPercentOver() / 100)) + getBaseTax(), 2); } private double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP); return Double.parseDouble(bd.toString()); } }
3,025
Java
.java
103
26.747573
78
0.792603
chrisbjr/philippine-income-tax-android
1
0
0
GPL-3.0
9/5/2024, 12:34:55 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,025
1,515,495
JavaFXShape.java
Lonzak_JPedal/src/org/jpedal/render/output/javafx/JavaFXShape.java
/* * =========================================== * Java Pdf Extraction Decoding Access Library * =========================================== * * Project Info: http://www.idrsolutions.com * Help section for developers at http://www.idrsolutions.com/java-pdf-library-support/ * * (C) Copyright 1997-2013, IDRsolutions and Contributors. * * This file is part of JPedal * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * --------------- * JavaFXShape.java * --------------- */ package org.jpedal.render.output.javafx; import java.awt.BasicStroke; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import org.jpedal.color.PdfPaint; import org.jpedal.objects.GraphicsState; import org.jpedal.objects.PdfPageData; import org.jpedal.render.ShapeFactory; import org.jpedal.render.output.OutputShape; public class JavaFXShape extends OutputShape implements ShapeFactory { // JavaFX supports both winding rules, it's default is non-zero private int windingRule = PathIterator.WIND_NON_ZERO; public JavaFXShape(int cmd, int shapeCount, float scaling, Shape currentShape, GraphicsState gs, AffineTransform scalingTransform, Point2D midPoint, Rectangle cropBox, int currentColor, int dpCount, int pageRotation, PdfPageData pageData, int pageNumber, boolean includeClip) { super(cmd, scaling, currentShape, gs, scalingTransform, midPoint, cropBox, currentColor, dpCount, pageRotation, pageData, pageNumber, includeClip); this.shapeCount = shapeCount; this.windingRule = currentShape.getPathIterator(scalingTransform).getWindingRule(); // Added winding rule via shape iterator generateShapeFromG2Data(gs, scalingTransform, cropBox); } @Override protected void beginShape() { this.pathCommands.add("\n"); this.pathCommands.add("\tPath path_" + this.shapeCount + " = new Path();"); this.pathCommands.add("\tObservableList<PathElement> shape_" + this.shapeCount + " = path_" + this.shapeCount + ".getElements();"); this.pathCommands.add("\taddToGroup.add(path_" + this.shapeCount + ");");// add the shape to the group } @Override protected void lineTo(double[] coords) { this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new LineTo(" + coordsToStringParam(coords, 2) + "));"); } @Override protected void bezierCurveTo(double[] coords) { this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new CubicCurveTo(" + coordsToStringParam(coords, 6) + "));"); } @Override protected void quadraticCurveTo(double[] coords) { this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new QuadCurveTo(" + coordsToStringParam(coords, 4) + "));"); } @Override protected void moveTo(double[] coords) { this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new MoveTo(" + coordsToStringParam(coords, 2) + "));"); } @Override protected void closePath() { this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new ClosePath());"); } @Override protected void drawCropBox() { this.pathCommands.clear(); this.pathCommands.add("\n\t\t/**"); this.pathCommands.add("\t* Crop Box properties"); this.pathCommands.add("\t*/ "); this.pathCommands.add("\tPath path_" + this.shapeCount + " = new Path();"); this.pathCommands.add("\tObservableList<PathElement> " + "shape_" + this.shapeCount + " = path_" + this.shapeCount + ".getElements();"); this.pathCommands.add("\taddToGroup.add(path_" + this.shapeCount + ");");// add the cropBox to the group double[] coords = { this.cropBox.x, this.cropBox.y }; this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new MoveTo(" + convertCoords(coords, 2) + "));"); coords[0] += this.cropBox.width; this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new LineTo(" + convertCoords(coords, 2) + "));"); coords[1] += this.cropBox.height; this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new LineTo(" + convertCoords(coords, 2) + "));"); coords[0] -= this.cropBox.width; this.pathCommands.add("\tshape_" + this.shapeCount + ".add(new LineTo(" + convertCoords(coords, 2) + "));"); } @Override protected void applyGraphicsStateToPath(GraphicsState gs) { int fillType = gs.getFillType(); if (fillType == GraphicsState.FILL || fillType == GraphicsState.FILLSTROKE) { PdfPaint col = gs.getNonstrokeColor(); if (this.windingRule == PathIterator.WIND_EVEN_ODD) { this.pathCommands.add("\tpath_" + this.shapeCount + ".setFillRule(FillRule.EVEN_ODD);"); } float fillOpacity = gs.getAlpha(GraphicsState.FILL); if (fillOpacity != 1) { this.pathCommands.add("\tpath_" + this.shapeCount + ".setOpacity(" + fillOpacity + ");"); } this.pathCommands.add("\tpath_" + this.shapeCount + ".setStroke(null);"); // The default value is null for all shapes except Line, // Polyline, and Path. The default value is Color.BLACK for // those shapes. this.pathCommands.add("\tpath_" + this.shapeCount + ".setFill(Color." + rgbToCSSColor(col.getRGB()) + ");"); this.currentColor = col.getRGB(); } if (fillType == GraphicsState.STROKE || fillType == GraphicsState.FILLSTROKE) { BasicStroke stroke = (BasicStroke) gs.getStroke(); // allow for any opacity float strokeOpacity = gs.getAlpha(GraphicsState.STROKE); if (strokeOpacity != 1) { this.pathCommands.add("\tpath_" + this.shapeCount + ".setOpacity(" + strokeOpacity + ");"); // JavaFX fills & strokes cannot have // separate opacities. } if (gs.getOutputLineWidth() != 1) { // attribute double lineWidth; (default 1) this.pathCommands.add("\tpath_" + this.shapeCount + ".setStrokeWidth(" + gs.getOutputLineWidth() + ");"); } if (stroke.getMiterLimit() != 10) { // attribute double miterLimit; // (default 10) this.pathCommands.add("\tpath_" + this.shapeCount + ".setStrokeMiterLimit(" + ((double) stroke.getLineWidth() * this.scaling) + ");"); } this.pathCommands.add("\tpath_" + this.shapeCount + ".setStrokeLineCap(StrokeLineCap." + determineLineCap(stroke) + ");"); this.pathCommands.add("\tpath_" + this.shapeCount + ".setStrokeLineJoin(StrokeLineJoin." + determineLineJoin(stroke) + ");"); PdfPaint col = gs.getStrokeColor(); this.pathCommands.add("\tpath_" + this.shapeCount + ".setStroke(Color." + rgbToCSSColor(col.getRGB()) + ");"); } } /** * Extract line cap attribute javaFX implementation */ protected static String determineLineCap(BasicStroke stroke) {// javaFX implementation // attribute DOMString lineCap; // "butt", "round", "square" (default "butt") String attribute; switch (stroke.getEndCap()) { case (BasicStroke.CAP_ROUND): attribute = "ROUND"; break; case (BasicStroke.CAP_SQUARE): attribute = "SQUARE"; break; default: attribute = "BUTT"; break; } return attribute; } /** * Extract line join attribute javaFX implementation */ protected static String determineLineJoin(BasicStroke stroke) {// javaFX implementation // attribute DOMString lineJoin; // "round", "bevel", "miter" (default "miter") String attribute; switch (stroke.getLineJoin()) { case (BasicStroke.JOIN_ROUND): attribute = "ROUND"; break; case (BasicStroke.JOIN_BEVEL): attribute = "BEVEL"; break; default: attribute = "MITER"; break; } return attribute; } @Override public void setShapeNumber(int shapeCount) { this.shapeCount = shapeCount; } }
8,217
Java
.java
178
42.561798
138
0.700987
Lonzak/JPedal
20
8
1
LGPL-2.1
9/4/2024, 7:55:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
8,217
5,128,202
RuleEventFactory.java
JONA-GA_smarthome/bundles/automation/org.eclipse.smarthome.automation.api/src/main/java/org/eclipse/smarthome/automation/events/RuleEventFactory.java
/** * Copyright (c) 2014,2018 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.smarthome.automation.events; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.eclipse.smarthome.automation.Rule; import org.eclipse.smarthome.automation.RuleStatusInfo; import org.eclipse.smarthome.automation.dto.RuleDTO; import org.eclipse.smarthome.automation.dto.RuleDTOMapper; import org.eclipse.smarthome.core.events.AbstractEventFactory; import org.eclipse.smarthome.core.events.Event; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * this is a factory to create Rule Events * * @author Benedikt Niehues - initial contribution * @author Markus Rathgeb - Use the DTO for the Rule representation */ public class RuleEventFactory extends AbstractEventFactory { private final Logger logger = LoggerFactory.getLogger(RuleEventFactory.class); private static final String RULE_STATE_EVENT_TOPIC = "smarthome/rules/{ruleID}/state"; private static final String RULE_ADDED_EVENT_TOPIC = "smarthome/rules/{ruleID}/added"; private static final String RULE_REMOVED_EVENT_TOPIC = "smarthome/rules/{ruleID}/removed"; private static final String RULE_UPDATED_EVENT_TOPIC = "smarthome/rules/{ruleID}/updated"; private static final Set<String> SUPPORTED_TYPES = new HashSet<String>(); static { SUPPORTED_TYPES.add(RuleAddedEvent.TYPE); SUPPORTED_TYPES.add(RuleRemovedEvent.TYPE); SUPPORTED_TYPES.add(RuleStatusInfoEvent.TYPE); SUPPORTED_TYPES.add(RuleUpdatedEvent.TYPE); } public RuleEventFactory() { super(SUPPORTED_TYPES); } @Override protected Event createEventByType(String eventType, String topic, String payload, String source) throws Exception { logger.trace("creating ruleEvent of type: {}", eventType); if (eventType == null) { return null; } if (eventType.equals(RuleAddedEvent.TYPE)) { return createRuleAddedEvent(topic, payload, source); } else if (eventType.equals(RuleRemovedEvent.TYPE)) { return createRuleRemovedEvent(topic, payload, source); } else if (eventType.equals(RuleStatusInfoEvent.TYPE)) { return createRuleStatusInfoEvent(topic, payload, source); } else if (eventType.equals(RuleUpdatedEvent.TYPE)) { return createRuleUpdatedEvent(topic, payload, source); } return null; } private Event createRuleUpdatedEvent(String topic, String payload, String source) { RuleDTO[] ruleDTO = deserializePayload(payload, RuleDTO[].class); if (ruleDTO.length != 2) { throw new IllegalArgumentException("Creation of RuleUpdatedEvent failed: invalid payload: " + payload); } return new RuleUpdatedEvent(topic, payload, source, ruleDTO[0], ruleDTO[1]); } private Event createRuleStatusInfoEvent(String topic, String payload, String source) { RuleStatusInfo statusInfo = deserializePayload(payload, RuleStatusInfo.class); return new RuleStatusInfoEvent(topic, payload, source, statusInfo, getRuleId(topic)); } private Event createRuleRemovedEvent(String topic, String payload, String source) { RuleDTO ruleDTO = deserializePayload(payload, RuleDTO.class); return new RuleRemovedEvent(topic, payload, source, ruleDTO); } private Event createRuleAddedEvent(String topic, String payload, String source) { RuleDTO ruleDTO = deserializePayload(payload, RuleDTO.class); return new RuleAddedEvent(topic, payload, source, ruleDTO); } private String getRuleId(String topic) { String[] topicElements = getTopicElements(topic); if (topicElements.length != 4) { throw new IllegalArgumentException("Event creation failed, invalid topic: " + topic); } return topicElements[2]; } /** * Creates a rule updated event * * @param rule the new rule * @param oldRule the rule that has been updated * @param source the source of the event * @return {@link RuleUpdatedEvent} instance */ public static RuleUpdatedEvent createRuleUpdatedEvent(Rule rule, Rule oldRule, String source) { String topic = buildTopic(RULE_UPDATED_EVENT_TOPIC, rule); final RuleDTO ruleDto = RuleDTOMapper.map(rule); final RuleDTO oldRuleDto = RuleDTOMapper.map(oldRule); List<RuleDTO> rules = new LinkedList<RuleDTO>(); rules.add(ruleDto); rules.add(oldRuleDto); String payload = serializePayload(rules); return new RuleUpdatedEvent(topic, payload, source, ruleDto, oldRuleDto); } /** * Creates a rule status info event * * @param statusInfo the status info of the event * @param ruleUID the UID of the rule for which the event is created * @param source the source of the event * @return {@link RuleStatusInfoEvent} instance */ public static RuleStatusInfoEvent createRuleStatusInfoEvent(RuleStatusInfo statusInfo, String ruleUID, String source) { String topic = buildTopic(RULE_STATE_EVENT_TOPIC, ruleUID); String payload = serializePayload(statusInfo); return new RuleStatusInfoEvent(topic, payload, source, statusInfo, ruleUID); } /** * Creates a rule removed event * * @param rule the rule for which this event is created * @param source the source of the event * @return {@link RuleRemovedEvent} instance */ public static RuleRemovedEvent createRuleRemovedEvent(Rule rule, String source) { String topic = buildTopic(RULE_REMOVED_EVENT_TOPIC, rule); final RuleDTO ruleDto = RuleDTOMapper.map(rule); String payload = serializePayload(ruleDto); return new RuleRemovedEvent(topic, payload, source, ruleDto); } /** * Creates a rule added event * * @param rule the rule for which this event is created * @param source the source of the event * @return {@link RuleAddedEvent} instance */ public static RuleAddedEvent createRuleAddedEvent(Rule rule, String source) { String topic = buildTopic(RULE_ADDED_EVENT_TOPIC, rule); final RuleDTO ruleDto = RuleDTOMapper.map(rule); String payload = serializePayload(ruleDto); return new RuleAddedEvent(topic, payload, source, ruleDto); } private static String buildTopic(String topic, String ruleUID) { return topic.replace("{ruleID}", ruleUID); } private static String buildTopic(String topic, Rule rule) { return buildTopic(topic, rule.getUID()); } }
7,050
Java
.java
155
39.23871
119
0.716676
JONA-GA/smarthome
1
0
0
EPL-2.0
9/5/2024, 12:41:59 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
7,050
1,068,706
AllowedUrlRepositoryIT.java
Hexlet_hexlet-correction/src/test/java/io/hexlet/typoreporter/repository/AllowedUrlRepositoryIT.java
package io.hexlet.typoreporter.repository; import com.github.database.rider.core.api.configuration.DBUnit; import com.github.database.rider.core.api.dataset.DataSet; import com.github.database.rider.spring.api.DBRider; import io.hexlet.typoreporter.config.audit.AuditConfiguration; import io.hexlet.typoreporter.domain.workspace.AllowedUrl; import io.hexlet.typoreporter.test.DBUnitEnumPostgres; import jakarta.validation.ConstraintViolationException; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.context.annotation.Import; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.transaction.annotation.Transactional; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import static com.github.database.rider.core.api.configuration.Orthography.LOWERCASE; import static io.hexlet.typoreporter.test.Constraints.POSTGRES_IMAGE; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest @Testcontainers @Import(AuditConfiguration.class) @Transactional @DBRider @DBUnit(caseInsensitiveStrategy = LOWERCASE, dataTypeFactoryClass = DBUnitEnumPostgres.class, cacheConnection = false) @DataSet(value = {"workspaces.yml", "allowedUrls.yml"}) @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) class AllowedUrlRepositoryIT { @Container public static PostgreSQLContainer<?> postgreSQLContainer = new PostgreSQLContainer<>(POSTGRES_IMAGE) .withPassword("inmemory") .withUsername("inmemory"); @Autowired private AllowedUrlRepository allowedUrlRepository; @Autowired private WorkspaceRepository workspaceRepository; @DynamicPropertySource static void datasourceProperties(DynamicPropertyRegistry registry) { registry.add("spring.datasource.url", postgreSQLContainer::getJdbcUrl); registry.add("spring.datasource.password", postgreSQLContainer::getPassword); registry.add("spring.datasource.username", postgreSQLContainer::getUsername); } @ParameterizedTest @MethodSource("io.hexlet.typoreporter.test.factory.EntitiesFactory#getWorkspaceAndAllowedUrlsRelated") void getAllowedUrlByUrl(final Long wksId, final String url) { final var allowedUrl = allowedUrlRepository.findAllowedUrlByUrlAndWorkspaceId(url, wksId); assertThat(allowedUrl).isNotEmpty(); assertThat(allowedUrl.map(AllowedUrl::getUrl).orElseThrow()).isEqualTo(url); } @ParameterizedTest @MethodSource("io.hexlet.typoreporter.test.factory.EntitiesFactory#getWorkspaceAndAllowedUrlsNotRelated") void getAllowedUrlByUrlNotExists(final Long wksId, final String url) { assertThat(allowedUrlRepository.findAllowedUrlByUrlAndWorkspaceId(url, wksId)).isEmpty(); } @ParameterizedTest @MethodSource("io.hexlet.typoreporter.test.factory.EntitiesFactory#getAllowedUrls") void notSaveAllowedUrlEntityWithInvalidWorkspaceId(final AllowedUrl allowedUrl) { final var newUrl = allowedUrl.setId(null); newUrl.getWorkspace().setId(999_999_999L); assertThrows(DataIntegrityViolationException.class, () -> allowedUrlRepository.saveAndFlush(newUrl)); } @ParameterizedTest @MethodSource("io.hexlet.typoreporter.test.factory.EntitiesFactory#getAllowedUrls") void notSaveAllowedUrlEntityWithNullWorkspace(final AllowedUrl allowedUrl) { final var newUrl = allowedUrl.setId(null); newUrl.setWorkspace(null); assertThrows(ConstraintViolationException.class, () -> allowedUrlRepository.saveAndFlush(newUrl)); } @ParameterizedTest @MethodSource("io.hexlet.typoreporter.test.factory.EntitiesFactory#getWorkspaceIdsExist") void findPageAllowedUrlByWorkspaceId(final Long wksId) { final var wks = workspaceRepository.getWorkspaceById(wksId).orElseThrow(); final var pageReq = PageRequest.of(0, 10, Sort.by("url")); final var urlPage = allowedUrlRepository.findPageAllowedUrlByWorkspaceId(pageReq, wksId); assertThat(urlPage.getTotalElements()).isEqualTo(wks.getAllowedUrls().size()); } @ParameterizedTest @NullSource @ValueSource(longs = {9999L, 8888L, 7777L}) void findPageAllowedUrlByWorkspaceIdNotExist(final Long wksId) { final var pageReq = PageRequest.of(0, 10, Sort.by("url")); final var urlPage = allowedUrlRepository.findPageAllowedUrlByWorkspaceId(pageReq, wksId); assertThat(urlPage.getTotalElements()).isZero(); } }
5,251
Java
.java
95
50.873684
118
0.811079
Hexlet/hexlet-correction
45
79
29
AGPL-3.0
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
5,251
3,249,936
StronglyConnectedComponentsProc.java
meta-exp_neo4j-graph-algorithms/algo/src/main/java/org/neo4j/graphalgo/StronglyConnectedComponentsProc.java
/** * Copyright (c) 2017 "Neo4j, Inc." <http://neo4j.com> * * This file is part of Neo4j Graph Algorithms <http://github.com/neo4j-contrib/neo4j-graph-algorithms>. * * Neo4j Graph Algorithms is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphalgo; import com.carrotsearch.hppc.IntSet; import com.carrotsearch.hppc.ObjectArrayList; import com.carrotsearch.hppc.cursors.IntCursor; import org.neo4j.graphalgo.api.Graph; import org.neo4j.graphalgo.core.GraphLoader; import org.neo4j.graphalgo.core.ProcedureConfiguration; import org.neo4j.graphalgo.core.neo4jview.DirectIdMapping; import org.neo4j.graphalgo.core.utils.Pools; import org.neo4j.graphalgo.core.utils.ProgressLogger; import org.neo4j.graphalgo.core.utils.ProgressTimer; import org.neo4j.graphalgo.core.utils.TerminationFlag; import org.neo4j.graphalgo.core.write.Exporter; import org.neo4j.graphalgo.core.write.OptionalIntArrayTranslator; import org.neo4j.graphalgo.impl.*; import org.neo4j.graphalgo.impl.multistepscc.MultistepSCC; import org.neo4j.graphalgo.results.SCCResult; import org.neo4j.graphalgo.results.SCCStreamResult; import org.neo4j.graphdb.Direction; import org.neo4j.kernel.api.KernelTransaction; import org.neo4j.kernel.internal.GraphDatabaseAPI; import org.neo4j.logging.Log; import org.neo4j.procedure.*; import org.neo4j.values.storable.IntValue; import org.neo4j.values.storable.Values; import java.util.Map; import java.util.stream.Stream; /** * @author mknblch */ public class StronglyConnectedComponentsProc { public static final String CONFIG_WRITE_PROPERTY = "partitionProperty"; public static final String CONFIG_CLUSTER = "partition"; @Context public GraphDatabaseAPI api; @Context public Log log; @Context public KernelTransaction transaction; // default algo.scc -> iterative tarjan @Procedure(value = "algo.scc", mode = Mode.WRITE) @Description("CALL algo.scc(label:String, relationship:String, config:Map<String, Object>) YIELD " + "loadMillis, computeMillis, writeMillis, setCount, maxSetSize, minSetSize") public Stream<SCCResult> sccDefaultMethod( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { return sccIterativeTarjan(label, relationship, config); } // default algo.scc -> iter tarjan @Procedure(value = "algo.scc.stream") @Description("CALL algo.scc.stream(label:String, relationship:String, config:Map<String, Object>) YIELD " + "loadMillis, computeMillis, writeMillis, setCount, maxSetSize, minSetSize") public Stream<SCCStreamResult> sccDefaultMethodStream( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { return sccIterativeTarjanStream(label, relationship, config); } // algo.scc.tarjan @Procedure(value = "algo.scc.recursive.tarjan", mode = Mode.WRITE) @Description("CALL algo.scc.tarjan(label:String, relationship:String, config:Map<String, Object>) YIELD " + "loadMillis, computeMillis, writeMillis, setCount, maxSetSize, minSetSize") public Stream<SCCResult> sccTarjan( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { ProcedureConfiguration configuration = ProcedureConfiguration.create(config); SCCResult.Builder builder = SCCResult.builder(); ProgressTimer loadTimer = builder.timeLoad(); Graph graph = new GraphLoader(api, Pools.DEFAULT) .init(log, label, relationship, configuration) .withOptionalLabel(label) .withOptionalRelationshipType(relationship) .withoutRelationshipWeights() .withDirection(Direction.OUTGOING) .load(configuration.getGraphImpl()); loadTimer.stop(); final TerminationFlag terminationFlag = TerminationFlag.wrap(transaction); SCCTarjan tarjan = new SCCTarjan(graph) .withProgressLogger(ProgressLogger.wrap(log, "SCC(Tarjan)")) .withTerminationFlag(terminationFlag); builder.timeEval(() -> { tarjan.compute(); builder.withMaxSetSize(tarjan.getMaxSetSize()) .withMinSetSize(tarjan.getMinSetSize()) .withSetCount(tarjan.getConnectedComponents().size()); }); if (configuration.isWriteFlag()) { builder.timeWrite(() -> { final ObjectArrayList<IntSet> connectedComponents = tarjan.getConnectedComponents(); tarjan.release(); Exporter.of(new DirectIdMapping(connectedComponents.size()), api) .withLog(log) .parallel(Pools.DEFAULT, configuration.getConcurrency(), terminationFlag) .build() .write( configuration.get(CONFIG_WRITE_PROPERTY, CONFIG_CLUSTER), propertyId -> (ops, id) -> { final int setId = (int) (id); IntValue property = Values.intValue(setId + 1); for (final IntCursor iCursor : connectedComponents.get(setId)) { ops.nodeSetProperty( graph.toOriginalNodeId(iCursor.value), propertyId, property); } } ); }); } return Stream.of(builder.build()); } // algo.scc.tunedTarjan @Procedure(value = "algo.scc.recursive.tunedTarjan", mode = Mode.WRITE) @Description("CALL algo.scc.recursive.tunedTarjan(label:String, relationship:String, config:Map<String, Object>) YIELD " + "loadMillis, computeMillis, writeMillis, setCount, maxSetSize, minSetSize") public Stream<SCCResult> sccTunedTarjan( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { ProcedureConfiguration configuration = ProcedureConfiguration.create(config); SCCResult.Builder builder = SCCResult.builder(); ProgressTimer loadTimer = builder.timeLoad(); Graph graph = new GraphLoader(api, Pools.DEFAULT) .init(log, label, relationship, configuration) .withoutRelationshipWeights() .withDirection(Direction.OUTGOING) .load(configuration.getGraphImpl()); loadTimer.stop(); final TerminationFlag terminationFlag = TerminationFlag.wrap(transaction); SCCTunedTarjan tarjan = new SCCTunedTarjan(graph) .withProgressLogger(ProgressLogger.wrap(log, "SCC(TunedTarjan)")) .withTerminationFlag(terminationFlag); builder.timeEval(tarjan::compute); builder.withMaxSetSize(tarjan.getMaxSetSize()) .withMinSetSize(tarjan.getMinSetSize()) .withSetCount(tarjan.getSetCount()); if (configuration.isWriteFlag()) { builder.timeWrite(() -> Exporter .of(api, graph) .withLog(log) .parallel(Pools.DEFAULT, configuration.getConcurrency(), terminationFlag) .build() .write( configuration.get(CONFIG_WRITE_PROPERTY, CONFIG_CLUSTER), tarjan.getConnectedComponents(), OptionalIntArrayTranslator.INSTANCE )); } return Stream.of(builder.build()); } // algo.scc.tunedTarjan.stream @Procedure(value = "algo.scc.recursive.tunedTarjan.stream", mode = Mode.WRITE) @Description("CALL algo.scc.recursive.tunedTarjan.stream(label:String, relationship:String, config:Map<String, Object>) YIELD " + "nodeId, partition") public Stream<SCCStreamResult> sccTunedTarjanStream( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { ProcedureConfiguration configuration = ProcedureConfiguration.create(config); Graph graph = new GraphLoader(api, Pools.DEFAULT) .init(log, label, relationship, configuration) .withoutRelationshipWeights() .withDirection(Direction.OUTGOING) .load(configuration.getGraphImpl()); return new SCCTunedTarjan(graph) .withProgressLogger(ProgressLogger.wrap(log, "SCC(TunedTarjan)")) .withTerminationFlag(TerminationFlag.wrap(transaction)) .compute() .resultStream(); } // algo.scc.iterative @Procedure(value = "algo.scc.iterative", mode = Mode.WRITE) @Description("CALL algo.scc.iterative(label:String, relationship:String, config:Map<String, Object>) YIELD " + "loadMillis, computeMillis, writeMillis, setCount, maxSetSize, minSetSize") public Stream<SCCResult> sccIterativeTarjan( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { ProcedureConfiguration configuration = ProcedureConfiguration.create(config); SCCResult.Builder builder = SCCResult.builder(); ProgressTimer loadTimer = builder.timeLoad(); Graph graph = new GraphLoader(api, Pools.DEFAULT) .init(log, label, relationship, configuration) .withoutRelationshipWeights() .withDirection(Direction.OUTGOING) .load(configuration.getGraphImpl()); loadTimer.stop(); final TerminationFlag terminationFlag = TerminationFlag.wrap(transaction); SCCIterativeTarjan tarjan = new SCCIterativeTarjan(graph) .withProgressLogger(ProgressLogger.wrap(log, "SCC(IterativeTarjan)")) .withTerminationFlag(terminationFlag); builder.timeEval(tarjan::compute); builder.withSetCount(tarjan.getSetCount()) .withMinSetSize(tarjan.getMinSetSize()) .withMaxSetSize(tarjan.getMaxSetSize()); if (configuration.isWriteFlag()) { final int[] connectedComponents = tarjan.getConnectedComponents(); graph.release(); tarjan.release(); builder.timeWrite(() -> Exporter .of(api, graph) .withLog(log) .parallel(Pools.DEFAULT, configuration.getConcurrency(), terminationFlag) .build() .write( configuration.get(CONFIG_WRITE_PROPERTY, CONFIG_CLUSTER), connectedComponents, OptionalIntArrayTranslator.INSTANCE )); } return Stream.of(builder.build()); } // algo.scc.iterative.stream @Procedure(value = "algo.scc.iterative.stream", mode = Mode.WRITE) @Description("CALL algo.scc.iterative.stream(label:String, relationship:String, config:Map<String, Object>) YIELD " + "nodeId, partition") public Stream<SCCStreamResult> sccIterativeTarjanStream( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { ProcedureConfiguration configuration = ProcedureConfiguration.create(config); Graph graph = new GraphLoader(api, Pools.DEFAULT) .init(log, label, relationship, configuration) .withoutRelationshipWeights() .withDirection(Direction.OUTGOING) .load(configuration.getGraphImpl()); final SCCIterativeTarjan compute = new SCCIterativeTarjan(graph) .withProgressLogger(ProgressLogger.wrap(log, "SCC(IterativeTarjan)")) .withTerminationFlag(TerminationFlag.wrap(transaction)) .compute(); graph.release(); return compute.resultStream(); } // algo.scc.multistep @Procedure(value = "algo.scc.multistep", mode = Mode.WRITE) @Description("CALL algo.scc.multistep(label:String, relationship:String, {write:true, concurrency:4, cutoff:100000}) YIELD " + "loadMillis, computeMillis, writeMillis, setCount, maxSetSize, minSetSize") public Stream<SCCResult> multistep( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { ProcedureConfiguration configuration = ProcedureConfiguration.create(config); SCCResult.Builder builder = SCCResult.builder(); ProgressTimer loadTimer = builder.timeLoad(); Graph graph = new GraphLoader(api, Pools.DEFAULT) .init(log, label, relationship, configuration) .withoutRelationshipWeights() .load(configuration.getGraphImpl()); loadTimer.stop(); final TerminationFlag terminationFlag = TerminationFlag.wrap(transaction); final MultistepSCC multistep = new MultistepSCC(graph, org.neo4j.graphalgo.core.utils.Pools.DEFAULT, configuration.getConcurrency(), configuration.getNumber("cutoff", 100_000).intValue()) .withProgressLogger(ProgressLogger.wrap(log, "SCC(MultiStep)")) .withTerminationFlag(terminationFlag); builder.timeEval(multistep::compute); builder.withMaxSetSize(multistep.getMaxSetSize()) .withMinSetSize(multistep.getMinSetSize()) .withSetCount(multistep.getSetCount()); if (configuration.isWriteFlag()) { final int[] connectedComponents = multistep.getConnectedComponents(); graph.release(); multistep.release(); builder.timeWrite(() -> Exporter .of(api, graph) .withLog(log) .parallel(Pools.DEFAULT, configuration.getConcurrency(), terminationFlag) .build() .write( configuration.get(CONFIG_WRITE_PROPERTY, CONFIG_CLUSTER), connectedComponents, OptionalIntArrayTranslator.INSTANCE )); } return Stream.of(builder.build()); } // algo.scc.multistep.stream @Procedure(value = "algo.scc.multistep.stream") @Description("CALL algo.scc.multistep.stream(label:String, relationship:String, {write:true, concurrency:4, cutoff:100000}) YIELD " + "nodeId, partition") public Stream<SCCStreamResult> multistepStream( @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { ProcedureConfiguration configuration = ProcedureConfiguration.create(config); Graph graph = new GraphLoader(api, Pools.DEFAULT) .init(log, label, relationship, configuration) .withoutRelationshipWeights() .load(configuration.getGraphImpl()); final MultistepSCC multistep = new MultistepSCC(graph, org.neo4j.graphalgo.core.utils.Pools.DEFAULT, configuration.getConcurrency(), configuration.getNumber("cutoff", 100_000).intValue()) .withProgressLogger(ProgressLogger.wrap(log, "SCC(MultiStep)")) .withTerminationFlag(TerminationFlag.wrap(transaction)); multistep.compute(); graph.release(); return multistep.resultStream(); } // algo.scc.forwardBackward.stream @Procedure(value = "algo.scc.forwardBackward.stream") @Description("CALL algo.scc.forwardBackward.stream(long startNodeId, label:String, relationship:String, {write:true, concurrency:4}) YIELD " + "nodeId, partition") public Stream<ForwardBackwardScc.Result> fwbwStream( @Name(value = "startNodeId", defaultValue = "0") long startNodeId, @Name(value = "label", defaultValue = "") String label, @Name(value = "relationship", defaultValue = "") String relationship, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) { ProcedureConfiguration configuration = ProcedureConfiguration.create(config); Graph graph = new GraphLoader(api, Pools.DEFAULT) .init(log, label, relationship, configuration) .withoutRelationshipWeights() .load(configuration.getGraphImpl()); final ForwardBackwardScc algo = new ForwardBackwardScc(graph, Pools.DEFAULT, configuration.getConcurrency()) .withProgressLogger(ProgressLogger.wrap(log, "SCC(ForwardBackward)")) .withTerminationFlag(TerminationFlag.wrap(transaction)) .compute(graph.toMappedNodeId(startNodeId)); graph.release(); return algo.resultStream(); } }
18,844
Java
.java
341
43.255132
146
0.642404
meta-exp/neo4j-graph-algorithms
4
0
0
GPL-3.0
9/4/2024, 11:08:11 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,844
3,742,322
AuthTypeStatusDtoV2.java
mosip_resident-services/resident/resident-service/src/main/java/io/mosip/resident/dto/AuthTypeStatusDtoV2.java
package io.mosip.resident.dto; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) public class AuthTypeStatusDtoV2 extends AuthTypeStatusDto { private String authSubType; }
220
Java
.java
8
26
60
0.870813
mosip/resident-services
3
82
28
MPL-2.0
9/4/2024, 11:40:41 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
220
542,851
ItemPrismarineStack.java
AllayMC_Allay/api/src/main/java/org/allaymc/api/item/interfaces/ItemPrismarineStack.java
package org.allaymc.api.item.interfaces; import org.allaymc.api.item.ItemStack; public interface ItemPrismarineStack extends ItemStack { }
141
Java
.java
4
33.75
56
0.859259
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
141
344,538
ActuatorFactory.java
tronprotocol_sun-network/dapp-chain/side-chain/framework/src/main/java/org/tron/core/actuator/ActuatorFactory.java
package org.tron.core.actuator; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.db.Manager; import org.tron.protos.Protocol; import org.tron.protos.Protocol.Transaction.Contract; @Slf4j(topic = "actuator") public class ActuatorFactory { public static final ActuatorFactory INSTANCE = new ActuatorFactory(); private ActuatorFactory() { } public static ActuatorFactory getInstance() { return INSTANCE; } /** * create actuator. */ public static List<Actuator> createActuator(TransactionCapsule transactionCapsule, Manager manager) { List<Actuator> actuatorList = Lists.newArrayList(); if (null == transactionCapsule || null == transactionCapsule.getInstance()) { logger.info("transactionCapsule or Transaction is null"); return actuatorList; } Preconditions.checkNotNull(manager, "manager is null"); Protocol.Transaction.raw rawData = transactionCapsule.getInstance().getRawData(); rawData.getContractList() .forEach(contract -> { try { actuatorList .add(getActuatorByContract(contract, manager, transactionCapsule)); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } }); return actuatorList; } private static Actuator getActuatorByContract(Contract contract, Manager manager, TransactionCapsule tx) throws IllegalAccessException, InstantiationException { Class<? extends Actuator> clazz = TransactionFactory.getActuator(contract.getType()); AbstractActuator abstractActuator = (AbstractActuator) clazz.newInstance(); abstractActuator.setChainBaseManager(manager.getChainBaseManager()).setContract(contract) .setForkUtils(manager.getForkController()).setTx(tx); return abstractActuator; } }
2,043
Java
.java
51
34.686275
93
0.742814
tronprotocol/sun-network
344
140
91
LGPL-3.0
9/4/2024, 7:06:38 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
2,043
544,037
ItemTurtleEggStack.java
AllayMC_Allay/api/src/main/java/org/allaymc/api/item/interfaces/egg/ItemTurtleEggStack.java
package org.allaymc.api.item.interfaces.egg; import org.allaymc.api.item.ItemStack; public interface ItemTurtleEggStack extends ItemStack { }
144
Java
.java
4
34.5
55
0.855072
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
144
3,372,462
Files.java
Dev7ex_FacilisCommon/facilis-common-core/src/main/java/com/dev7ex/common/io/file/Files.java
package com.dev7ex.common.io.file; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * Utility class for file operations. */ public final class Files { private Files() { } /** * Checks if the specified folder contains a file with the given name. * * @param folder The folder to search in. * @param fileName The name of the file to check for. * @return True if the folder contains the file, false otherwise. */ public static boolean containsFile(final File folder, final String fileName) { if (!folder.isDirectory()) { throw new IllegalArgumentException("Specified file is not a directory: " + folder.getAbsolutePath()); } final File[] files = Objects.requireNonNull(folder.listFiles()); for (final File file : files) { if (file.isFile() && file.getName().equalsIgnoreCase(fileName)) { return true; } } return false; } /** * Retrieves a list of files in the specified folder. * * @param folder The folder to retrieve files from. * @return A list of files in the folder. * @throws IllegalArgumentException if the specified file is not a directory. */ public static List<File> getFiles(final File folder) { if (!folder.isDirectory()) { throw new IllegalArgumentException("Specified file is not a directory: " + folder.getAbsolutePath()); } return Arrays.asList(Objects.requireNonNull(folder.listFiles())); } /** * Converts the names of all subdirectories of the specified file to a list of strings. * * @param file The file containing subdirectories. * @return A list of subdirectory names. */ public static List<String> toStringList(final File file) { if (!file.isDirectory()) { throw new IllegalArgumentException("Specified file is not a directory: " + file.getAbsolutePath()); } return Arrays.stream(Objects.requireNonNull(file.listFiles(File::isDirectory))) .map(File::getName) .collect(Collectors.toList()); } }
2,246
Java
.java
59
31.220339
113
0.655949
Dev7ex/FacilisCommon
4
1
0
GPL-3.0
9/4/2024, 11:16:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,246
220,369
SecureKeyTest.java
jpos_jPOS/jpos/src/test/java/org/jpos/security/SecureKeyTest.java
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2024 jPOS Software SRL * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.security; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.api.Test; public class SecureKeyTest { @Test public void testGetKeyBytes() throws Throwable { SecureKey secureDESKey = new SecureDESKey(); byte[] keyBytes = new byte[0]; secureDESKey.setKeyBytes(keyBytes); byte[] result = secureDESKey.getKeyBytes(); assertSame(keyBytes, result, "result"); } @Test public void testGetKeyBytes1() throws Throwable { byte[] keyBytes = new byte[3]; byte[] result = new SecureDESKey((short) 100, "testSecureKeyKeyType", keyBytes, keyBytes).getKeyBytes(); assertSame(keyBytes, result, "result"); assertEquals((byte) 0, keyBytes[0], "keyBytes[0]"); } @Test public void testGetKeyLength() throws Throwable { SecureKey secureDESKey = new SecureDESKey(); secureDESKey.setKeyLength((short) 100); short result = secureDESKey.getKeyLength(); assertEquals((short) 100, result, "result"); } @Test public void testGetKeyType() throws Throwable { SecureKey secureDESKey = new SecureDESKey(); secureDESKey.setKeyType("testSecureKeyKeyType"); String result = secureDESKey.getKeyType(); assertEquals("testSecureKeyKeyType", result, "result"); } @Test public void testSetKeyBytes() throws Throwable { byte[] keyBytes = new byte[3]; SecureKey secureDESKey = new SecureDESKey((short) 100, "testSecureKeyKeyType", keyBytes, keyBytes); secureDESKey.setKeyBytes(keyBytes); assertSame(keyBytes, ((SecureDESKey) secureDESKey).keyBytes, "(SecureDESKey) secureDESKey.keyBytes"); } @Test public void testSetKeyLength() throws Throwable { byte[] keyBytes = new byte[3]; new SecureDESKey((short) 100, "testSecureKeyKeyType", keyBytes, keyBytes).getKeyBytes(); SecureKey secureDESKey = new SecureDESKey((short) 1000, "testSecureKeyKeyType1", "3check-value>".getBytes(), keyBytes); secureDESKey.setKeyLength((short) 100); assertEquals((short) 100, ((SecureDESKey) secureDESKey).keyLength, "(SecureDESKey) secureDESKey.keyLength"); } @Test public void testSetKeyType() throws Throwable { byte[] keyBytes = new byte[3]; new SecureDESKey((short) 100, "testSecureKeyKeyType", keyBytes, keyBytes).getKeyBytes(); SecureKey secureDESKey = new SecureDESKey((short) 1000, "testSecureKeyKeyType1", "3check-value>".getBytes(), keyBytes); secureDESKey.setKeyType("testSecureKeyKeyType"); assertEquals("testSecureKeyKeyType", ((SecureDESKey) secureDESKey).keyType, "(SecureDESKey) secureDESKey.keyType"); } }
3,566
Java
.java
75
41.76
127
0.713506
jpos/jPOS
604
459
91
AGPL-3.0
9/4/2024, 7:05:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,566
1,622,954
ServiceManager.java
identityxx_penrose-server/server/src/java/org/safehaus/penrose/service/ServiceManager.java
/** * Copyright 2009 Red Hat, Inc. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.safehaus.penrose.service; import org.safehaus.penrose.server.PenroseServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; /** * @author Endi S. Dewata */ public class ServiceManager { public Logger log = LoggerFactory.getLogger(getClass()); PenroseServer penroseServer; private Map<String,Service> services = new LinkedHashMap<String,Service>(); private ServiceConfigManager serviceConfigManager; public ServiceManager(PenroseServer penroseServer, ServiceConfigManager serviceConfigManager) { this.penroseServer = penroseServer; this.serviceConfigManager = serviceConfigManager; } public void addServiceConfig(ServiceConfig serviceConfig) throws Exception { serviceConfigManager.addServiceConfig(serviceConfig); } public File getServicesDir() { return serviceConfigManager.getServicesDir(); } public void addService(Service service) { services.put(service.getName(), service); } public Service getService(String name) { return services.get(name); } public Collection<String> getServiceNames() { return services.keySet(); } public Collection<Service> getServices() { return services.values(); } public Service removeService(String name) { return services.remove(name); } public void clear() { services.clear(); } public void loadServiceConfig(String name) throws Exception { log.debug("Loading "+name+" service."); ServiceConfig serviceConfig = serviceConfigManager.load(name); serviceConfigManager.addServiceConfig(serviceConfig); } public Service startService(String serviceName) throws Exception { ServiceConfig serviceConfig = serviceConfigManager.getServiceConfig(serviceName); if (!serviceConfig.isEnabled()) { log.debug(serviceConfig.getName()+" service is disabled."); return null; } log.debug("Starting "+serviceName+" service."); ServiceContext serviceContext = createServiceContext(serviceConfig); Service service = createService(serviceConfig, serviceContext); service.init(serviceConfig, serviceContext); addService(service); return service; } public ServiceContext createServiceContext(ServiceConfig serviceConfig) throws Exception { File serviceDir = new File(serviceConfigManager.getServicesDir(), serviceConfig.getName()); ClassLoader classLoader = new ServiceClassLoader(serviceDir, getClass().getClassLoader()); //Collection<URL> classPaths = serviceConfig.getClassPaths(); //URLClassLoader classLoader = new URLClassLoader(classPaths.toArray(new URL[classPaths.size()]), getClass().getClassLoader()); ServiceContext serviceContext = new ServiceContext(); serviceContext.setPath(serviceDir); serviceContext.setPenroseServer(penroseServer); serviceContext.setClassLoader(classLoader); return serviceContext; } public Service createService(ServiceConfig serviceConfig, ServiceContext serviceContext) throws Exception { ClassLoader classLoader = serviceContext.getClassLoader(); Class clazz = classLoader.loadClass(serviceConfig.getServiceClass()); return (Service)clazz.newInstance(); } public void stopService(String name) throws Exception { log.debug("Stopping "+name+" service."); Service service = getService(name); if (service == null) return; service.destroy(); services.remove(name); } public void unloadService(String name) throws Exception { serviceConfigManager.removeServiceConfig(name); } public String getServiceStatus(String name) { Service service = services.get(name); if (service == null) { return "STOPPED"; } else { return "STARTED"; } } public ServiceConfigManager getServiceConfigManager() { return serviceConfigManager; } public void setServiceConfigManager(ServiceConfigManager serviceConfigManager) { this.serviceConfigManager = serviceConfigManager; } public ServiceConfig getServiceConfig(String serviceName) { return serviceConfigManager.getServiceConfig(serviceName); } }
5,413
Java
.java
123
36.235772
136
0.711698
identityxx/penrose-server
15
6
0
GPL-2.0
9/4/2024, 8:06:43 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
5,413
5,029,296
CardModifyAction.java
zning1994_paper/数据库与飞机大战/名片管理系统/Card/src/com/user/action/CardModifyAction.java
package com.user.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.manager.dao.impl.CompanyDaoImpl; import com.manager.dao.impl.DepartmentDaoImpl; import com.manager.dao.impl.PositionDaoImpl; import com.manager.entity.Card; import com.manager.entity.Card_Users; import com.manager.entity.Users; import com.manager.entity.Users_Card; import com.user.daoimpl.CardDaoImpl; import com.user.daoimpl.Card_UsersDaoImpl; import com.user.daoimpl.Users_CardDaoImpl; public class CardModifyAction extends com.opensymphony.xwork2.ActionSupport{ private File[] myFile; private String[] myFileFileName; private String usernameS; private String company; private String department; private String position; private String homeaddress; private int postcode; private String tel; private String mailbox; private String remark; private int carspower; private int cardid; private int state; public int getState() { return state; } public void setState(int state) { this.state = state; } public int getCardid() { return cardid; } public void setCardid(int cardid) { this.cardid = cardid; } public File[] getMyFile() { return myFile; } public void setMyFile(File[] myFile) { this.myFile = myFile; } public String[] getMyFileFileName() { return myFileFileName; } public void setMyFileFileName(String[] myFileFileName) { this.myFileFileName = myFileFileName; } public String getUsernameS() { return usernameS; } public void setUsernameS(String usernameS) { this.usernameS = usernameS; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getHomeaddress() { return homeaddress; } public void setHomeaddress(String homeaddress) { this.homeaddress = homeaddress; } public int getPostcode() { return postcode; } public void setPostcode(int postcode) { this.postcode = postcode; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getMailbox() { return mailbox; } public void setMailbox(String mailbox) { this.mailbox = mailbox; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getCarspower() { return carspower; } public void setCarspower(int carspower) { this.carspower = carspower; } public String execute() throws Exception{ Card card = new Card(); card.setCardId(getCardid()); card.setState(getCarspower()); card.setNotes(getRemark()); card.setFront(myFileFileName[0]); System.out.println("cardmodifyaction"+myFileFileName[0]); card.setBehind(myFileFileName[1]); card.setState(state); CardDaoImpl cdi = new CardDaoImpl(); cdi.update(card); Card_Users cu = new Card_Users(); cu.setCardId(getCardid()); //System.out.println("cardmodifyaction getCardid()"+getCardid()); cu.setAddress(getHomeaddress()); System.out.println(getHomeaddress()+"getHomeaddress()"); cu.setCardUsersName(getUsernameS()); CompanyDaoImpl cdi1 = new CompanyDaoImpl(); cu.setCompanyId(cdi1.findByName(getCompany())); cu.setTel(getTel()); cu.setPostCode(this.getPostcode()); cu.setEmail(getMailbox()); DepartmentDaoImpl dp = new DepartmentDaoImpl(); cu.setDepartmentId(dp.findByName(getCompany(), getDepartment())); PositionDaoImpl psd = new PositionDaoImpl(); cu.setPositionId(psd.findByName(getCompany(), getDepartment(), getPosition())); CardDaoImpl cdl = new CardDaoImpl(); //System.out.println("uploadaction"+cdl.findId()); cu.setCardId(cdl.findId()); //System.out.println("uploadaction2"+cu.getCardId()); Card_UsersDaoImpl cui = new Card_UsersDaoImpl(); cui.update(cu); //System.out.println("cui.insert(cu)"+cui.insert(cu));//cui.insert(cu); // Users_Card uc = new Users_Card(); // HttpSession session=ServletActionContext.getRequest().getSession(); // //uc.setCardId(cardId) // //ActionContext c = ActionContext.getContext(); // //HttpSession session=(HttpSession) c.getSession(); // Users users=(Users) session.getAttribute("users"); // //Users users = (Users) c.getSession().get("users"); // CardDaoImpl uccdl = new CardDaoImpl(); // uc.setCardId(uccdl.findId()); // //uc.setCardId(cardId) //先将card插入数据库,再从数据库查cardId // System.out.println("uploadaction2 users.getUsersId()"+users.getUsersId()); // uc.setUsersId(users.getUsersId()); // com.user.dao.impl.Users_CardDaoImpl ucdi = new com.user.dao.impl.Users_CardDaoImpl(); // ucdi.update(uc); // OutputStream output=null; InputStream input=null; System.out.println("cardmodifyaction name"+usernameS); try{ for(int i=0;i<myFileFileName.length;i++){ output=new FileOutputStream("e:/temp/"+myFileFileName[i]); //output=new FileOutputStream("temp/"+myFileFileName[i]); byte[] bs=new byte[1024]; input = new FileInputStream(myFile[i]); int length=0; while((length=input.read(bs))>0){ output.write(bs,0,length); } } }catch(Exception e){} finally{ input.close(); output.close(); } return SUCCESS; } }
5,787
Java
.java
187
27.176471
90
0.728212
zning1994/paper
1
0
0
GPL-2.0
9/5/2024, 12:39:19 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
5,773
4,428,035
BedManager.java
EterniaServer_EterniaServer/src/main/java/br/com/eterniaserver/eterniaserver/modules/bed/BedManager.java
package br.com.eterniaserver.eterniaserver.modules.bed; import br.com.eterniaserver.eternialib.EterniaLib; import br.com.eterniaserver.eterniaserver.EterniaServer; import br.com.eterniaserver.eterniaserver.modules.Module; import br.com.eterniaserver.eterniaserver.enums.Integers; import br.com.eterniaserver.eterniaserver.modules.bed.Services.SleepingService; import br.com.eterniaserver.eterniaserver.modules.bed.Configurations.BedMessages; import br.com.eterniaserver.eterniaserver.modules.bed.Configurations.BedConfiguration; public class BedManager implements Module { private final SleepingService sleepingService = new SleepingService(); private final EterniaServer plugin; public BedManager(EterniaServer plugin) { this.plugin = plugin; } @Override public void loadConfigurations() { BedMessages messages = new BedMessages(plugin); BedConfiguration configuration = new BedConfiguration(plugin); EterniaLib.registerConfiguration("eterniaserver", "bed_messages", messages); EterniaLib.registerConfiguration("eterniaserver", "bed", configuration); messages.executeConfig(); configuration.executeConfig(); configuration.executeCritical(); messages.saveConfiguration(true); configuration.saveConfiguration(true); } @Override public void loadCommandsCompletions() { } @Override public void loadConditions() { } @Override public void loadListeners() { plugin.getServer().getPluginManager().registerEvents(new Handlers(plugin, sleepingService), plugin); } @Override public void loadSchedules() { new Schedules .CheckWorld(plugin, sleepingService) .runTaskTimer(plugin, 0, 20L * plugin.getInteger(Integers.BED_CHECK_TIME)); } @Override public void loadCommands() { } }
1,886
Java
.java
43
37.767442
108
0.754376
EterniaServer/EterniaServer
2
0
0
GPL-3.0
9/5/2024, 12:12:53 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,886
402,326
ActiveNotificationErrors.java
DP-3T_dp3t-sdk-android/dp3t-sdk/sdk/src/main/java/org/dpppt/android/sdk/internal/storage/models/ActiveNotificationErrors.java
package org.dpppt.android.sdk.internal.storage.models; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.dpppt.android.sdk.TracingStatus.ErrorState; /** * Map: ErrorState key -> suppressed until (unit timestamp, millis) */ public class ActiveNotificationErrors extends HashMap<String, Long> { public Set<ErrorState> getUnsuppressedErrors(long now) { Set<ErrorState> unsuppressedErrors = new HashSet<>(); for (String errorKey : getUnsuppressedErrorKeys(now)) { ErrorState error = ErrorState.tryValueOf(errorKey); if (error != null) { unsuppressedErrors.add(error); } } return unsuppressedErrors; } /** * @return timestamp of next unsuppression event, -1 if no future event. */ public long refreshActiveErrors(Collection<ErrorState> activeErrors, long now, long suppressNewErrorsUntil, Collection<ErrorState> unsuppressableErrors) { if (activeErrors.isEmpty()) { clear(); return -1; } Set<String> activeErrorKeys = new HashSet<>(); for (ErrorState activeError : activeErrors) { activeErrorKeys.add(activeError.name()); } // remove obsolete errors for (String errorKey : new HashSet<>(keySet())) { if (!activeErrorKeys.contains(errorKey)) { remove(errorKey); } } // add new errors with suppressNewErrorsUntil for (ErrorState error : activeErrors) { String errorKey = error.name(); if (!containsKey(errorKey)) { put(errorKey, unsuppressableErrors.contains(error) ? -1 : suppressNewErrorsUntil); } } Long nextUnsuppressionTime = getNextUnsuppressionTime(now); if (nextUnsuppressionTime != null) { return nextUnsuppressionTime; } else { return -1; } } private Set<String> getUnsuppressedErrorKeys(long now) { Set<String> unsuppressedErrorKeys = new HashSet<>(); for (Entry<String, Long> errorKeySuppressedUntil : entrySet()) { if (errorKeySuppressedUntil.getValue() <= now) { unsuppressedErrorKeys.add(errorKeySuppressedUntil.getKey()); } } return unsuppressedErrorKeys; } private Long getNextUnsuppressionTime(long now) { Long nextUnsuppressionTime = null; for (Entry<String, Long> errorKeySuppressedUntil : entrySet()) { if (errorKeySuppressedUntil.getValue() > now && (nextUnsuppressionTime == null || errorKeySuppressedUntil.getValue() < nextUnsuppressionTime)) { nextUnsuppressionTime = errorKeySuppressedUntil.getValue(); } } return nextUnsuppressionTime; } }
2,484
Java
.java
73
30.835616
108
0.752814
DP-3T/dp3t-sdk-android
243
94
22
MPL-2.0
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,484
4,305,294
CommandWHome.java
StefanoTavonatti_SimpleWaypoints/src/main/java/tavonatti/stefano/spigot_plugin/waypoints/commands/CommandWHome.java
package tavonatti.stefano.spigot_plugin.waypoints.commands; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import tavonatti.stefano.spigot_plugin.waypoints.utils.Permissions; import tavonatti.stefano.spigot_plugin.waypoints.utils.TPUtils; public class CommandWHome implements CommandExecutor { public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if(commandSender instanceof Player){ Player player= (Player) commandSender; if(!player.hasPermission(Permissions.WAYPOINTS.permission)){ player.sendMessage(""+ ChatColor.RED+"You don't have the permission to do this!!!"); return true; } if(player.getBedSpawnLocation()!=null) TPUtils.teleportPlayer(player,player.getBedSpawnLocation()); else { player.sendMessage(""+ChatColor.RED+"Spawn point not found"); } } return true; } }
1,130
Java
.java
25
37.24
104
0.706096
StefanoTavonatti/SimpleWaypoints
2
2
0
GPL-3.0
9/5/2024, 12:08:36 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,130
369,318
MarkdownPageTest.java
winterstein_Eclipse-Markdown-Editor-Plugin/plugin/src/winterwell/markdown/pagemodel/MarkdownPageTest.java
package winterwell.markdown.pagemodel; import java.io.File; import java.util.List; import winterwell.markdown.pagemodel.MarkdownPage.Header; import winterwell.utils.io.FileUtils; public class MarkdownPageTest //extends TestCase { public static void main(String[] args) { MarkdownPageTest mpt = new MarkdownPageTest(); mpt.testGetHeadings(); } public void testGetHeadings() { // problem caused by a line beginning --, now fixed String txt = FileUtils.read(new File( "/home/daniel/winterwell/companies/DTC/projects/DTC-bayes/report1.txt")); MarkdownPage p = new MarkdownPage(txt); List<Header> h1s = p.getHeadings(null); Header h1 = h1s.get(0); List<Header> h2s = h1.getSubHeaders(); assert h2s.size() > 2; } }
746
Java
.java
22
31.227273
78
0.762238
winterstein/Eclipse-Markdown-Editor-Plugin
296
73
31
EPL-1.0
9/4/2024, 7:06:52 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
746
4,149,178
IntFixedListTest.java
aherbert_gdsc-core/gdsc-core/src/test/java/uk/ac/sussex/gdsc/core/utils/IntFixedListTest.java
/*- * #%L * Genome Damage and Stability Centre Core Package * * Contains core utilities for image analysis and is used by: * * GDSC ImageJ Plugins - Microscopy image analysis * * GDSC SMLM ImageJ Plugins - Single molecule localisation microscopy (SMLM) * %% * Copyright (C) 2011 - 2023 Alex Herbert * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package uk.ac.sussex.gdsc.core.utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings({"javadoc"}) class IntFixedListTest { @Test void testAddGetSet() { final int capacity = 5; final IntFixedList list = new IntFixedList(capacity); Assertions.assertEquals(capacity, list.capacity()); Assertions.assertEquals(0, list.size()); for (int i = 0; i < capacity; i++) { list.add(i + 1); Assertions.assertEquals(i + 1, list.size()); Assertions.assertEquals(i + 1, list.get(i)); list.set(i, i + 7); Assertions.assertEquals(i + 7, list.get(i)); } } @Test void testAddArray() { final IntFixedList list = new IntFixedList(10); final int[] data = {42, 7, 13}; list.add(data); Assertions.assertEquals(3, list.size()); for (int i = 0; i < list.size(); i++) { Assertions.assertEquals(data[i], list.get(i)); } list.addValues(data); Assertions.assertEquals(6, list.size()); for (int i = 0; i < list.size(); i++) { Assertions.assertEquals(data[i % 3], list.get(i)); } } @Test void testAddIntFixedList() { final IntFixedList list = new IntFixedList(10); final IntFixedList list2 = new IntFixedList(10); final int[] data = {42, 7, 13}; list2.add(data); list.add(list2); Assertions.assertEquals(3, list.size()); for (int i = 0; i < list.size(); i++) { Assertions.assertEquals(data[i], list.get(i)); } list.add(list2); Assertions.assertEquals(6, list.size()); for (int i = 0; i < list.size(); i++) { Assertions.assertEquals(data[i % 3], list.get(i)); } } @Test void testCopy() { final IntFixedList list = new IntFixedList(10); final int[] data = {42, 7, 13}; list.add(data); final int[] dest = new int[5]; list.copy(dest, 2); Assertions.assertArrayEquals(new int[] {0, 0, 42, 7, 13}, dest); } @Test void testClear() { final IntFixedList list = new IntFixedList(10); final int[] data = {42, 7, 13}; list.add(data); Assertions.assertEquals(3, list.size()); list.clear(); Assertions.assertEquals(0, list.size()); } @Test void testToArray() { final IntFixedList list = new IntFixedList(10); Assertions.assertArrayEquals(new int[0], list.toArray()); final int[] data = {42, 7, 13}; list.add(data); Assertions.assertArrayEquals(data, list.toArray()); } @Test void testRemove() { final IntFixedList list = new IntFixedList(10); final int[] data = {42, 7, 13}; list.add(data); list.remove(1); Assertions.assertArrayEquals(new int[] {42, 13}, list.toArray()); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> list.remove(-1)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> list.remove(list.size())); } @Test void testRemoveIf() { final IntFixedList list = new IntFixedList(10); final int[] data = {42, 7, 13}; list.add(data); list.removeIf(i -> i == 99); Assertions.assertArrayEquals(data, list.toArray()); list.removeIf(i -> i == 42); Assertions.assertArrayEquals(new int[] {7, 13}, list.toArray()); list.removeIf(i -> i != 42); Assertions.assertArrayEquals(new int[0], list.toArray()); // Test with a bad predicate list.add(data); try { list.removeIf(i -> { if (i == 42) { return true; } throw new RuntimeException(); }); } catch (final RuntimeException expected) { // ignore } // The list is not corrupted Assertions.assertEquals(2, list.size()); Assertions.assertArrayEquals(new int[] {7, 13}, list.toArray()); } }
4,692
Java
.java
142
28.739437
93
0.659467
aherbert/gdsc-core
2
1
0
GPL-3.0
9/5/2024, 12:04:22 AM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,692
1,209,006
ThemeDotDensityContainer.java
SuperMap-iDesktop_SuperMap-iDesktop-Cross/MapView/src/main/java/com/supermap/desktop/newtheme/themeDotDensity/ThemeDotDensityContainer.java
package com.supermap.desktop.newtheme.themeDotDensity; import com.supermap.data.Dataset; import com.supermap.data.DatasetVector; import com.supermap.data.GeoStyle; import com.supermap.data.SymbolType; import com.supermap.desktop.controls.utilities.SymbolDialogFactory; import com.supermap.desktop.dialog.SmOptionPane; import com.supermap.desktop.dialog.symbolDialogs.ISymbolApply; import com.supermap.desktop.dialog.symbolDialogs.SymbolDialog; import com.supermap.desktop.mapview.MapViewProperties; import com.supermap.desktop.newtheme.commonPanel.ThemeChangePanel; import com.supermap.desktop.newtheme.commonUtils.ThemeGuideFactory; import com.supermap.desktop.newtheme.commonUtils.ThemeUtil; import com.supermap.desktop.ui.UICommonToolkit; import com.supermap.desktop.ui.controls.DialogResult; import com.supermap.desktop.ui.controls.GridBagConstraintsHelper; import com.supermap.desktop.ui.controls.LayersTree; import com.supermap.desktop.utilities.MapUtilities; import com.supermap.desktop.utilities.StringUtilities; import com.supermap.mapping.*; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.*; import java.text.DecimalFormat; import java.util.ArrayList; /** * 点密度专题图 * * @author xie * */ public class ThemeDotDensityContainer extends ThemeChangePanel { private static final long serialVersionUID = 1L; private JTabbedPane tabbedPaneInfo; private JPanel panelProperty; private JLabel labelExpression; private JLabel labelValue; private JLabel labelDotDensityValue; private JLabel labelDotDensityStyle; private JComboBox<String> comboBoxExpression;// 表达式 private JTextField textFieldValue;// 单点代表的值 private JSpinner spinnerDotDensityValue;// 最大值包含的点个数 private JButton buttonDotDensityStyle;// 点风格 private ThemeDotDensity themeDotDensity; private Layer themeDotDensityLayer; private DatasetVector datasetVector; private boolean isRefreshAtOnce; private Map map; private String layerName; private double maxValue; private ArrayList<String> comboBoxArray; private LayersTree layersTree = UICommonToolkit.getLayersManager().getLayersTree(); private DecimalFormat format = new DecimalFormat("#.####"); private ItemListener expressionListener = new ExpressionListener(); private ActionListener buttonActionListener = new ButtonActionListener(); private ChangeListener changeListener = new SpinnerListener(); private FocusAdapter textFieldListener = new TextFieldListener(); private MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { // 动态刷新表达式 initComboBoxExpression(); } }; public ThemeDotDensityContainer(Layer layer) { this.themeDotDensityLayer = layer; this.layerName = layer.getName(); this.themeDotDensity = new ThemeDotDensity((ThemeDotDensity) layer.getTheme()); this.datasetVector = (DatasetVector) layer.getDataset(); this.map = ThemeGuideFactory.getMapControl().getMap(); initComponents(); initResources(); registActionListener(); } private void initComponents() { GridBagLayout gridBagLayout = new GridBagLayout(); this.setLayout(gridBagLayout); this.tabbedPaneInfo = new JTabbedPane(); this.panelProperty = new JPanel(); this.tabbedPaneInfo.add(MapViewProperties.getString("String_Theme_Property"), this.panelProperty); this.add(tabbedPaneInfo, new GridBagConstraintsHelper(0, 0, 1, 1).setAnchor(GridBagConstraints.NORTH).setFill(GridBagConstraints.BOTH).setWeight(1, 1)); initPanelProperty(); } private void initResources() { this.labelExpression.setText(MapViewProperties.getString("String_Label_Expression")); this.labelValue.setText(MapViewProperties.getString("String_ThemeDotDensityProperty_LabelDotValue")); this.labelDotDensityValue.setText(MapViewProperties.getString("String_ThemeDotDensityProperty_LabelMaxCount")); this.labelDotDensityStyle.setText(MapViewProperties.getString("String_ThemeDotDensityProperty_LabelDotStyle")); } private void initPanelProperty() { this.labelExpression = new JLabel(); this.comboBoxExpression = new JComboBox<String>(); this.labelValue = new JLabel(); this.textFieldValue = new JTextField(); this.labelDotDensityValue = new JLabel(); this.spinnerDotDensityValue = new JSpinner(); this.labelDotDensityStyle = new JLabel(); this.buttonDotDensityStyle = new JButton("..."); this.spinnerDotDensityValue.setModel(new SpinnerNumberModel(1, 1, null, 1)); initComboBoxExpression(); initTextFieldValue(); Dimension dimension = new Dimension(120, 23); this.comboBoxExpression.setPreferredSize(dimension); this.textFieldValue.setPreferredSize(dimension); this.spinnerDotDensityValue.setPreferredSize(dimension); this.buttonDotDensityStyle.setPreferredSize(dimension); //@formatter:off JPanel panelContent = new JPanel(); panelContent.setLayout(new GridBagLayout()); panelContent.add(labelExpression, new GridBagConstraintsHelper(0, 0, 1, 1).setAnchor(GridBagConstraints.WEST).setInsets(5,10,5,10).setWeight(40, 1).setIpad(20, 0)); panelContent.add(comboBoxExpression, new GridBagConstraintsHelper(1, 0, 2, 1).setAnchor(GridBagConstraints.WEST).setInsets(5,10,5,10).setWeight(60, 1).setFill(GridBagConstraints.HORIZONTAL)); panelContent.add(labelValue, new GridBagConstraintsHelper(0, 1, 1, 1).setAnchor(GridBagConstraints.WEST).setInsets(0,10,5,10).setWeight(40, 1).setIpad(20, 0)); panelContent.add(textFieldValue, new GridBagConstraintsHelper(1, 1, 2, 1).setAnchor(GridBagConstraints.WEST).setInsets(0,10,5,10).setWeight(60, 1).setFill(GridBagConstraints.HORIZONTAL)); panelContent.add(labelDotDensityValue, new GridBagConstraintsHelper(0, 2, 1, 1).setAnchor(GridBagConstraints.WEST).setInsets(0,10,5,10).setWeight(40, 1).setIpad(20, 0)); panelContent.add(spinnerDotDensityValue, new GridBagConstraintsHelper(1, 2, 2, 1).setAnchor(GridBagConstraints.WEST).setInsets(0,10,5,10).setWeight(60, 1).setFill(GridBagConstraints.HORIZONTAL)); panelContent.add(labelDotDensityStyle, new GridBagConstraintsHelper(0, 3, 1, 1).setAnchor(GridBagConstraints.WEST).setInsets(0,10,5,10).setWeight(40, 1).setIpad(20, 0)); panelContent.add(buttonDotDensityStyle, new GridBagConstraintsHelper(1, 3, 2, 1).setAnchor(GridBagConstraints.WEST).setInsets(0,10,5,10).setWeight(60, 1).setFill(GridBagConstraints.HORIZONTAL)); this.panelProperty.setLayout(new GridBagLayout()); this.panelProperty.add(panelContent, new GridBagConstraintsHelper(0, 0, 1, 1).setWeight(1, 1).setAnchor(GridBagConstraints.NORTH).setFill(GridBagConstraints.HORIZONTAL).setInsets(5, 10, 5, 10)); //@formatter:on } private void initComboBoxExpression() { //处理点击下拉列表框地图卡顿,同 themeUniqueContainer this.comboBoxExpression.removeItemListener(this.expressionListener); this.comboBoxArray = new ArrayList<String>(); ThemeUtil.initComboBox(comboBoxExpression, themeDotDensity.getDotExpression(), datasetVector, themeDotDensityLayer.getDisplayFilter().getJoinItems(), comboBoxArray, true, false); this.comboBoxExpression.addItemListener(this.expressionListener); } private void initTextFieldValue() { this.textFieldValue.setText(String.valueOf(format.format(themeDotDensity.getValue()))); String expression = themeDotDensity.getDotExpression(); setThemeDotDensityInfo(expression); if (Double.compare(themeDotDensity.getValue(), 0.0) != 0) { int splinnerValue = Integer.parseInt(new DecimalFormat("#").format(maxValue / themeDotDensity.getValue())); this.spinnerDotDensityValue.setValue(splinnerValue); } } private void setThemeDotDensityInfo(String expression) { String tempExpression = expression; DatasetVector dataset = this.datasetVector; if (expression.contains(".")) { String datasetName = expression.substring(0, expression.indexOf(".")); dataset = (DatasetVector) dataset.getDatasource().getDatasets().get(datasetName); } maxValue = ThemeGuideFactory.getMaxValue(dataset, tempExpression, this.themeDotDensityLayer.getDisplayFilter().getJoinItems()); } @Override public Theme getCurrentTheme() { return this.themeDotDensity; } @Override public Layer getCurrentLayer() { return this.themeDotDensityLayer; } @Override public void setCurrentLayer(Layer layer) { this.themeDotDensityLayer = layer; } @Override public void registActionListener() { this.textFieldValue.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { int keyChar = e.getKeyChar(); if ((keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9) || keyChar == '.') { return; } else { e.consume(); } } @Override public void keyReleased(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ENTER) { resetValue(); } } }); unregistActionListener(); this.comboBoxExpression.addItemListener(this.expressionListener); this.buttonDotDensityStyle.addActionListener(this.buttonActionListener); this.textFieldValue.addFocusListener(this.textFieldListener); this.spinnerDotDensityValue.addChangeListener(this.changeListener); this.comboBoxExpression.getComponent(0).addMouseListener(this.mouseAdapter); } @Override public void unregistActionListener() { this.comboBoxExpression.removeItemListener(this.expressionListener); this.buttonDotDensityStyle.removeActionListener(this.buttonActionListener); this.textFieldValue.removeFocusListener(this.textFieldListener); this.spinnerDotDensityValue.removeChangeListener(this.changeListener); this.comboBoxExpression.getComponent(0).removeMouseListener(this.mouseAdapter); } class TextFieldListener extends FocusAdapter { @Override public void focusLost(FocusEvent e) { resetValue(); } } private void resetValue() { String strValue = textFieldValue.getText(); if (!StringUtilities.isNullOrEmpty(strValue) && StringUtilities.isNumber(strValue)) { themeDotDensity.setValue(Double.parseDouble(strValue)); double newValue = maxValue / themeDotDensity.getValue(); // 为了触发spinner的ChangeListener事件而设置两次 spinnerDotDensityValue.setValue(0); if (Double.compare(newValue, 1.0) < 0) { newValue = 1.0; } int splinnerValue = Integer.parseInt(new DecimalFormat("#").format(newValue)); spinnerDotDensityValue.setValue(splinnerValue); refreshAtOnce(); } else { textFieldValue.setText(format.format(themeDotDensity.getValue())); } } class ExpressionListener implements ItemListener { @Override public void itemStateChanged(ItemEvent e) { Dataset[] datasets = ThemeUtil.getDatasets(themeDotDensityLayer, datasetVector); if (e.getStateChange() == ItemEvent.SELECTED) { // sql表达式 String tempExpression = themeDotDensity.getDotExpression(); if (!comboBoxArray.contains(tempExpression)) { tempExpression = tempExpression.substring(tempExpression.indexOf(".") + 1, tempExpression.length()); } boolean itemHasChanged = ThemeUtil.getSqlExpression(comboBoxExpression, datasets, comboBoxArray, tempExpression, true); // 修改表达式 if (itemHasChanged) { // 如果sql表达式中修改了选项 tempExpression = comboBoxExpression.getSelectedItem().toString(); setThemeDotDensityInfo(tempExpression); if (maxValue > 0) { themeDotDensity.setDotExpression(tempExpression); int dotValue = (int) spinnerDotDensityValue.getValue(); themeDotDensity.setValue(maxValue / dotValue); textFieldValue.setText(String.valueOf(format.format(maxValue / dotValue))); refreshAtOnce(); } else { SmOptionPane smOptionPane = new SmOptionPane(); smOptionPane.showMessageDialog(MapViewProperties.getString("String_MaxValue")); resetThemeItem(); } } } } } private void resetThemeItem() { String tempExpression = themeDotDensity.getDotExpression(); if (comboBoxArray.contains(tempExpression)) { comboBoxExpression.setSelectedItem(tempExpression); } else { comboBoxExpression.setSelectedItem(tempExpression.substring(tempExpression.indexOf(".") + 1, tempExpression.length())); } } class ButtonActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { SymbolDialog symbolStyle = SymbolDialogFactory.getSymbolDialog(SymbolType.MARKER); GeoStyle geoStyle = themeDotDensity.getStyle(); ISymbolApply symbolApply = new ISymbolApply() { @Override public void apply(GeoStyle geoStyle) { themeDotDensity.setStyle(geoStyle); refreshAtOnce(); return; } }; DialogResult dialogResult; if (null != geoStyle) { dialogResult = symbolStyle.showDialog(geoStyle, symbolApply); } else { dialogResult = symbolStyle.showDialog(new GeoStyle(), symbolApply); } if (DialogResult.OK.equals(dialogResult)) { GeoStyle nowGeoStyle = symbolStyle.getCurrentGeoStyle(); themeDotDensity.setStyle(nowGeoStyle); refreshAtOnce(); symbolStyle = null; return; } } } class SpinnerListener implements ChangeListener { @Override public void stateChanged(ChangeEvent e) { double value = Double.parseDouble(spinnerDotDensityValue.getValue().toString()); final double dotValue = maxValue / value; themeDotDensity.setValue(dotValue); textFieldValue.setText(String.valueOf(format.format(dotValue))); refreshAtOnce(); } } @Override public void setRefreshAtOnce(boolean isRefreshAtOnce) { this.isRefreshAtOnce = isRefreshAtOnce; } private void refreshAtOnce() { firePropertyChange("ThemeChange", null, null); if (isRefreshAtOnce) { refreshMapAndLayer(); } } @Override public void refreshMapAndLayer() { if (null != ThemeGuideFactory.getMapControl()) { this.map = ThemeGuideFactory.getMapControl().getMap(); } this.themeDotDensityLayer = MapUtilities.findLayerByName(map, layerName); if (null != themeDotDensityLayer && null != themeDotDensityLayer.getTheme() && themeDotDensityLayer.getTheme().getType() == ThemeType.DOTDENSITY) { ThemeDotDensity nowThemeDotDensity = ((ThemeDotDensity) this.themeDotDensityLayer.getTheme()); nowThemeDotDensity.fromXML(themeDotDensity.toXML()); this.map.refresh(); } } }
14,269
Java
.java
318
41.141509
197
0.7912
SuperMap-iDesktop/SuperMap-iDesktop-Cross
31
19
1
GPL-3.0
9/4/2024, 7:24:11 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
14,109
2,869,999
SolarFluxSettingsDaoConfig.java
SolarNetwork_solarnetwork-central/solarnet/solardin/src/main/java/net/solarnetwork/central/din/app/config/SolarFluxSettingsDaoConfig.java
/* ================================================================== * SolarFluxSettingsDaoConfig.java - 26/06/2024 3:48:19 pm * * Copyright 2024 SolarNetwork.net Dev Team * * 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., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * ================================================================== */ package net.solarnetwork.central.din.app.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import net.solarnetwork.central.datum.flux.dao.FluxPublishSettingsDao; import net.solarnetwork.central.datum.flux.dao.StaticFluxPublishSettingsDao; import net.solarnetwork.central.datum.flux.domain.FluxPublishSettingsInfo; /** * SolarFlux settings DAO configuration. * * @author matt * @version 1.0 */ @Configuration(proxyBeanMethods = false) public class SolarFluxSettingsDaoConfig { @Bean public FluxPublishSettingsDao staticFluxPublishSettingsDao() { return new StaticFluxPublishSettingsDao(FluxPublishSettingsInfo.PUBLISH_NOT_RETAINED); } }
1,703
Java
.java
40
40.375
88
0.732972
SolarNetwork/solarnetwork-central
5
6
0
GPL-2.0
9/4/2024, 10:30:23 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,703
543,426
ItemBrainCoralStack.java
AllayMC_Allay/api/src/main/java/org/allaymc/api/item/interfaces/coral/ItemBrainCoralStack.java
package org.allaymc.api.item.interfaces.coral; import org.allaymc.api.item.ItemStack; public interface ItemBrainCoralStack extends ItemStack { }
147
Java
.java
4
35.25
56
0.858156
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
147
3,217,746
DataSourceFullHarvesterJob.java
52North_sensorweb-server-helgoland-adapters/harvest/src/main/java/org/n52/sensorweb/server/helgoland/adapters/harvest/DataSourceFullHarvesterJob.java
/* * Copyright (C) 2015-2023 52°North Spatial Information Research GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public License * version 2 and the aforementioned licenses. * * 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. */ package org.n52.sensorweb.server.helgoland.adapters.harvest; import org.n52.bjornoya.schedule.FullHarvesterJob; import org.n52.sensorweb.server.helgoland.adapters.connector.AbstractServiceConstellation; import org.n52.sensorweb.server.helgoland.adapters.connector.ConnectorRequestFailedException; import org.quartz.DisallowConcurrentExecution; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.PersistJobDataAfterExecution; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @SuppressWarnings("SpringJavaAutowiredMembersInspection") @PersistJobDataAfterExecution @DisallowConcurrentExecution @SuppressFBWarnings({ "EI_EXPOSE_REP", "EI_EXPOSE_REP2" }) public class DataSourceFullHarvesterJob extends AbstractDataSourceHarvesterJob implements FullHarvesterJob { private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceFullHarvesterJob.class); public DataSourceFullHarvesterJob() { } protected void process(JobExecutionContext context) throws JobExecutionException { DataSourceJobConfiguration dataSourceJobConfiguration = getDataSourceJobConfiguration(); AbstractServiceConstellation result = determineConstellation(dataSourceJobConfiguration); try { if (result == null) { LOGGER.warn("No connector found for {}", dataSourceJobConfiguration); } else { FullHarvester harvester = getHelper().getFullHarvester(result.getFullHarvester()); if (harvester == null) { LOGGER.warn("No harvester found for {}", result.getFullHarvester()); } else { harvester.process(result.getHavesterContext()); submitEvent(result.getEvent()); } for (HarvestingListener listener : getHelper().getHarvestListener()) { try { listener.onResult(result); } catch (Throwable t) { LOGGER.warn("error executing listener " + listener, t); } } } } catch (ConnectorRequestFailedException ex) { throw new JobExecutionException(ex); } } protected Class<DataSourceFullHarvesterJob> getClazz() { return DataSourceFullHarvesterJob.class; } }
3,720
Java
.java
76
42.197368
108
0.726423
52North/sensorweb-server-helgoland-adapters
4
5
11
GPL-2.0
9/4/2024, 11:05:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,720
3,047,246
VisibilityRefactoring.java
Cevelop_cevelop/CevelopProject/bundles/com.cevelop.tdd/src/com/cevelop/tdd/refactorings/visibility/VisibilityRefactoring.java
/******************************************************************************* * Copyright (c) 2011, IFS Institute for Software, HSR Rapperswil, * Switzerland, http://ifs.hsr.ch * * Permission to use, copy, and/or distribute this software for any * purpose without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. *******************************************************************************/ package com.cevelop.tdd.refactorings.visibility; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.cpp.ICPPMember; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.refactoring.NodeContainer; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import ch.hsr.ifs.iltis.cpp.core.ui.refactoring.SelectionRefactoring; import ch.hsr.ifs.iltis.cpp.core.wrappers.ModificationCollector; import com.cevelop.tdd.helpers.TddHelper; import com.cevelop.tdd.helpers.TypeHelper; import com.cevelop.tdd.infos.VisibilityInfo; public class VisibilityRefactoring extends SelectionRefactoring<VisibilityInfo> { public VisibilityRefactoring(final ICElement element, final VisibilityInfo info) { super(element, info); } /** * {@inheritDoc} */ @Override public String getName() { return Messages.ChangeVisibility_name; } @Override protected RefactoringDescriptor getRefactoringDescriptor() { String comment = selectedRegion != null ? Messages.ChangeVisibility_descWithSection : Messages.ChangeVisibility_descWoSection; return new VisibilityRefactoringDescriptor(project.getProject().getName(), Messages.ChangeVisibility_name, comment, info); } @Override protected void collectModifications(IProgressMonitor pm, ModificationCollector collector) throws CoreException, OperationCanceledException { if (!selection.isPresent()) { return; } IASTTranslationUnit localunit = refactoringContext.getAST(tu, pm); IASTNode selectedNode = localunit.getNodeSelector(null).findEnclosingNode(selection.get().getOffset(), selection.get().getLength()); if (!(selectedNode instanceof IASTName)) { return; } ICPPASTCompositeTypeSpecifier typeSpec = TypeHelper.getTypeOfMember(localunit, (IASTName) selectedNode, refactoringContext); MethodFindVisitor memberfinder = new MethodFindVisitor(info.memberName); typeSpec.accept(memberfinder); IASTNode function = memberfinder.getFoundNode(); if (function == null) { TddHelper.showErrorOnStatusLine(Messages.ChangeVisibilityRefactoring_0); return; } ASTRewrite rewrite = collector.rewriterForTranslationUnit(typeSpec.getTranslationUnit()); rewrite.remove(function, null); TddHelper.insertMember(function, typeSpec, rewrite); } class MethodFindVisitor extends ASTVisitor { private final NodeContainer container; private final String nameToSearch; { shouldVisitNames = true; } public MethodFindVisitor(String nameToSearch) { this.container = new NodeContainer(); this.nameToSearch = nameToSearch; } @Override public int visit(IASTName name) { IBinding binding = name.resolveBinding(); if (binding instanceof ICPPMember) { String bindingname = binding.getName().replaceAll("\\(\\w*\\)", ""); if (bindingname.equals(nameToSearch)) { ICPPASTCompositeTypeSpecifier typeSpec = TddHelper.getAncestorOfType(name, ICPPASTCompositeTypeSpecifier.class); if (typeSpec != null) { IASTNode function = TddHelper.getAncestorOfType(name, ICPPASTFunctionDefinition.class); if (function == null) { function = TddHelper.getAncestorOfType(name, IASTSimpleDeclaration.class); } container.add(function); return PROCESS_ABORT; } } } return PROCESS_CONTINUE; } public IASTNode getFoundNode() { if (container.size() > 0) { return container.getNodesToWrite().get(0); } return null; } } }
5,075
Java
.java
105
40.009524
144
0.679855
Cevelop/cevelop
5
0
41
EPL-2.0
9/4/2024, 10:44:33 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
5,075
3,314,301
VerifyVersionResult.java
wultra_mobile-utility-server/src/main/java/com/wultra/app/mobileutilityserver/rest/model/response/VerifyVersionResult.java
/* * Wultra Mobile Utility Server * Copyright (C) 2023 Wultra s.r.o. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.wultra.app.mobileutilityserver.rest.model.response; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * Response version verification. * * @author Lubos Racansky, lubos.racansky@wultra.com */ @Getter @EqualsAndHashCode @ToString @Builder public class VerifyVersionResult { @lombok.NonNull @Schema(requiredMode = Schema.RequiredMode.REQUIRED) private Update update; @Schema( description = "Optional localized message, should be filled when the status is 'SUGGEST_UPDATE' or 'REQUIRE_UPDATE'.", requiredMode = Schema.RequiredMode.NOT_REQUIRED ) private String message; /** * Create ok response. * * @return ok response */ public static VerifyVersionResult ok() { return VerifyVersionResult.builder() .update(Update.NOT_REQUIRED) .build(); } public enum Update { NOT_REQUIRED, SUGGESTED, FORCED } }
1,826
Java
.java
57
27.877193
130
0.723453
wultra/mobile-utility-server
4
2
4
AGPL-3.0
9/4/2024, 11:12:15 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,826
4,288,339
CounterNode.java
muthhus_narchy/util/src/main/java/jcog/tree/rtree/util/CounterNode.java
package jcog.tree.rtree.util; /* * #%L * Conversant RTree * ~~ * Conversantmedia.com © 2016, Conversant, Inc. Conversant® is a trademark of Conversant, Inc. * ~~ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import jcog.tree.rtree.HyperRegion; import jcog.tree.rtree.Node; import jcog.tree.rtree.Nodelike; import jcog.tree.rtree.Spatialization; import java.util.Iterator; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; /** * Created by jcovert on 6/18/15. */ public final class CounterNode<T> implements Node<T, Object> { public static int searchCount; public static int bboxEvalCount; private final Node<T, Object> node; public CounterNode(final Node<T, Object> node) { this.node = node; } @Override public Object get(int i) { return node.get(i); } @Override public Stream<T> stream() { return node.stream(); } @Override public Iterator<Object> iterateNodes() { return node.iterateNodes(); } @Override public boolean isLeaf() { return this.node.isLeaf(); } @Override public HyperRegion bounds() { return this.node.bounds(); } @Override public Node<T, ?> add(T t, Nodelike<T> parent, Spatialization<T> model, boolean[] added) { return this.node.add(t, parent!=null ? this : null, model, added); } @Override public Node<T, ?> remove(T x, HyperRegion xBounds, Spatialization<T> model, boolean[] removed) { return this.node.remove(x, xBounds, model, removed); } @Override public Node<T, ?> update(T told, T tnew, Spatialization<T> model) { return this.node.update(told, tnew, model); } @Override public boolean AND(Predicate<T> p) { throw new UnsupportedOperationException("TODO"); } @Override public boolean OR(Predicate<T> p) { throw new UnsupportedOperationException("TODO"); } @Override public boolean containing(HyperRegion rect, Predicate<T> t, Spatialization<T> model) { searchCount++; bboxEvalCount += this.node.size(); return this.node.containing(rect, t, model); } // @Override // public void intersectingNodes(HyperRegion rect, Predicate<Node<T, ?>> t, Spatialization<T> model) { // node.intersectingNodes(rect, t, model); // } @Override public int size() { return this.node.size(); } @Override public void forEach(Consumer<? super T> consumer) { this.node.forEach(consumer); } @Override public boolean intersecting(HyperRegion rect, Predicate<T> t, Spatialization<T> model) { this.node.intersecting(rect, t, model); return false; } @Override public void collectStats(Stats stats, int depth) { this.node.collectStats(stats, depth); } @Override public Node<T, ?> instrument() { return this; } // @Override // public double perimeter(Spatialization<T> model) { // return node.perimeter(model); // } @Override public boolean contains(T t, HyperRegion b, Spatialization<T> model) { return node.contains(t, b, model); } }
3,762
Java
.java
118
27.161017
105
0.675145
muthhus/narchy
2
7
0
AGPL-3.0
9/5/2024, 12:07:57 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,760
542,116
CEntityLoadNBTEvent.java
AllayMC_Allay/server/src/main/java/org/allaymc/server/entity/component/event/CEntityLoadNBTEvent.java
package org.allaymc.server.entity.component.event; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import org.allaymc.api.eventbus.event.Event; import org.cloudburstmc.nbt.NbtMap; /** * @author daoge_cmd */ @Getter @Setter @AllArgsConstructor public class CEntityLoadNBTEvent extends Event { protected NbtMap nbt; }
354
Java
.java
15
22.066667
50
0.830861
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
354
3,980,667
Link.java
almejo_vsim/src/main/java/cl/almejo/vsim/gates/Link.java
package cl.almejo.vsim.gates; /** * vsim * <p> * This program is distributed under the terms of the GNU General Public License * The license is included in license.txt * * @author Alejandro Vera */ class Link { private Link link = this; private Link find(Link link) { Link currentLink = this.link; do { if (currentLink == link) { return link; } currentLink = link; } while (currentLink != this); return null; } void join(Link link) { if (find(link) != null) { link.link = this.link; this.link = link; } } Link getNext() { return link; } void delete() { Link previous = findPrevious(); if (previous != null) { previous.link = link; link = this; } } private Link findPrevious() { Link previous = this; do { Link next = previous.getNext(); if (next == this) { return previous; } previous = next; } while (previous != this); return null; } }
931
Java
.java
49
16.102041
80
0.651826
almejo/vsim
2
0
19
GPL-3.0
9/4/2024, 11:59:09 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
931
3,314,375
WaypointCommand.java
freethemanatee_manatee-plus/src/main/java/me/manatee/plus/command/commands/WaypointCommand.java
package me.manatee.plus.command.commands; import me.manatee.plus.ManateePlus; import me.manatee.plus.command.Command; import me.manatee.plus.waypoint.Waypoint; import net.minecraft.client.Minecraft; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.event.HoverEvent; import java.awt.*; public class WaypointCommand extends Command { @Override public String[] getAlias() { return new String[]{ "waypoint", "point", "wp", "waypoints", "points" }; } @Override public String getSyntax() { return "waypoint <add | del | list> <name> <x> <y> <z> <(optional) color>"; } @Override public void onCommand(String command, String[] args) throws Exception { if (args[0].equalsIgnoreCase("add")) { if (args.length == 6) { ManateePlus.getInstance().waypointManager.addWaypoint(new Waypoint( args[1], Double.parseDouble(args[2]), Double.parseDouble(args[3]), Double.parseDouble(args[4]), Color.getColor(args[5]))); sendClientMessage("added waypoint: Name: " + args[1] + " x" + Double.parseDouble(args[2]) + " y" + Double.parseDouble(args[3]) + " z" + Double.parseDouble(args[4]) + " Color: " + Color.getColor(args[5])); } else if (args.length == 5) { ManateePlus.getInstance().waypointManager.addWaypoint(new Waypoint( args[1], Double.parseDouble(args[2]), Double.parseDouble(args[3]), Double.parseDouble(args[4]))); sendClientMessage("added waypoint: Name: " + args[1] + " x" + Double.parseDouble(args[2]) + " y" + Double.parseDouble(args[3]) + " z" + Double.parseDouble(args[4])); } } else if (args[0].equalsIgnoreCase("del") || args[0].equalsIgnoreCase("remove")) { ManateePlus.getInstance().waypointManager.delWaypoint(ManateePlus.getInstance().waypointManager.getWaypointByName(args[1])); } else if (args[0].equalsIgnoreCase("list")) { TextComponentString tcs = new TextComponentString(""); ManateePlus.getInstance().waypointManager.getWaypoints().forEach(w -> { tcs.appendSibling(new TextComponentString(w.getName() + ", ")) .setStyle(new Style() .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("x" + w.getX() + " y" + w.getY() + " z" + w.getZ())))); }); Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(tcs); } } }
2,862
Java
.java
55
39.509091
170
0.580864
freethemanatee/manatee-plus
4
3
0
GPL-3.0
9/4/2024, 11:12:15 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,862
4,695,585
ModelItemContentProvider.java
eclipse-dali_webtools_dali/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/jface/ModelItemContentProvider.java
/******************************************************************************* * Copyright (c) 2007, 2013 Oracle. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0, which accompanies this distribution * and is available at https://www.eclipse.org/legal/epl-2.0/. * * Contributors: * Oracle - initial API and implementation ******************************************************************************/ package org.eclipse.jpt.common.ui.internal.jface; import java.util.ConcurrentModificationException; import org.eclipse.jpt.common.ui.internal.swt.listeners.SWTListenerTools; import org.eclipse.jpt.common.ui.jface.ItemContentProvider; import org.eclipse.jpt.common.utility.internal.ArrayTools; import org.eclipse.jpt.common.utility.internal.ObjectTools; import org.eclipse.jpt.common.utility.internal.iterable.EmptyIterable; import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; import org.eclipse.jpt.common.utility.model.listener.CollectionChangeAdapter; import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; /** * This abstract class provides the behavior common to item structure and tree * content providers (i.e. maintaining a list of an item's elements/children). * * @param <M> the type of the provider's manager */ abstract class ModelItemContentProvider<M extends ItemContentProvider.Manager> implements ItemContentProvider { /* private-protected */ final Object item; private final CollectionValueModel<?> childrenModel; private final CollectionChangeListener childrenListener; /** * The children must be accessed on the manager's UI thread. * This is <code>null</code> when the provider is disposed. */ /* private-protected */ Object[] children; /* private-protected */ final M manager; /* private-protected */ static final Iterable<?> EMPTY_ITERABLE = EmptyIterable.instance(); ModelItemContentProvider(Object item, CollectionValueModel<?> childrenModel, M manager) { super(); if (item == null) { throw new NullPointerException(); } this.item = item; if (childrenModel == null) { throw new NullPointerException(); } this.childrenModel = childrenModel; if (manager == null) { throw new NullPointerException(); } this.manager = manager; this.childrenListener = this.buildChildrenListener(); this.childrenModel.addCollectionChangeListener(CollectionValueModel.VALUES, this.childrenListener); this.children = this.buildChildren(); } // ********** children ********** /* private-protected */ Object[] getChildren() { return this.children; } private CollectionChangeListener buildChildrenListener() { return SWTListenerTools.wrap(this.buildChildrenListener_(), this.manager.getViewer()); } private CollectionChangeListener buildChildrenListener_() { return new ChildrenListener(); } /* CU private */ class ChildrenListener extends CollectionChangeAdapter { @Override public void itemsAdded(CollectionAddEvent event) { ModelItemContentProvider.this.childrenAdded(event.getItems()); } @Override public void itemsRemoved(CollectionRemoveEvent event) { ModelItemContentProvider.this.childrenRemoved(event.getItems()); } @Override public void collectionChanged(CollectionChangeEvent event) { ModelItemContentProvider.this.childrenChanged(); } @Override public void collectionCleared(CollectionClearEvent event) { ModelItemContentProvider.this.childrenCleared(); } } /* CU private */ void childrenAdded(Iterable<?> addedChildren) { if (this.isAlive()) { this.childrenAdded_(addedChildren); } } private void childrenAdded_(Iterable<?> addedChildren) { this.children = ArrayTools.addAll(this.children, addedChildren); this.notifyManager(addedChildren, EMPTY_ITERABLE); } /* CU private */ void childrenRemoved(Iterable<?> removedChildren) { if (this.isAlive()) { this.childrenRemoved_(removedChildren); } } private void childrenRemoved_(Iterable<?> removedChildren) { this.children = ArrayTools.removeAll(this.children, removedChildren); this.notifyManager(EMPTY_ITERABLE, removedChildren); } /* CU private */ void childrenChanged() { if (this.isAlive()) { this.childrenChanged_(); } } private void childrenChanged_() { Object[] old = this.children; this.children = this.buildChildren(); Iterable<?> addedChildren = ArrayTools.iterable(ArrayTools.removeAll(this.children, old)); Iterable<?> removedChildren = ArrayTools.iterable(ArrayTools.removeAll(old, this.children)); this.notifyManager(addedChildren, removedChildren); } /* CU private */ void childrenCleared() { if (this.isAlive()) { this.childrenCleared_(); } } private void childrenCleared_() { Object[] old = this.children; this.children = ObjectTools.EMPTY_OBJECT_ARRAY; if (old.length != 0) { this.notifyManager(EMPTY_ITERABLE, ArrayTools.iterable(old)); } } /** * Notify the item content provider's manager the item's list of children * has changed. */ /* private-protected */ abstract void notifyManager(Iterable<?> addedChildren, Iterable<?> removedChildren); private Object[] buildChildren() { while (true) { try { return ArrayTools.array(this.childrenModel); } catch (ConcurrentModificationException ex) { // try again - hack: need to make value models thread-safe... TODO bjv } } } // ********** dispose ********** public void dispose() { this.childrenModel.removeCollectionChangeListener(CollectionValueModel.VALUES, this.childrenListener); this.children = null; // NB: disposed! } // ********** misc ********** /** * Check whether the provider was disposed between the time an event was * fired and the time the event is handled on the UI thread. */ private boolean isAlive() { return this.children != null; } @Override public String toString() { return ObjectTools.toString(this, this.item); } }
6,277
Java
.java
164
35.536585
109
0.746215
eclipse-dali/webtools.dali
2
3
7
EPL-2.0
9/5/2024, 12:21:48 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,277
3,390,034
Data.java
project-BarryBarry_coffeeport/src/main/java/com/barrybarry/coffeeport/data/xml/Data.java
package com.barrybarry.coffeeport.data.xml; import com.barrybarry.coffeeport.type.CommandType; import lombok.Getter; import lombok.Setter; @Getter @Setter @SuppressWarnings({"FieldCanBeLocal", "unused"}) public class Data { private CommandType cmd; private InstallationConfigureData configure; }
307
Java
.java
11
25.909091
50
0.829352
project-BarryBarry/coffeeport
4
1
5
GPL-3.0
9/4/2024, 11:17:49 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
307
1,527,404
Member.java
choral-lang_choral/choral/src/main/java/choral/types/Member.java
/* * Copyright (C) 2019 by Saverio Giallorenzo <saverio.giallorenzo@gmail.com> * Copyright (C) 2019 by Fabrizio Montesi <famontesi@gmail.com> * Copyright (C) 2019 by Marco Peressotti <marco.peressotti@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library 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 Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package choral.types; import choral.ast.Node; import choral.exceptions.StaticVerificationException; import choral.utils.Formatting; import java.util.*; import java.util.stream.Collectors; import static choral.types.Modifier.*; import static choral.types.ModifierUtils.assertAccessModifiers; import static choral.types.ModifierUtils.assertIllegalCombinationOfModifiers; public abstract class Member implements HasSource { protected Member( GroundClassOrInterface declarationContext, String identifier, Variety variety, EnumSet< Modifier > modifiers ) { this( declarationContext, identifier, variety, modifiers, true ); } protected Member( GroundClassOrInterface declarationContext, String identifier, Variety variety, EnumSet< Modifier > modifiers, boolean checkModifiers ) { this.declarationContext = declarationContext; this.variety = variety; this.modifiers = EnumSet.copyOf( modifiers ); this.identifier = identifier; if( checkModifiers ) { assertModifiers( modifiers ); } } // source code position for error reporting private Node source; @Override public final Optional< Node > sourceCode() { return Optional.ofNullable( source ); } @Override public final void setSourceCode( Node source ) { this.source = source; } private final String identifier; public String identifier() { return identifier; } private final EnumSet< Modifier > modifiers; protected void assertModifiers( EnumSet< Modifier > modifiers ) { assertAccessModifiers( modifiers ); assertIllegalCombinationOfModifiers( modifiers, ABSTRACT, STATIC ); assertIllegalCombinationOfModifiers( modifiers, ABSTRACT, PRIVATE ); assertIllegalCombinationOfModifiers( modifiers, ABSTRACT, FINAL ); } protected final EnumSet< Modifier > modifiers() { return modifiers; } public final boolean isAbstract() { return modifiers.contains( ABSTRACT ); } public final boolean isPublic() { return modifiers.contains( PUBLIC ); } public final boolean isPrivate() { return modifiers.contains( PRIVATE ); } public final boolean isProtected() { return modifiers.contains( PROTECTED ); } public final boolean isPackagePrivate() { return !isPublic() && !isProtected() && !isPrivate(); } public final boolean isFinal() { return modifiers.contains( FINAL ); } public final boolean isStatic() { return modifiers.contains( STATIC ); } public final boolean isAccessibleFrom( GroundClassOrInterface context ) { /* DEBUG */ // System.out.println("-- isAccessible"); // System.out.println(" " + this); // System.out.println(" " + this.declarationContext + " == " + context + " " + (this.declarationContext == context)); // System.out.println(" " + this.isPublic()); // System.out.println(" " + this.isProtected()); // System.out.println(" " + this.isPrivate()); // System.out.println(" " + this.isPackagePrivate()); // System.out.println("-- result = " + (this.declarationContext == context || this.isPublic() || this.isProtected() || ( this.isPackagePrivate() && // context.declarationPackage() == this.declarationContext().declarationPackage() ))); return this.declarationContext == context || this.isPublic() || this.isProtected() || ( this.isPackagePrivate() && this.declarationContext().declarationPackage() == context.declarationPackage() ) || ( this.isPrivate() && this.declarationContext().typeConstructor() == context.typeConstructor() ); } public final boolean isAccessibleFrom( GroundTypeParameter context ) { return this.isPublic() || this.isProtected() || ( this.isPackagePrivate() && this.declarationContext().declarationPackage() == context.typeConstructor().declarationContext().declarationPackage() ); } private final GroundClassOrInterface declarationContext; public GroundClassOrInterface declarationContext() { return declarationContext; } public enum Variety { FIELD( "field" ), METHOD( "method" ), CONSTRUCTOR( "constructor" ); public final String label; Variety( String label ) { this.label = label; } } private final Variety variety; public final Variety variety() { return variety; } abstract Member applySubstitution( Substitution substitution ); public static final class Field extends Member { private final GroundDataType type; public Field( GroundClassOrInterface declarationContext, String identifier, EnumSet< Modifier > modifiers, GroundDataType type ) { super( declarationContext, identifier, Variety.FIELD, modifiers ); this.type = type; } private Field( GroundClassOrInterface declarationContext, String identifier, EnumSet< Modifier > modifiers, GroundDataType type, boolean performCheks ) { super( declarationContext, identifier, Variety.FIELD, modifiers, performCheks ); this.type = type; } @Override protected void assertModifiers( EnumSet< Modifier > modifiers ) { if( modifiers.contains( ABSTRACT ) ) { throw new StaticVerificationException( "modifier 'abstract' not allowed for fields" ); } super.assertModifiers( modifiers ); } public GroundDataType type() { return type; } @Override Field applySubstitution( Substitution substitution ) { GroundDataType type = this.type().applySubstitution( substitution ); GroundClassOrInterface declarationContext = this.declarationContext().applySubstitution( substitution ); return new Field( declarationContext, identifier(), modifiers(), type, false ); } } public static abstract class HigherCallable extends Member implements TypeParameterDeclarationContext { private final static String CONSTRUCTOR_NAME = "new"; protected HigherCallable( GroundClassOrInterface declarationContext, String identifier, Variety variety, EnumSet< Modifier > modifiers, List< HigherTypeParameter > typeParameters, boolean performChecks ) { super( declarationContext, identifier, variety, modifiers, performChecks ); this.typeParameters = new ArrayList<>( typeParameters ); if( performChecks ) { String[] names = new String[ typeParameters.size() ]; int i = 0; for( HigherTypeParameter x : typeParameters ) { x.setDeclarationContext( this ); for( int j = 0; j < i; j++ ) { if( names[ j ].equals( x.identifier() ) ) { throw StaticVerificationException.of( "duplicate type parameter '" + names[ j ] + "'", x.sourceCode() ); } } names[ i++ ] = x.identifier(); } } } @Override public Package declarationPackage() { return declarationContext().typeConstructor().declarationPackage(); } private final ArrayList< HigherTypeParameter > typeParameters; @Override public List< ? extends HigherTypeParameter > typeParameters() { return Collections.unmodifiableList( typeParameters ); } @Override public Optional< ? extends HigherTypeParameter > typeParameter( int index ) { if( 0 <= index && index < typeParameters.size() ) { return Optional.of( typeParameters.get( index ) ); } else { return Optional.empty(); } } @Override public Optional< ? extends HigherTypeParameter > typeParameter( String name ) { return typeParameters.stream().filter( x -> x.identifier().equals( name ) ).findAny(); } public abstract GroundCallable applyTo( List< ? extends HigherReferenceType > typeArgs ); protected final Substitution getApplicationSubstitution( List< ? extends HigherReferenceType > typeArgs ) { if( typeArgs.size() != typeParameters.size() ) { throw new StaticVerificationException( "illegal type instantiation: expected " + typeParameters.size() + " type arguments but found " + typeArgs.size() ); } Substitution substitution = new Substitution() { @Override public HigherReferenceType get( HigherTypeParameter placeHolder ) { int i = typeParameters.indexOf( placeHolder ); return ( i == -1 ) ? placeHolder : typeArgs.get( i ); } }; for( HigherTypeParameter t : typeParameters ) { t.assertWithinBounds( substitution ); } return substitution; } @Override abstract HigherCallable applySubstitution( Substitution substitution ); protected final List< HigherTypeParameter > prepareTypeParameters( Substitution substitution ) { Universe universe = declarationContext().universe(); List< HigherTypeParameter > newTypeParams = new ArrayList<>(); for( HigherTypeParameter t : typeParameters() ) { newTypeParams.add( new HigherTypeParameter( universe, t.identifier(), t.worldParameters.stream().map( x -> new World( universe, x.identifier() ) ).collect( Collectors.toList() ) ) ); } for( int i = 0; i < typeParameters().size(); i++ ) { HigherTypeParameter oldTypeParam = typeParameters().get( i ); HigherTypeParameter newTypeParam = newTypeParams.get( i ); List< World > newWorldParams = newTypeParam.worldParameters; // oldTypeParam.worldParameters().stream() // .map( x -> new World( universe, x.identifier() ) ).collect( // Collectors.toList() ); Substitution boundSubs = new Substitution() { @Override public World get( World placeHolder ) { int i = oldTypeParam.worldParameters.indexOf( placeHolder ); return ( i == -1 ) ? substitution.get( placeHolder ) : newWorldParams.get( i ); } @Override public HigherReferenceType get( HigherTypeParameter placeHolder ) { int i = typeParameters().indexOf( placeHolder ); return ( i == -1 ) ? substitution.get( placeHolder ) : newTypeParams.get( i ); } }; oldTypeParam.innerType().upperBound().forEach( x -> newTypeParam.innerType().addUpperBound( x.applySubstitution( boundSubs ) ) ); assert ( oldTypeParam.innerType().isBoundFinalised() ); newTypeParam.innerType().finaliseBound(); } return newTypeParams; } public boolean sameSignatureOf( HigherCallable other ) { if( !this.identifier().equals( other.identifier() ) || this.typeParameters.size() != other.typeParameters.size() || this.arity() != other.arity() ) { return false; } Substitution s1 = new Substitution() { @Override public HigherReferenceType get( HigherTypeParameter placeHolder ) { int i = typeParameters.indexOf( placeHolder ); return ( i == -1 ) ? placeHolder : other.typeParameters.get( i ); } }; Substitution s2 = new Substitution() { @Override public HigherReferenceType get( HigherTypeParameter placeHolder ) { int i = other.typeParameters().indexOf( placeHolder ); return ( i == -1 ) ? placeHolder : typeParameters.get( i ); } }; for( int i = 0; i < this.typeParameters.size(); i++ ) { HigherTypeParameter t1 = this.typeParameters.get( i ); HigherTypeParameter t2 = other.typeParameters.get( i ); if( !t1.isSameKind( t2 ) ) { return false; } GroundReferenceType g1 = t1.applyTo( t2.worldParameters ).applySubstitution( s1 ); GroundReferenceType g2 = t2.applyTo( t1.worldParameters ).applySubstitution( s2 ); if( !t1.innerType().upperBound().allMatch( g2::isSubtypeOf ) || !t2.innerType().upperBound().allMatch( g1::isSubtypeOf ) ) { return false; } } for( int i = 0; i < this.arity(); i++ ) { GroundDataType t1 = this.innerCallable().signature().parameters().get( i ).type(); GroundDataType t2 = other.innerCallable().signature().parameters().get( i ).type(); if( !t1.isEquivalentTo( t2.applySubstitution( s2 ) ) ) { return false; } } return true; } public boolean isSubSignatureOf( HigherCallable other ) { return this.sameSignatureOf( other ) || this.sameSignatureErasureOf( other ); } public boolean sameSignatureErasureOf( HigherCallable other ) { if( !this.typeParameters.isEmpty() || this.arity() != other.arity() || !this.identifier().equals( other.identifier() ) ) { return false; } for( int i = 0; i < this.arity(); i++ ) { GroundDataType t1 = this.innerCallable().signature().parameters().get( i ).type(); GroundDataType t2 = other.innerCallable().signature().parameters().get( i ).type(); if( !t1.isEquivalentToErasureOf( t2 ) ) { return false; } } return true; } public boolean sameErasureAs( HigherCallable other ) { if( this.arity() != other.arity() || !this.identifier().equals( other.identifier() ) ) { return false; } for( int i = 0; i < this.arity(); i++ ) { GroundDataType t1 = this.innerCallable().signature().parameters().get( i ).type(); GroundDataType t2 = other.innerCallable().signature().parameters().get( i ).type(); if( !t1.isEquivalentToErasureOf( t2 ) && !t2.isEquivalentToErasureOf( t1 ) ) { return false; } } return true; } public boolean isOverrideEquivalentTo( HigherCallable other ) { // (sec. 8.4.2) return this.sameSignatureOf( other ) || ( this.sameSignatureErasureOf( other ) == !other.sameSignatureErasureOf( this ) ); } public int arity() { return innerCallable().signature().parameters().size(); } public abstract Definition innerCallable(); public abstract class Definition implements GroundCallable { Definition( Signature signature ) { this.signature = signature; } @Override public List< ? extends HigherReferenceType > typeArguments() { return typeParameters(); } private final Signature signature; @Override public Signature signature() { return signature; } private boolean finalised = false; boolean isFinalised() { return finalised && signature().isFinalised(); } public void finalise() { signature().finalise(); finalised = true; } } protected abstract class Proxy implements GroundCallable { Proxy( Substitution substitution ) { this.substitution = substitution; } protected abstract Definition definition(); private final Substitution substitution; protected final Substitution substitution() { return substitution; } public final List< ? extends HigherReferenceType > typeArguments() { return HigherCallable.this.typeParameters().stream().map( substitution()::get ).collect( Collectors.toList() ); } public Signature signature() { return definition().signature().applySubstitution( substitution() ); } } } public interface GroundCallable { List< ? extends HigherReferenceType > typeArguments(); Signature signature(); HigherCallable higherCallable(); } public static final class HigherMethod extends HigherCallable { public HigherMethod( GroundClassOrInterface declarationContext, String identifier, EnumSet< Modifier > modifiers, List< HigherTypeParameter > typeParameters ) { this( declarationContext, identifier, modifiers, typeParameters, new Signature(), true ); } private HigherMethod( GroundClassOrInterface declarationContext, String identifier, EnumSet< Modifier > modifiers, List< HigherTypeParameter > typeParameters, Signature signature, boolean performChecks ) { super( declarationContext, identifier, Variety.METHOD, modifiers, typeParameters, performChecks ); assert ( !HigherCallable.CONSTRUCTOR_NAME.equals( identifier ) ); this.innerCallable = new Definition( signature ); } @Override public String toString() { return identifier() + innerCallable().signature(); } public boolean isReturnTypeAssignable( HigherMethod other ) { if( this.innerCallable().returnType.isVoid() && other.innerCallable().returnType.isVoid() ) { return true; } if( !this.innerCallable().returnType.isVoid() && !other.innerCallable().returnType.isVoid() ) { Substitution s2 = new Substitution() { @Override public HigherReferenceType get( HigherTypeParameter placeHolder ) { int i = other.typeParameters().indexOf( placeHolder ); return ( i == -1 ) ? placeHolder : HigherMethod.this.typeParameters().get( i ); } }; GroundDataType g2 = (GroundDataType) other.innerCallable.returnType.applySubstitution( s2 ); return innerCallable().returnType.isAssignableTo( g2 ); } return false; } boolean selectionMethod = false; public boolean isSelectionMethod() { return selectionMethod; } public void setSelectionMethod() { this.selectionMethod = true; } boolean typeSelectionMethod = false; public boolean isTypeSelectionMethod() { return typeSelectionMethod; } public void setTypeSelectionMethod() { this.typeSelectionMethod = true; } private final HashMap< Substitution, HigherMethod > alphaIndex = new HashMap<>(); @Override HigherMethod applySubstitution( Substitution substitution ) { HigherMethod result = alphaIndex.get( substitution ); if( result == null ) { List< HigherTypeParameter > newTypeParams = prepareTypeParameters( substitution ); Substitution newSubstitution = new Substitution() { @Override public World get( World placeHolder ) { return substitution.get( placeHolder ); } @Override public HigherReferenceType get( HigherTypeParameter placeHolder ) { int i = typeParameters().indexOf( placeHolder ); return ( i == -1 ) ? substitution.get( placeHolder ) : newTypeParams.get( i ); } }; Signature signature = this.innerCallable.signature().applySubstitution( newSubstitution ); result = new HigherMethod( this.declarationContext().applySubstitution( substitution ), identifier(), modifiers(), newTypeParams, signature, false ); result.innerCallable.setReturnType( this.innerCallable.returnType.applySubstitution( newSubstitution ) ); if( isSelectionMethod() ) { result.setSelectionMethod(); } if (isTypeSelectionMethod()) { result.setTypeSelectionMethod(); } result.innerCallable.finalise(); alphaIndex.put( substitution, result ); } return result; } HigherMethod copyFor( GroundClassOrInterface declarationContext ) { List< HigherTypeParameter > newTypeParams = prepareTypeParameters( Substitution.ID ); Substitution newSubstitution = new Substitution() { @Override public HigherReferenceType get( HigherTypeParameter placeHolder ) { int i = typeParameters().indexOf( placeHolder ); return ( i == -1 ) ? placeHolder : newTypeParams.get( i ); } }; Signature signature = this.innerCallable.signature().applySubstitution( newSubstitution ); HigherMethod result = new HigherMethod( declarationContext, identifier(), modifiers(), newTypeParams, signature, false ); result.innerCallable.setReturnType( this.innerCallable.returnType.applySubstitution( newSubstitution ) ); if( isSelectionMethod() ) { result.setSelectionMethod(); } if (isTypeSelectionMethod()) { result.setTypeSelectionMethod(); } result.innerCallable.finalise(); return result; } private final HashMap< List< ? extends HigherReferenceType >, GroundMethod > instIndex = new HashMap<>(); @Override public GroundMethod applyTo( List< ? extends HigherReferenceType > typeArgs ) { GroundMethod result = instIndex.get( typeArgs ); if( result == null ) { result = new Proxy( getApplicationSubstitution( typeArgs ) ); instIndex.put( typeArgs, result ); } return result; } private final Definition innerCallable; @Override public Definition innerCallable() { return innerCallable; } public final class Definition extends HigherCallable.Definition implements GroundMethod { private Definition( Signature signature ) { super( signature ); } @Override public String toString() { return typeArguments().stream().map( HigherReferenceType::toString ).collect( Formatting.joining( ",", "<", ">", "" ) ) + identifier() + signature(); } private GroundDataTypeOrVoid returnType; public GroundDataTypeOrVoid returnType() { return returnType; } public void setReturnType( GroundDataTypeOrVoid type ) { assert ( !isFinalised() ); this.returnType = type; } @Override public HigherMethod higherCallable() { return HigherMethod.this; } } private final class Proxy extends HigherCallable.Proxy implements GroundMethod { private Proxy( Substitution substitution ) { super( substitution ); } @Override public String toString() { return typeArguments().stream().map( HigherReferenceType::toString ).collect( Formatting.joining( ",", "<", ">", "" ) ) + identifier() + signature(); } @Override protected Definition definition() { return HigherMethod.this.innerCallable(); } public GroundDataTypeOrVoid returnType() { return definition().returnType().applySubstitution( substitution() ); } @Override public HigherMethod higherCallable() { return HigherMethod.this; } } } public interface GroundMethod extends GroundCallable { GroundDataTypeOrVoid returnType(); HigherMethod higherCallable(); } public static final class HigherConstructor extends HigherCallable { public HigherConstructor( GroundClass declarationContext, EnumSet< Modifier > modifiers, List< HigherTypeParameter > typeParameters ) { this( declarationContext, modifiers, typeParameters, new Signature(), true ); } private HigherConstructor( GroundClass declarationContext, EnumSet< Modifier > modifiers, List< HigherTypeParameter > typeParameters, Signature signature, boolean performChecks ) { super( declarationContext, HigherCallable.CONSTRUCTOR_NAME, Variety.CONSTRUCTOR, modifiers, typeParameters, performChecks ); this.innerCallable = new Definition( signature ); } @Override public String toString() { return declarationContext().typeConstructor().identifier() + innerCallable().signature(); } public GroundClass declarationContext() { return (GroundClass) super.declarationContext(); } private final HashMap< Substitution, HigherConstructor > alphaIndex = new HashMap<>(); @Override HigherConstructor applySubstitution( Substitution substitution ) { HigherConstructor result = alphaIndex.get( substitution ); if( result == null ) { List< HigherTypeParameter > newTypeParams = prepareTypeParameters( substitution ); Substitution newSubstitution = new Substitution() { @Override public World get( World placeHolder ) { return substitution.get( placeHolder ); } @Override public HigherReferenceType get( HigherTypeParameter placeHolder ) { int i = typeParameters().indexOf( placeHolder ); return ( i == -1 ) ? substitution.get( placeHolder ) : newTypeParams.get( i ); } }; result = new HigherConstructor( this.declarationContext().applySubstitution( substitution ), modifiers(), newTypeParams, this.innerCallable.signature().applySubstitution( newSubstitution ), false ); result.innerCallable.finalise(); alphaIndex.put( substitution, result ); } return result; } private final HashMap< List< ? extends HigherReferenceType >, GroundConstructor > instIndex = new HashMap<>(); @Override public GroundConstructor applyTo( List< ? extends HigherReferenceType > typeArgs ) { GroundConstructor result = instIndex.get( typeArgs ); if( result == null ) { result = new Proxy( getApplicationSubstitution( typeArgs ) ); instIndex.put( typeArgs, result ); } return result; } private final Definition innerCallable; @Override public Definition innerCallable() { return innerCallable; } public final class Definition extends HigherCallable.Definition implements GroundConstructor { private Definition( Signature signature ) { super( signature ); } @Override public String toString() { return typeArguments().stream().map( HigherReferenceType::toString ).collect( Formatting.joining( ",", "<", ">", "" ) ) + declarationContext().typeConstructor().identifier() + signature(); } @Override public HigherConstructor higherCallable() { return HigherConstructor.this; } } private final class Proxy extends HigherCallable.Proxy implements GroundConstructor { private Proxy( Substitution substitution ) { super( substitution ); } @Override public String toString() { return typeArguments().stream().map( HigherReferenceType::toString ).collect( Formatting.joining( ",", "<", ">", "" ) ) + declarationContext().typeConstructor().identifier() + signature(); } @Override protected Definition definition() { return HigherConstructor.this.innerCallable(); } @Override public HigherConstructor higherCallable() { return HigherConstructor.this; } } } public interface GroundConstructor extends GroundCallable { HigherConstructor higherCallable(); } }
26,266
Java
.java
749
30.566088
148
0.712794
choral-lang/choral
22
5
1
LGPL-2.1
9/4/2024, 7:56:41 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,266
2,213,203
FolderListItemAdapter.java
albu-razvan_Stario/app/src/main/java/com/stario/launcher/sheet/drawer/category/list/FolderListItemAdapter.java
/* Copyright (C) 2024 Răzvan Albu This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stario.launcher.sheet.drawer.category.list; import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.stario.launcher.R; import com.stario.launcher.apps.LauncherApplication; import com.stario.launcher.apps.categories.Category; import com.stario.launcher.sheet.drawer.BumpRecyclerViewAdapter; import com.stario.launcher.themes.ThemedActivity; import com.stario.launcher.ui.icons.AdaptiveIconView; import com.stario.launcher.ui.recyclers.async.AsyncRecyclerAdapter; import com.stario.launcher.utils.UiUtils; import java.util.function.Supplier; public class FolderListItemAdapter extends AsyncRecyclerAdapter<FolderListItemAdapter.ViewHolder> implements BumpRecyclerViewAdapter { public static final int SOFT_LIMIT = 3; public static final int HARD_LIMIT = 5; private final ThemedActivity activity; private Category category; private Category.CategoryItemListener listener; private boolean limit; private int size; public FolderListItemAdapter(ThemedActivity activity) { super(activity); this.activity = activity; this.size = 0; this.limit = true; setHasStableIds(true); } @SuppressLint("NotifyDataSetChanged") public void setCategory(Category category, boolean animate) { if (this.category != category) { if (listener != null) { this.category.removeCategoryItemListener(listener); } if (animate) { size = 0; limit = true; if (this.category != null && this.category.getSize() > 0) { notifyItemRangeRemoved(0, this.category.getSize() - 1); } this.category = category; // Fake a loading delay not to freeze the UI when inflating all views int loop = getMaxSize(); if (loop > 0) { UiUtils.runOnUIThreadDelayed(this::removeLimit, loop * BumpRecyclerViewAdapter.DELAY * 4); while (loop > 0) { UiUtils.runOnUIThreadDelayed(this::bump, loop * BumpRecyclerViewAdapter.DELAY * 4); loop--; } } } else { limit = false; this.category = category; notifyDataSetChanged(); } listener = new Category.CategoryItemListener() { int preparedRemovalIndex = -1; boolean skipInsertion = false; @Override public void onPrepareInsertion(LauncherApplication application) { if (category.getSize() >= HARD_LIMIT) { skipInsertion = true; } } @Override public void onInserted(LauncherApplication application) { if (!skipInsertion) { int index = category.indexOf(application); if (index >= 0 && index < HARD_LIMIT) { notifyItemInserted(index); } } skipInsertion = false; } @Override public void onPrepareRemoval(LauncherApplication application) { preparedRemovalIndex = category.indexOf(application); } @Override public void onRemoved(LauncherApplication application) { if (preparedRemovalIndex >= 0 && preparedRemovalIndex < HARD_LIMIT) { notifyItemRemoved(preparedRemovalIndex); preparedRemovalIndex = -1; } else { notifyDataSetChanged(); } } @Override public void onUpdated(LauncherApplication application) { notifyDataSetChanged(); } }; category.addCategoryItemListener(listener); } } protected class ViewHolder extends AsyncViewHolder { private AdaptiveIconView icon; @Override protected void onInflated() { itemView.setHapticFeedbackEnabled(false); icon = itemView.findViewById(R.id.icon); } } @Override protected int getLayout() { return R.layout.folder_item; } @Override protected void onBind(@NonNull ViewHolder holder, int position) { if (position < category.getSize()) { LauncherApplication application = category.get(position); if (application != LauncherApplication.FALLBACK_APP) { Drawable appIcon = application.getIcon(); if (position >= SOFT_LIMIT && category.getSize() > HARD_LIMIT) { holder.itemView.setOnClickListener((view) -> { View folder = (View) holder.itemView.getParent(); while (!(folder.getParent() instanceof RecyclerView)) { folder = (View) folder.getParent(); } folder.callOnClick(); }); } else { holder.itemView.setOnClickListener(view -> application.launch(activity, holder.icon)); } if (appIcon != null) { holder.icon.setIcon(appIcon); } } } else { holder.icon.setIcon(null); holder.itemView.setOnClickListener(null); } holder.itemView.requestLayout(); } @Override public long getItemId(int position) { LauncherApplication application = category.get(position); if (application != null) { return application.hashCode(); } else { return RecyclerView.NO_ID; } } @Override public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) { if (category != null && listener != null) { category.removeCategoryItemListener(listener); } } @Override protected Supplier<ViewHolder> getHolderSupplier() { return ViewHolder::new; } @Override public int getItemCount() { return limit ? size : getMaxSize(); } private int getMaxSize() { return category != null ? Math.min(category.getSize(), HARD_LIMIT) : 0; } public boolean isCapped() { return category.getSize() > HARD_LIMIT; } @Override public void bump() { if (limit) { notifyItemInserted(++size - 1); } } @Override public void removeLimit() { limit = false; int inserted = getMaxSize() - size; notifyItemRangeInserted(getItemCount() - inserted, inserted); } }
7,859
Java
.java
195
28.323077
97
0.585731
albu-razvan/Stario
15
1
4
GPL-3.0
9/4/2024, 8:32:56 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,859
3,166,514
ForEachTest.java
cloudeecn_fiscevm/fiscevm-runtime/src/main/java/EXCLUDE/fisce/test/ForEachTest.java
/* 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 EXCLUDE.fisce.test; import fisce.util.SimpleList; /** * @author Cloudee * */ public class ForEachTest extends TestService { /** * @param args */ public static void main(String[] args) { SimpleList<Integer> sl = new SimpleList<Integer>(); int[] input = { 1, 2, 5, 6, 0x7f7f7f7f, 5 }; for (int in : input) { sl.add(in); } int i = 0; for (int in : sl) { if (input[i] != in || input[i] != sl.get(i)) { RuntimeException e = new RuntimeException(i + " " + in + " " + input[i] + " " + sl.get(i)); e.printStackTrace(); fail("for each"); } i++; } } }
1,452
Java
.java
43
30.046512
76
0.673557
cloudeecn/fiscevm
4
1
0
LGPL-3.0
9/4/2024, 11:02:28 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,452
4,533,006
PnEvaluatedZipCodeEvent.java
pagopa_pn-model/src/main/java/it/pagopa/pn/api/dto/events/PnEvaluatedZipCodeEvent.java
package it.pagopa.pn.api.dto.events; import lombok.*; @Builder @Getter @EqualsAndHashCode @ToString public class PnEvaluatedZipCodeEvent implements GenericEventBridgeEvent<PnAttachmentsConfigEventPayload> { private PnAttachmentsConfigEventPayload detail; }
262
Java
.java
9
27.555556
106
0.876984
pagopa/pn-model
2
1
1
EUPL-1.2
9/5/2024, 12:16:15 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
262
2,985,050
TigLibraryController.java
Bierheng_hengmall/service-user/src/main/java/com/hengmall/user/controller/TigLibraryController.java
package com.hengmall.user.controller; import java.util.List; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.hengmall.user.model.api.Ajax; import com.hengmall.user.model.tigLibrary.TigLibraryAddReq; import com.hengmall.user.model.tigLibrary.TigLibraryDelReq; import com.hengmall.user.model.tigLibrary.TigLibraryRes; import com.hengmall.user.service.TigLibraryService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * 标签库管理NEW Controller * @author Administrator * */ @Api(value = "标签库", description = "标签库") @RestController public class TigLibraryController { final static Logger log= LoggerFactory.getLogger(TigLibraryController.class); @Autowired private TigLibraryService tigLibraryService; @RequestMapping(value = "/tigLibrary/tigLibraryList",method = RequestMethod.POST) @ApiOperation(value = "标签库列表" ,response = TigLibraryRes.class) public Ajax<List<TigLibraryRes>> tigLibraryList()throws Exception{ log.info("客户端请求数据【/productClassify/classifyList】,{}" ); Ajax<List<TigLibraryRes>> ajax = new Ajax<>(); try { List<TigLibraryRes> tigLibraryList = tigLibraryService.tigLibraryList(); ajax.setCode(0); ajax.setData(tigLibraryList); return ajax; } catch (Exception e) { e.printStackTrace(); ajax.setCode(-1); ajax.setErrMsg("获取标签库列表失败!"); return ajax; } } @RequestMapping(value = "/tigLibrary/recache",method = RequestMethod.POST) @ApiOperation(value = "标签库列表" ,response = TigLibraryRes.class) public Ajax<?> recache()throws Exception{ log.info("客户端请求数据【/productClassify/classifyList】,{}" ); Ajax<List<TigLibraryRes>> ajax = new Ajax<>(); try { List<TigLibraryRes> tigLibraryList = tigLibraryService.tigLibraryList(); ajax.setCode(0); ajax.setData(tigLibraryList); return ajax; } catch (Exception e) { e.printStackTrace(); ajax.setCode(-1); ajax.setErrMsg("获取标签库列表失败!"); return ajax; } } @RequestMapping(value = "/tigLibrary/tigLibrarySave",method = RequestMethod.POST) @ApiOperation(value = "标签库添加、修改" ,response = Ajax.class) public Ajax<Object> tigLibraryAdd(@RequestBody @Valid TigLibraryAddReq tigLibraryAddReq,BindingResult result)throws Exception{ log.info("客户端请求数据【/tigLibrary/tigLibraryAdd】,{}" ); Ajax<Object> ajax = new Ajax<>(); try { if(result.hasErrors()) { StringBuffer sb = new StringBuffer(); List<ObjectError> errorList = result.getAllErrors(); for(ObjectError error : errorList){ sb.append(error.getDefaultMessage() + "!"); } ajax.setCode(-1); ajax.setErrMsg(sb.toString()); }else{ int id = tigLibraryService.tigLibraryAdd(tigLibraryAddReq); ajax.setData(id); ajax.setCode(0); } return ajax; } catch (Exception e) { e.printStackTrace(); ajax.setCode(-1); ajax.setErrMsg("标签库添加、修改失败"); return ajax; } } @RequestMapping(value = "/tigLibrary/tigLibraryDel",method = RequestMethod.POST) @ApiOperation(value = "标签库删除" ,response = Ajax.class) public Ajax<Object> tigLibraryDel(@RequestBody @Valid TigLibraryDelReq tigLibraryDelReq,BindingResult result)throws Exception{ log.info("客户端请求数据【/tigLibrary/tigLibraryDel】,{}" ); Ajax<Object> ajax = new Ajax<>(); try { if(result.hasErrors()) { StringBuffer sb = new StringBuffer(); List<ObjectError> errorList = result.getAllErrors(); for(ObjectError error : errorList){ sb.append(error.getDefaultMessage() + "!"); } ajax.setCode(-1); ajax.setErrMsg(sb.toString()); }else{ tigLibraryService.tigLibraryDel(tigLibraryDelReq); } ajax.setCode(0); return ajax; } catch (Exception e) { e.printStackTrace(); ajax.setCode(-1); ajax.setErrMsg(e.getMessage()); return ajax; } } }
4,629
Java
.java
118
32.288136
130
0.714818
Bierheng/hengmall
5
3
0
AGPL-3.0
9/4/2024, 10:40:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,429
1,952,132
DataObjectReference.java
ProgrammeVitam_sedatools/sedalib/src/main/java/fr/gouv/vitam/tools/sedalib/metadata/content/DataObjectReference.java
/** * Copyright French Prime minister Office/DINSIC/Vitam Program (2015-2019) * <p> * contact.vitam@programmevitam.fr * <p> * This software is developed as a validation helper tool, for constructing Submission Information Packages (archives * sets) in the Vitam program whose purpose is to implement a digital archiving back-office system managing high * volumetry securely and efficiently. * <p> * This software is governed by the CeCILL 2.1 license under French law and abiding by the rules of distribution of free * software. You can use, modify and/ or redistribute the software under the terms of the CeCILL 2.1 license as * circulated by CEA, CNRS and INRIA archiveDeliveryRequestReply the following URL "http://www.cecill.info". * <p> * As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, * users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the * successive licensors have only limited liability. * <p> * In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or * developing or reproducing the software by the user in light of its specific status of free software, that may mean * that it is complicated to manipulate, and that also therefore means that it is reserved for developers and * experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the * software's suitability as regards their requirements in conditions enabling the security of their systems and/or data * to be ensured and, more generally, to use and operate it in the same conditions as regards security. * <p> * The fact that you are presently reading this means that you have had knowledge of the CeCILL 2.1 license and that you * accept its terms. */ package fr.gouv.vitam.tools.sedalib.metadata.content; import fr.gouv.vitam.tools.sedalib.metadata.namedtype.ComplexListMetadataKind; import fr.gouv.vitam.tools.sedalib.metadata.namedtype.ComplexListMetadataMap; import fr.gouv.vitam.tools.sedalib.metadata.namedtype.ComplexListType; import fr.gouv.vitam.tools.sedalib.metadata.namedtype.SIPInternalIDType; import fr.gouv.vitam.tools.sedalib.utils.SEDALibException; import java.util.LinkedHashMap; import java.util.Map; /** * The Class DataObjectReference. * <p> * Class for DataObjectReference metadata. * <p> * Part of RelatedReferenceObject metadata. * <p> * Standard quote: "Référence à un objet-données ou à un groupe d'objets-données interne(s)." */ public class DataObjectReference extends ComplexListType { /** * Init metadata map. */ @ComplexListMetadataMap public static final Map<String, ComplexListMetadataKind> metadataMap; static { metadataMap = new LinkedHashMap<>(); metadataMap.put("DataObjectReferenceId", new ComplexListMetadataKind(SIPInternalIDType.class, false)); metadataMap.put("DataObjectGroupReferenceId", new ComplexListMetadataKind(SIPInternalIDType.class, false)); } /** * Instantiates a new reference to SIP internal object type. */ public DataObjectReference() { super("DataObjectReference"); } /** * Instantiates a new referenced to SIP internal object type with DataObjectReferenceId and DataObjectGroupReferenceId.. * If one field is null, it's omitted. * * @param dataObjectReferenceId the data object reference id * @param dataObjectGroupReferenceId the data object group reference id * @throws SEDALibException the seda lib exception */ public DataObjectReference(String dataObjectReferenceId, String dataObjectGroupReferenceId) throws SEDALibException { this(); if (dataObjectReferenceId!=null) addNewMetadata("DataObjectReferenceId", dataObjectReferenceId); if (dataObjectGroupReferenceId!=null) addNewMetadata("DataObjectGroupReferenceId", dataObjectGroupReferenceId); } }
4,058
Java
.java
77
48.753247
124
0.774389
ProgrammeVitam/sedatools
11
9
14
CECILL-2.1
9/4/2024, 8:24:31 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,052
4,575,998
DefaultSplitApkSourceMetaResolver.java
roshdev32_Installer-APK/app/src/main/java/com/installer/apkinstaller/installerx/resolver/meta/impl/DefaultSplitApkSourceMetaResolver.java
package com.installer.apkinstaller.installerx.resolver.meta.impl; import android.content.Context; import android.util.Log; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import installer.apk.xapk.apkinstaller.R; import com.installer.apkinstaller.installerx.common.Category; import com.installer.apkinstaller.installerx.common.MutableSplitPart; import com.installer.apkinstaller.installerx.common.ParserContext; import com.installer.apkinstaller.installerx.common.SplitApkSourceMeta; import com.installer.apkinstaller.installerx.postprocessing.Postprocessor; import com.installer.apkinstaller.installerx.resolver.appmeta.AppMeta; import com.installer.apkinstaller.installerx.resolver.appmeta.AppMetaExtractor; import com.installer.apkinstaller.installerx.resolver.meta.ApkSourceFile; import com.installer.apkinstaller.installerx.resolver.meta.ApkSourceMetaResolutionError; import com.installer.apkinstaller.installerx.resolver.meta.ApkSourceMetaResolutionResult; import com.installer.apkinstaller.installerx.resolver.meta.Notice; import com.installer.apkinstaller.installerx.resolver.meta.SplitApkSourceMetaResolver; import com.installer.apkinstaller.installerx.splitmeta.BaseSplitMeta; import com.installer.apkinstaller.installerx.splitmeta.FeatureSplitMeta; import com.installer.apkinstaller.installerx.splitmeta.SplitMeta; import com.installer.apkinstaller.installerx.splitmeta.config.AbiConfigSplitMeta; import com.installer.apkinstaller.installerx.splitmeta.config.LocaleConfigSplitMeta; import com.installer.apkinstaller.installerx.splitmeta.config.ScreenDestinyConfigSplitMeta; import com.installer.apkinstaller.installerx.util.AndroidBinXmlParser; import com.installer.apkinstaller.utils.IOUtils; import com.installer.apkinstaller.utils.Stopwatch; import com.installer.apkinstaller.utils.Utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class DefaultSplitApkSourceMetaResolver implements SplitApkSourceMetaResolver { private static final String TAG = "DSASMetaResolver"; private static final String MANIFEST_FILE = "AndroidManifest.xml"; public static final String NOTICE_TYPE_NO_XAPK_OBB_SUPPORT = "Notice.DefaultSplitApkSourceMetaResolver.NoXApkObbSupport"; private Context mContext; private AppMetaExtractor mAppMetaExtractor; private List<Postprocessor> mPostprocessors = new ArrayList<>(); public DefaultSplitApkSourceMetaResolver(Context context, AppMetaExtractor appMetaExtractor) { mContext = context.getApplicationContext(); mAppMetaExtractor = appMetaExtractor; } public void addPostprocessor(Postprocessor postprocessor) { mPostprocessors.add(postprocessor); } @Override public ApkSourceMetaResolutionResult resolveFor(ApkSourceFile apkSourceFile) throws Exception { Stopwatch sw = new Stopwatch(); try { ApkSourceMetaResolutionResult result = parseViaParsingManifests(apkSourceFile); Log.d(TAG, String.format("Resolved meta for %s via parsing manifests in %d ms.", apkSourceFile.getName(), sw.millisSinceStart())); return result; } catch (Exception e) { //TODO alt parse throw e; } } private ApkSourceMetaResolutionResult parseViaParsingManifests(ApkSourceFile aApkSourceFile) throws Exception { try (ApkSourceFile apkSourceFile = aApkSourceFile) { String packageName = null; String versionName = null; Long versionCode = null; boolean seenApk = false; boolean seenBaseApk = false; boolean seenObb = false; ParserContext parserContext = new ParserContext(); ApkSourceFile.Entry baseApkEntry = null; for (ApkSourceFile.Entry entry : apkSourceFile.listEntries()) { if (!entry.getName().toLowerCase().endsWith(".apk")) { if ("xapk".equals(Utils.getExtension(apkSourceFile.getName())) && entry.getName().toLowerCase().endsWith(".obb") && !seenObb) { seenObb = true; parserContext.addNotice(new Notice(NOTICE_TYPE_NO_XAPK_OBB_SUPPORT, null, getString(R.string.installerx_notice_xapk))); } continue; } seenApk = true; boolean seenManifestElement = false; HashMap<String, String> manifestAttrs = new HashMap<>(); ByteBuffer manifestBytes = stealManifestFromApk(apkSourceFile.openEntryInputStream(entry)); if (manifestBytes == null) return createErrorResult(R.string.installerx_dsas_meta_resolver_error_no_manifest, true); AndroidBinXmlParser parser = new AndroidBinXmlParser(manifestBytes); int eventType = parser.getEventType(); while (eventType != AndroidBinXmlParser.EVENT_END_DOCUMENT) { if (eventType == AndroidBinXmlParser.EVENT_START_ELEMENT) { if (parser.getName().equals("manifest") && parser.getDepth() == 1 && parser.getNamespace().isEmpty()) { if (seenManifestElement) return createErrorResult(R.string.installerx_dsas_meta_resolver_error_dup_manifest_entry, true); seenManifestElement = true; for (int i = 0; i < parser.getAttributeCount(); i++) { if (parser.getAttributeName(i).isEmpty()) continue; String namespace = "" + (parser.getAttributeNamespace(i).isEmpty() ? "" : (parser.getAttributeNamespace(i) + ":")); manifestAttrs.put(namespace + parser.getAttributeName(i), parser.getAttributeStringValue(i)); } } } eventType = parser.next(); } if (!seenManifestElement) return createErrorResult(R.string.installerx_dsas_meta_resolver_error_no_manifest_entry, true); SplitMeta splitMeta = SplitMeta.from(manifestAttrs); if (packageName == null) { packageName = splitMeta.packageName(); } else { if (!packageName.equals(splitMeta.packageName())) return createErrorResult(R.string.installerx_dsas_meta_resolver_error_pkg_mismatch, true); } if (versionCode == null) { versionCode = splitMeta.versionCode(); } else { if (!versionCode.equals(splitMeta.versionCode())) return createErrorResult(R.string.installerx_dsas_meta_resolver_error_version_mismatch, true); } if (splitMeta instanceof BaseSplitMeta) { if (seenBaseApk) return createErrorResult(R.string.installerx_dsas_meta_resolver_error_multiple_base_apks, true); seenBaseApk = true; baseApkEntry = entry; BaseSplitMeta baseSplitMeta = (BaseSplitMeta) splitMeta; versionName = baseSplitMeta.versionName(); parserContext.getOrCreateCategory(Category.BASE_APK, getString(R.string.installerx_category_base_apk), null) .addPart(new MutableSplitPart(splitMeta, entry.getName(), entry.getLocalPath(), baseSplitMeta.packageName(), entry.getSize(), Utils.formatSize(mContext, entry.getSize()), true, true)); continue; } if (splitMeta instanceof FeatureSplitMeta) { FeatureSplitMeta featureSplitMeta = (FeatureSplitMeta) splitMeta; parserContext.getOrCreateCategory(Category.FEATURE, getString(R.string.installerx_category_dynamic_features), null) .addPart(new MutableSplitPart(splitMeta, entry.getName(), entry.getLocalPath(), getString(R.string.installerx_dynamic_feature, featureSplitMeta.module()), entry.getSize(), Utils.formatSize(mContext, entry.getSize()), false, true)); continue; } if (splitMeta instanceof AbiConfigSplitMeta) { AbiConfigSplitMeta abiConfigSplitMeta = (AbiConfigSplitMeta) splitMeta; String name; if (abiConfigSplitMeta.isForModule()) { name = getString(R.string.installerx_split_config_abi_for_module, abiConfigSplitMeta.abi(), abiConfigSplitMeta.module()); } else { name = getString(R.string.installerx_split_config_abi_for_base, abiConfigSplitMeta.abi()); } parserContext.getOrCreateCategory(Category.CONFIG_ABI, getString(R.string.installerx_category_config_abi), null) .addPart(new MutableSplitPart(splitMeta, entry.getName(), entry.getLocalPath(), name, entry.getSize(), Utils.formatSize(mContext, entry.getSize()), false, false)); continue; } if (splitMeta instanceof LocaleConfigSplitMeta) { LocaleConfigSplitMeta localeConfigSplitMeta = (LocaleConfigSplitMeta) splitMeta; String name; if (localeConfigSplitMeta.isForModule()) { name = getString(R.string.installerx_split_config_locale_for_module, localeConfigSplitMeta.locale().getDisplayName(), localeConfigSplitMeta.module()); } else { name = getString(R.string.installerx_split_config_locale_for_base, localeConfigSplitMeta.locale().getDisplayName()); } parserContext.getOrCreateCategory(Category.CONFIG_LOCALE, getString(R.string.installerx_category_config_locale), null) .addPart(new MutableSplitPart(splitMeta, entry.getName(), entry.getLocalPath(), name, entry.getSize(), Utils.formatSize(mContext, entry.getSize()), false, false)); continue; } if (splitMeta instanceof ScreenDestinyConfigSplitMeta) { ScreenDestinyConfigSplitMeta screenDestinyConfigSplitMeta = (ScreenDestinyConfigSplitMeta) splitMeta; String name; if (screenDestinyConfigSplitMeta.isForModule()) { name = getString(R.string.installerx_split_config_dpi_for_module, screenDestinyConfigSplitMeta.densityName(), screenDestinyConfigSplitMeta.density(), screenDestinyConfigSplitMeta.module()); } else { name = getString(R.string.installerx_split_config_dpi_for_base, screenDestinyConfigSplitMeta.densityName(), screenDestinyConfigSplitMeta.density()); } parserContext.getOrCreateCategory(Category.CONFIG_DENSITY, getString(R.string.installerx_category_config_dpi), null) .addPart(new MutableSplitPart(splitMeta, entry.getName(), entry.getLocalPath(), name, entry.getSize(), Utils.formatSize(mContext, entry.getSize()), false, false)); continue; } parserContext.getOrCreateCategory(Category.UNKNOWN, getString(R.string.installerx_category_unknown), null) .addPart(new MutableSplitPart(splitMeta, entry.getName(), entry.getLocalPath(), splitMeta.splitName(), entry.getSize(), Utils.formatSize(mContext, entry.getSize()), false, true)); } if (!seenApk) return createErrorResult(R.string.installerx_dsas_meta_resolver_error_no_apks, true); if (!seenBaseApk) return createErrorResult(R.string.installerx_dsas_meta_resolver_error_no_base_apk, true); AppMeta appMeta = mAppMetaExtractor.extract(apkSourceFile, baseApkEntry); if (appMeta == null) appMeta = new AppMeta(); appMeta.packageName = packageName; appMeta.versionCode = versionCode; if (versionName != null) appMeta.versionName = versionName; parserContext.setAppMeta(appMeta); for (Postprocessor postprocessor : mPostprocessors) postprocessor.process(parserContext); return ApkSourceMetaResolutionResult.success(new SplitApkSourceMeta(parserContext.getAppMeta(), parserContext.sealCategories(), Collections.emptyList(), parserContext.getNotices())); } } private ApkSourceMetaResolutionResult createErrorResult(@StringRes int message, boolean shouldTryToInstallAnyway) { return ApkSourceMetaResolutionResult.failure(new ApkSourceMetaResolutionError(getString(message), shouldTryToInstallAnyway)); } private String getString(@StringRes int id) { return mContext.getString(id); } private String getString(@StringRes int id, Object... formatArgs) { return mContext.getString(id, formatArgs); } @Nullable private ByteBuffer stealManifestFromApk(InputStream apkInputSteam) throws IOException { try (ZipInputStream zipInputStream = new ZipInputStream(apkInputSteam)) { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { if (!zipEntry.getName().equals(MANIFEST_FILE)) { zipInputStream.closeEntry(); continue; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyStream(zipInputStream, buffer); return ByteBuffer.wrap(buffer.toByteArray()); } } return null; } }
14,236
Java
.java
222
49.761261
259
0.659855
roshdev32/Installer-APK
2
0
0
GPL-3.0
9/5/2024, 12:18:11 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,236
4,190,289
RtYou.java
yusufbulentavci_rom-platform-oldy/src/main/java/com/bilgidoku/rom/web/sessionfuncs/rtcmds/RtYou.java
package com.bilgidoku.rom.web.sessionfuncs.rtcmds; public class RtYou extends RtCommon{ public RtYou(String cid){ super("*rt.you", "", null); this.jo.safePut("cid", cid); this.jo.safePut("time", System.currentTimeMillis()); } }
243
Java
.java
8
27.5
54
0.732456
yusufbulentavci/rom-platform-oldy
2
0
8
GPL-3.0
9/5/2024, 12:05:35 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
243
41,598
Tenant.java
jishenghua_jshERP/jshERP-boot/src/main/java/com/jsh/erp/datasource/entities/Tenant.java
package com.jsh.erp.datasource.entities; import java.util.Date; public class Tenant { private Long id; private Long tenantId; private String loginName; private Integer userNumLimit; private String type; private Boolean enabled; private Date createTime; private Date expireTime; private String remark; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getTenantId() { return tenantId; } public void setTenantId(Long tenantId) { this.tenantId = tenantId; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName == null ? null : loginName.trim(); } public Integer getUserNumLimit() { return userNumLimit; } public void setUserNumLimit(Integer userNumLimit) { this.userNumLimit = userNumLimit; } public String getType() { return type; } public void setType(String type) { this.type = type == null ? null : type.trim(); } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getExpireTime() { return expireTime; } public void setExpireTime(Date expireTime) { this.expireTime = expireTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } }
1,886
Java
.java
67
20.507463
70
0.620748
jishenghua/jshERP
3,145
1,149
66
GPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
true
true
true
false
true
true
true
false
1,886
856,275
ChunkGetterMode.java
LambdAurora_LambdaMap/src/main/java/dev/lambdaurora/lambdamap/map/ChunkGetterMode.java
/* * Copyright (c) 2021-2022 LambdAurora <email@lambdaurora.dev> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lambdaurora.lambdamap.map; import org.jetbrains.annotations.Nullable; /** * Represents a chunk getter mode. * * @author LambdAurora * @version 1.0.0 * @since 1.0.0 */ public enum ChunkGetterMode { /** * Gets the chunk from memory. */ GET(WorldMap::getChunk), /** * Gets the chunk from memory, or if absent loads the chunk from disk. */ LOAD(WorldMap::getChunkOrLoad), /** * Gets or loads the chunk, if absent creates a new empty chunk. */ CREATE(WorldMap::getChunkOrCreate); private final ChunkFactory factory; ChunkGetterMode(ChunkFactory factory) { this.factory = factory; } public @Nullable MapChunk getChunk(WorldMap map, int x, int z) { return this.factory.getChunk(map, x, z); } @FunctionalInterface public interface ChunkFactory { @Nullable MapChunk getChunk(WorldMap map, int x, int z); } }
1,596
Java
.java
50
29.72
78
0.751787
LambdAurora/LambdaMap
72
16
9
LGPL-3.0
9/4/2024, 7:09:22 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,596
2,085,373
MessagesConfigSingleManager.java
DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/configurate/manager/MessagesConfigSingleManager.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2024 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.config.configurate.manager; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.configurate.manager.abstraction.TranslatedConfigManager; import com.discordsrv.common.config.configurate.manager.loader.YamlConfigLoaderProvider; import com.discordsrv.common.config.messages.MessagesConfig; import org.spongepowered.configurate.yaml.YamlConfigurationLoader; import java.util.Locale; public class MessagesConfigSingleManager<C extends MessagesConfig> extends TranslatedConfigManager<C, YamlConfigurationLoader> implements YamlConfigLoaderProvider { private final MessagesConfigManager<C> aggregateManager; private final Locale locale; private final boolean multi; protected MessagesConfigSingleManager(DiscordSRV discordSRV, MessagesConfigManager<C> aggregateManager, Locale locale, boolean multi) { super(discordSRV); this.aggregateManager = aggregateManager; this.locale = locale; this.multi = multi; } @Override public String fileName() { if (multi) { return aggregateManager.directory().resolve(locale.getISO3Language() + ".yaml").toString(); } return MessagesConfig.FILE_NAME; } @Override public Locale locale() { return locale; } @Override public C createConfiguration() { return aggregateManager.createConfiguration(); } }
2,275
Java
.java
52
39.25
139
0.765025
DiscordSRV/Ascension
18
5
1
GPL-3.0
9/4/2024, 8:28:58 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,275
4,957,606
PlugUtil.java
informationgrid_ingrid-iplug/src/test/java/de/ingrid/iplug/PlugUtil.java
/* * **************************************************- * ingrid-iplug * ================================================== * Copyright (C) 2014 - 2024 wemove digital solutions GmbH * ================================================== * Licensed under the EUPL, Version 1.2 or – as soon they will be * approved by the European Commission - subsequent versions of the * EUPL (the "Licence"); * * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * https://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * **************************************************# */ /* * Copyright (c) 1997-2005 by media style GmbH * * $Source: /cvs/asp-search/src/java/com/ms/aspsearch/PermissionDeniedException.java,v $ */ package de.ingrid.iplug; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import de.ingrid.utils.PlugDescription; import de.ingrid.utils.xml.XMLSerializer; /** * tool to manipulate plug descriptions. * * created on 09.08.2005 * @author sg * @version $Revision: 1.3 $ */ public class PlugUtil { public static void main(String[] args) throws IOException { File inFile = new File(args[0]); File outFile = new File(args[1]); InputStream resourceAsStream = new FileInputStream(inFile); XMLSerializer serializer = new XMLSerializer(); PlugDescription description = (PlugDescription) serializer .deSerialize(resourceAsStream); description.addField("datatype"); description.addField("topic"); description.addField("partner"); serializer.aliasClass(PlugDescription.class.getName(), PlugDescription.class); serializer.serialize(description, outFile); } }
2,144
Java
.java
57
33.736842
88
0.653199
informationgrid/ingrid-iplug
1
0
0
EUPL-1.2
9/5/2024, 12:37:10 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,144
3,597,175
AbstractMBeanTab.java
TANGO-Project_code-profiler-plugin/bundles/org.jvmmonitor.ui/src/org/jvmmonitor/internal/ui/properties/mbean/AbstractMBeanTab.java
/******************************************************************************* * Copyright (c) 2010-2013 JVM Monitor project. All rights reserved. * * This code is distributed under the terms of the Eclipse Public License v1.0 * which is available at http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.jvmmonitor.internal.ui.properties.mbean; import javax.management.ObjectName; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.part.PageBook; import org.jvmmonitor.internal.ui.properties.AbstractJvmPropertySection; import org.jvmmonitor.ui.Activator; /** * The abstract class for MBean tab. */ abstract public class AbstractMBeanTab extends PageBook { /** The tab item. */ CTabItem tabItem; /** The object name. */ ObjectName objectName; /** The property section. */ AbstractJvmPropertySection section; /** The tab folder. */ private CTabFolder tabFolder; /** The error message page. */ private Composite errorMessagePage; /** The state indicating if invalid input is given. */ private boolean invalidInput; /** The tab image. */ private Image tabImage; /** The label to show message. */ private Label messageLabel; /** * The constructor. * * @param tabFolder * The tab folder * @param section * The property section */ public AbstractMBeanTab(CTabFolder tabFolder, AbstractJvmPropertySection section) { super(tabFolder, SWT.NONE); this.tabFolder = tabFolder; this.section = section; invalidInput = false; createErrorMessagePage(); addTabItem(); } /* * @see Widget#dispose() */ @Override public void dispose() { super.dispose(); if (tabImage != null) { tabImage.dispose(); } } /** * Notifies that selection has been changed. * * @param selection * The selection */ final protected void selectionChanged(StructuredSelection selection) { objectName = getObjectName(selection); if (objectName == null) { return; } invalidInput = false; selectionChanged(); } /** * Refreshes. */ final protected void refresh() { if (invalidInput) { return; } performRefresh(); } /** * Invoked when section is deactivated. */ protected void deactivated() { Job.getJobManager().cancel(toString()); } /** * Adds the tab item. */ void addTabItem() { tabItem = new CTabItem(tabFolder, SWT.NONE); tabItem.setText(getTabText()); tabItem.setImage(getTabImage()); tabItem.setControl(this); } /** * Gets the object name. * * @param selection * The selection * @return The object name */ static ObjectName getObjectName(StructuredSelection selection) { Object element = selection.getFirstElement(); if (element instanceof MBean) { return ((MBean) element).getObjectName(); } return null; } /** * Indicates that the given MBean is not supported. * * @param e * The exception */ void indicateNotSupported(Exception e) { Throwable t = e.getCause(); while (t.getCause() != null) { t = t.getCause(); } final String errorMessage = NLS.bind(Messages.mBeanNotSupportedMessage, t.getLocalizedMessage()); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { messageLabel.setText(errorMessage); showPage(errorMessagePage); } }); invalidInput = true; } /** * Notifies that selection has been changed. */ abstract void selectionChanged(); /** * Performs the refresh for tab specific things. */ abstract void performRefresh(); /** * Gets the tab text. * * @return The tab text */ abstract String getTabText(); /** * Gets the path to tab image. * * @return The path to tab image */ abstract String getTabImagePath(); /** * Creates the error message page. */ private void createErrorMessagePage() { errorMessagePage = new Composite(this, SWT.NONE); errorMessagePage.setLayout(new FillLayout()); errorMessagePage.setBackground(Display.getDefault().getSystemColor( SWT.COLOR_LIST_BACKGROUND)); FormToolkit toolkit = new FormToolkit(Display.getDefault()); messageLabel = toolkit.createLabel(errorMessagePage, ""); //$NON-NLS-1$ } /** * Gets the tab image. * * @return The tab image */ private Image getTabImage() { if (tabImage == null || tabImage.isDisposed()) { tabImage = Activator.getImageDescriptor(getTabImagePath()) .createImage(); } return tabImage; } }
5,709
Java
.java
188
23.68617
81
0.608306
TANGO-Project/code-profiler-plugin
3
1
0
EPL-2.0
9/4/2024, 11:34:47 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
5,709
2,045,500
LoadWorldEvent.java
itsnebulalol_Apollo/src/main/java/net/apolloclient/events/impl/world/LoadWorldEvent.java
/*⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤ Copyright (C) 2020-2021 developed by Icovid and Apollo Development Team This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/. Contact: Icovid#3888 @ https://discord.com ⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤*/ package net.apolloclient.events.impl.world; import net.apolloclient.events.Event; import lombok.Getter; import net.minecraft.client.multiplayer.WorldClient; /** Fired when player world is changed. * @author Icovid | Icovid#3888 * @since 1.0.0 **/ public class LoadWorldEvent extends Event { @Getter private final WorldClient worldClient; /** @param worldClient new world client loaded */ public LoadWorldEvent(WorldClient worldClient) { this.worldClient = worldClient; } }
1,561
Java
.java
28
46.107143
73
0.728571
itsnebulalol/Apollo
12
14
0
AGPL-3.0
9/4/2024, 8:27:28 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,371
3,441,720
TraceCustomized.java
whdc_ieo-beast/src/dr/inference/trace/TraceCustomized.java
/* * Trace.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.inference.trace; /** * Make a new trace calculated from an existing trace in log * * @author Walter Xie */ public class TraceCustomized extends Trace{ public TraceCustomized(String name) { // traceType = TraceFactory.TraceType.DOUBLE; super(name); } public void addValues(Trace<Double> t) { Double r = 1.0; for (Double v : t.values) { Double newV = 2.0 / (1.0 + v * r); super.values.add(newV); } } }
1,459
Java
.java
42
31.309524
87
0.713579
whdc/ieo-beast
3
1
0
LGPL-2.1
9/4/2024, 11:27:52 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,459
788,751
TimingPageNameTest.java
intuit_Tank/api/src/test/java/com/intuit/tank/vm/common/util/TimingPageNameTest.java
/** * Copyright 2011 Intuit Inc. All Rights Reserved */ package com.intuit.tank.vm.common.util; /* * #%L * Intuit Tank Api * %% * Copyright (C) 2011 - 2015 Intuit Inc. * %% * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * #L% */ import com.intuit.tank.test.TestGroups; import org.junit.jupiter.api.Tag; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; /** * TimingPageNameTest * * @author dangleton * */ public class TimingPageNameTest { static Stream<Arguments> data() { return Stream.of( Arguments.of("Page ID:||:Page Name:||:14", "Page ID", "Page Name", 14), Arguments.of("Page ID", "Page ID", "Page ID", null), Arguments.of(":||:Page Name", "Page Name", "Page Name", null), Arguments.of(":||:Page Name:||:15", "Page Name", "Page Name", 15), Arguments.of("Page ID:||:", "Page ID", "Page ID", null), Arguments.of("Page ID:||::||:16", "Page ID", "Page ID", 16), Arguments.of("Old Page", "Old Page", "Old Page", null) ); } @ParameterizedTest @Tag(TestGroups.FUNCTIONAL) @MethodSource("data") public void testParse(String pageIdString, String id, String name, Integer index) { TimingPageName timingPageName = new TimingPageName(pageIdString); assertEquals(timingPageName.getId(), id); assertEquals(timingPageName.getName(), name); assertEquals(timingPageName.getIndex(), index); } }
1,895
Java
.java
51
31.921569
87
0.666667
intuit/Tank
84
61
10
EPL-1.0
9/4/2024, 7:08:56 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,895
2,647,165
ExecutionLeg.java
gporter0205_schwab-api-client/src/main/java/com/pangility/schwab/api/client/accountsandtrading/model/order/ExecutionLeg.java
package com.pangility.schwab.api.client.accountsandtrading.model.order; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.pangility.schwab.api.client.common.deserializers.ZonedDateTimeDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; /** * ExecutionLeg * See the <a href="https://developer.schwab.com">Schwab Developer Portal</a> for more information */ @Getter @Setter @ToString @JsonInclude(JsonInclude.Include.NON_EMPTY) public class ExecutionLeg { private Long legId; private BigDecimal quantity; private BigDecimal mismarkedQuantity; private BigDecimal price; @JsonDeserialize(using = ZonedDateTimeDeserializer.class) private ZonedDateTime time; @JsonIgnore @JsonAnySetter private Map<String, Object> otherFields = new HashMap<>(); }
1,092
Java
.java
32
32.34375
98
0.837121
gporter0205/schwab-api-client
7
1
2
GPL-3.0
9/4/2024, 9:54:33 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,092
1,922,701
TourModeChoiceUtilityFunction.java
kit-ifv_mobitopp/mobitopp/src/main/java/edu/kit/ifv/mobitopp/simulation/tour/TourModeChoiceUtilityFunction.java
package edu.kit.ifv.mobitopp.simulation.tour; import java.util.Map; import java.util.Set; import edu.kit.ifv.mobitopp.simulation.Mode; import edu.kit.ifv.mobitopp.simulation.Person; public interface TourModeChoiceUtilityFunction { Map<Mode,Double> calculateUtilities( Tour tour, Person person, Map<Mode,Double> preferences, Set<Mode> choiceSet ); }
365
Java
.java
13
25.846154
48
0.817919
kit-ifv/mobitopp
16
5
1
GPL-3.0
9/4/2024, 8:23:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
365
3,894,146
RedisTopicPublisher.java
hupengwu_Fox-Edge-Server/fox-edge-server-kernel/fox-edge-server-kernel-system/fox-edge-server-system-common/src/main/java/cn/foxtech/kernel/system/common/redistopic/RedisTopicPublisher.java
package cn.foxtech.kernel.system.common.redistopic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; /** * 发布者 */ @Component public class RedisTopicPublisher { @Autowired protected RedisTemplate redisTemplate; public void sendMessage(String topic, Object message) { this.redisTemplate.convertAndSend(topic, message); } }
477
Java
.java
15
28.466667
62
0.807947
hupengwu/Fox-Edge-Server
3
2
0
GPL-3.0
9/4/2024, 11:47:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
471
4,267,439
RatRunnable.java
waikato-datamining_adams-addons/adams-rats-core/src/main/java/adams/flow/standalone/rats/RatRunnable.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * RatRunnable.java * Copyright (C) 2014-2018 University of Waikato, Hamilton, New Zealand */ package adams.flow.standalone.rats; import adams.core.Utils; import adams.core.logging.LoggingHelper; import adams.flow.core.RatMode; import adams.flow.core.RunnableWithLogging; import adams.flow.core.Token; import adams.flow.standalone.Rat; import adams.flow.standalone.rats.input.PollingRatInput; import java.util.logging.Level; /** * Runnable class for Rat used in a thread. * * @author fracpete (fracpete at waikato dot ac dot nz) */ public class RatRunnable extends RunnableWithLogging { /** for serialization. */ private static final long serialVersionUID = 143445804089303521L; /** the owning Rat. */ protected Rat m_Owner; /** whether we have any actors to apply to the data. */ protected boolean m_HasActors; /** whether the execution has been paused. */ protected boolean m_Paused; /** * Initializes the runnable. * * @param owner the owning actor * @param paused whether to start in paused mode */ public RatRunnable(Rat owner, boolean paused) { super(); m_Owner = owner; m_HasActors = (owner.getActorHandler().active() > 0); m_Paused = paused; } /** * Returns the owning actor. * * @return the owner */ public Rat getOwner() { return m_Owner; } /** * Transmits the data. * * @param data the data to transmit, ignored if null * @return null if successful, otherwise error message */ protected String transmit(Object data) { String result; result = null; if (data != null) { while (!m_Owner.getTransmitter().canInput() && !m_Stopped) Utils.wait(this, this, 100, 100); if (!m_Stopped) { if (isLoggingEnabled()) getLogger().finer("Inputting to " + m_Owner.getTransmitter().getFullName()); m_Owner.getTransmitter().input(data); if (isLoggingEnabled()) getLogger().info("Transmitting to " + m_Owner.getTransmitter().getFullName()); result = m_Owner.getTransmitter().transmit(); if (result != null) getLogger().warning("Failed to transmit to " + m_Owner.getTransmitter().getFullName() + ": " + result); else if (isLoggingEnabled()) getLogger().info("Transmitted to " + m_Owner.getTransmitter().getFullName()); } } return result; } /** * Performs the actual execution. */ @Override protected void doRun() { String result; Object data; Token token; while (!m_Stopped) { if (m_Paused && !m_Stopped) { Utils.wait(this, this, 100, 10); continue; } data = null; if (isLoggingEnabled()) getLogger().info("Receiving from " + m_Owner.getReceiver().getFullName()); if (m_Owner.getReceiver().isStopped()) break; try { result = m_Owner.getReceiver().receive(); } catch (Throwable t) { result = LoggingHelper.throwableToString(t); } if (getOwner().getReceiver().getReceptionInterrupted()) getLogger().warning("Reception interrupted: " + m_Owner.getReceiver().getFullName()); if (m_Stopped) break; if (result != null) { getOwner().log("Failed to receive from " + m_Owner.getReceiver().getFullName() + ": " + result, "receive"); } else { if (isLoggingEnabled()) getLogger().info("Received from " + m_Owner.getReceiver().getFullName()); if (isLoggingEnabled()) getLogger().fine("Pending output from " + m_Owner.getReceiver().getFullName() + ": " + m_Owner.getReceiver().hasPendingOutput()); try { while (m_Owner.getReceiver().hasPendingOutput() && !m_Stopped) { data = m_Owner.getReceiver().output(); if (isLoggingEnabled()) getLogger().finer("Data: " + data); if (m_Stopped) break; // actors? if (m_HasActors) { if (data != null) { // delayed setup? if (m_Owner.getPerformLazySetup() && !m_Owner.hasLazySetupPerformed()) { result = m_Owner.lazySetup(); if (result != null) getOwner().getLogger().log(Level.SEVERE, result); } if (result == null) { m_Owner.getActorHandler().input(new Token(data)); result = m_Owner.getActorHandler().execute(); } if (result == null) { while (m_Owner.getActorHandler().hasPendingOutput() && !m_Stopped) { token = m_Owner.getActorHandler().output(); try { result = transmit(token.getPayload()); } catch (Throwable t) { result = LoggingHelper.throwableToString(t); } if (result != null) { getOwner().queueSendError(data, result); break; } } } else { getOwner().queueFlowError(data, result); } // free up memory? if (m_Owner.getPerformLazySetup() && m_Owner.getWrapUpAfterExecution() && !m_Owner.isBreakpointPresent()) m_Owner.getActorHandler().wrapUp(); } } else { try { result = transmit(data); } catch (Throwable t) { result = LoggingHelper.throwableToString(t); } if (result != null) getOwner().queueSendError(data, result); } } } catch (Throwable t) { result = LoggingHelper.throwableToString(t); getOwner().queueFlowError(data, result); } // log error if (result != null) { if (m_HasActors) getOwner().log("Actors failed to transform/transmit data: " + result, "transform/transmit"); else getOwner().log("Failed to transmit data: " + result, "transmit"); } } // manual mode? if (m_Owner.getMode() == RatMode.MANUAL) break; // wait before next poll? if (!m_Stopped) { if (m_Owner.getReceiver() instanceof PollingRatInput) { Utils.wait(this, this, ((PollingRatInput) m_Owner.getReceiver()).getWaitPoll(), 10); } } } if (m_Stopped) { m_Owner.getReceiver().stopExecution(); m_Owner.getTransmitter().stopExecution(); } else if (m_Owner.getMode() == RatMode.MANUAL) { m_Owner.getReceiver().stopExecution(); m_Owner.wrapUpRunnable(); } } /** * Hook method after the run finished. */ protected void postRun() { super.postRun(); m_Owner.notifyRatStateListeners(); } /** * Pauses the execution. */ public void pauseExecution() { m_Paused = true; } /** * Resumes the execution. */ public void resumeExecution() { m_Paused = false; } /** * Returns whether the execution has been suspended. * * @return true if paused */ public boolean isPaused() { return m_Paused; } /** * Stops the execution. */ @Override public void stopExecution() { super.stopExecution(); m_Owner.getActorHandler().stopExecution(); m_Owner.getReceiver().stopExecution(); m_Owner.getTransmitter().stopExecution(); } }
7,401
Java
.java
249
25.385542
132
0.658657
waikato-datamining/adams-addons
2
3
0
GPL-3.0
9/5/2024, 12:07:24 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,401
2,056,917
GravelCommand.java
qixils_minecraft-crowdcontrol/paper/src/main/java/dev/qixils/crowdcontrol/plugin/paper/commands/GravelCommand.java
package dev.qixils.crowdcontrol.plugin.paper.commands; import dev.qixils.crowdcontrol.plugin.paper.PaperCrowdControlPlugin; import dev.qixils.crowdcontrol.plugin.paper.RegionalCommandSync; import dev.qixils.crowdcontrol.plugin.paper.utils.BlockUtil; import dev.qixils.crowdcontrol.socket.Request; import dev.qixils.crowdcontrol.socket.Response; import lombok.Getter; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.List; @Getter public class GravelCommand extends RegionalCommandSync { private final String effectName = "gravel_hell"; public GravelCommand(PaperCrowdControlPlugin plugin) { super(plugin); } @Override protected Response.@NotNull Builder buildFailure(@NotNull Request request) { return request.buildResponse() .type(Response.ResultType.RETRY) .message("No replaceable blocks nearby"); } @Override protected boolean executeRegionallySync(@NotNull Player player, @NotNull Request request) { List<Location> locations = BlockUtil.BlockFinder.builder() .origin(player.getLocation()) .locationValidator(loc -> !loc.getBlock().isEmpty() && loc.getBlock().getType() != Material.GRAVEL) .shuffleLocations(false) .maxRadius(7) .build().getAll(); if (locations.isEmpty()) return false; for (Location location : locations) { location.getBlock().setType(Material.GRAVEL); } return true; } }
1,449
Java
.java
39
34.717949
102
0.802998
qixils/minecraft-crowdcontrol
17
9
14
MPL-2.0
9/4/2024, 8:28:04 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,449
216,059
AddCloudAccountRequest.java
CloudExplorer-Dev_CloudExplorer-Lite/framework/management-center/backend/src/main/java/com/fit2cloud/controller/request/cloud_account/AddCloudAccountRequest.java
package com.fit2cloud.controller.request.cloud_account; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fit2cloud.autoconfigure.PluginsContextHolder; import com.fit2cloud.common.exception.Fit2cloudException; import com.fit2cloud.common.platform.credential.Credential; import com.fit2cloud.common.provider.IBaseCloudProvider; import com.fit2cloud.common.utils.JsonUtil; import com.fit2cloud.common.validator.annnotaion.CustomValidated; import com.fit2cloud.common.validator.group.ValidationGroup; import com.fit2cloud.common.validator.handler.ExistHandler; import com.fit2cloud.constants.ErrorCodeConstants; import com.fit2cloud.dao.mapper.CloudAccountMapper; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; import lombok.Data; import org.apache.commons.lang.StringUtils; import java.io.IOException; import java.util.Optional; /** * { @Author:张少虎} * { @Date: 2022/9/6 2:14 PM} * { @Version 1.0} * { @注释: } */ @Data @JsonDeserialize(using = AddCloudAccountRequest.Deserializer.class) public class AddCloudAccountRequest { @Schema(title = "云账号名称", description = "云账号名称") @NotNull(message = "云账号名称不能为null") @CustomValidated(groups = ValidationGroup.SAVE.class, mapper = CloudAccountMapper.class, field = "name", handler = ExistHandler.class, message = "{i18n.cloud_account.name.not.repeat}", exist = true) private String name; @Schema(title = "凭证信息", description = "凭证信息") @NotNull(message = "{i18n.cloud_account.credential.is.not.empty}") private Credential credential; @Schema(title = "云平台", description = "云平台") @NotNull(message = "{i18n.cloud_account.platform,is.not.empty}") private String platform; public static class Deserializer extends JsonDeserializer<AddCloudAccountRequest> { @Override public AddCloudAccountRequest deserialize(JsonParser p, DeserializationContext c) throws IOException { JsonNode jsonNode = p.getCodec().readValue(p, JsonNode.class); if (!jsonNode.has("platform")) { throw new Fit2cloudException(ErrorCodeConstants.CLOUD_ACCOUNT_PLATFORM_IS_NOT_NULL.getCode(), ErrorCodeConstants.CLOUD_ACCOUNT_PLATFORM_IS_NOT_NULL.getMessage()); } if (!jsonNode.has("credential")) { throw new Fit2cloudException(ErrorCodeConstants.CLOUD_ACCOUNT_CREDENTIAL_IS_NOT_EMPTY.getCode(), ErrorCodeConstants.CLOUD_ACCOUNT_CREDENTIAL_IS_NOT_EMPTY.getMessage()); } String platform = jsonNode.get("platform").textValue(); Optional<IBaseCloudProvider> first = PluginsContextHolder.getExtensions(IBaseCloudProvider.class).stream() .filter(platformConstants -> StringUtils.equals(platform, platformConstants.getCloudAccountMeta().platform)) .findFirst(); if (first.isEmpty()) { throw new Fit2cloudException(ErrorCodeConstants.CLOUD_ACCOUNT_NOT_SUPPORT_PLATFORM.getCode(), ErrorCodeConstants.CLOUD_ACCOUNT_NOT_SUPPORT_PLATFORM.getMessage()); } AddCloudAccountRequest addCloudAccountRequest = new AddCloudAccountRequest(); try { addCloudAccountRequest.setCredential(JsonUtil.mapper.readValue(jsonNode.get("credential").traverse(), first.get().getCloudAccountMeta().credential)); } catch (Exception e) { throw new Fit2cloudException(ErrorCodeConstants.CLOUD_ACCOUNT_CREDENTIAL_FORM_ERROR.getCode(), ErrorCodeConstants.CLOUD_ACCOUNT_CREDENTIAL_FORM_ERROR.getMessage()); } addCloudAccountRequest.setName(jsonNode.has("name") ? jsonNode.get("name").asText(null) : null); addCloudAccountRequest.setPlatform(platform); return addCloudAccountRequest; } } }
4,107
Java
.java
70
50.942857
202
0.746903
CloudExplorer-Dev/CloudExplorer-Lite
635
87
8
GPL-3.0
9/4/2024, 7:05:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,033
4,074,153
WalletEventListener.java
BWallet_bwallet-server/src/main/java/com/bdx/bwallet/server/core/event/WalletEventListener.java
package com.bdx.bwallet.server.core.event; public interface WalletEventListener { void onEvent(WalletEvent event); }
124
Java
.java
4
28.25
43
0.813559
BWallet/bwallet-server
2
1
1
LGPL-3.0
9/5/2024, 12:01:55 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
124
5,081,990
package-info.java
fantesy84_java-code-tutorials/java-code-tutorials-tools/src/test/java/net/fantesy84/test/util/poi/package-info.java
/** * Project: java-code-tutorials-tools * Created: 2016年7月7日 * ©gopay.com Inc. */ /** * Description: * <P> * @author junjie.ge * @since JDK1.7 */ package net.fantesy84.test.util.poi;
210
Java
.java
12
14.333333
38
0.635417
fantesy84/java-code-tutorials
1
1
0
GPL-2.0
9/5/2024, 12:40:42 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
203
2,159,046
DirectVector2fBuffer.java
vxel_ialon/core/src/main/java/com/rvandoosselaer/blocks/DirectVector2fBuffer.java
package com.rvandoosselaer.blocks; import com.jme3.math.Vector2f; import com.jme3.util.BufferUtils; import java.nio.FloatBuffer; public class DirectVector2fBuffer { private static final int INITIAL_CAPACITY = 1000; private FloatBuffer buff; private int size = 0; public DirectVector2fBuffer() { buff = BufferUtils.createFloatBuffer(INITIAL_CAPACITY * 2); } public DirectVector2fBuffer(int capacity) { buff = BufferUtils.createFloatBuffer(capacity * 2); } public void add(Vector2f v) { if (buff.position() + 2 > buff.capacity()) { increaseCapacity(); } buff.put(v.x).put(v.y); size++; } public FloatBuffer getBuffer() { FloatBuffer newbuffer = BufferUtils.createFloatBuffer(buff.position()); buff.flip(); newbuffer.put(buff); newbuffer.flip(); return newbuffer; } public FloatBuffer getInternalBuffer() { return buff; } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void clear() { buff.clear(); } private void increaseCapacity() { FloatBuffer newbuffer = BufferUtils.createFloatBuffer(buff.capacity() * 2); buff.clear(); newbuffer.put(buff); buff = newbuffer; } }
1,368
Java
.java
47
22.531915
83
0.639633
vxel/ialon
13
3
0
GPL-3.0
9/4/2024, 8:31:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,368
897,860
CharCursor.java
baratine_baratine/web/src/main/java/com/caucho/v5/util/CharCursor.java
/* * Copyright (c) 1998-2015 Caucho Technology -- all rights reserved * * This file is part of Baratine(TM)(TM) * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Baratine 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. * * Baratine 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Baratine; if not, write to the * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.v5.util; import java.text.CharacterIterator; /* The text cursor is purposely lightweight. It does not update with the * text, nor does is allow changes. */ public abstract class CharCursor implements CharacterIterator, CharReader { /** * returns the current location of the cursor */ public abstract int getIndex(); public abstract int getBeginIndex(); public abstract int getEndIndex(); /** * sets the cursor to the position */ public abstract char setIndex(int pos); public abstract char next(); public abstract char previous(); public abstract char current(); public abstract Object clone(); public char first() { return setIndex(getBeginIndex()); } public char last() { return setIndex(getEndIndex()); } /** * our stuff */ public char read() { char value = current(); next(); return value; } public char prev() { int pos = getIndex(); char value = previous(); setIndex(pos); return value; } /** * Skips the next n characters */ public char skip(int n) { for (int i = 0; i < n; i++) next(); return current(); } public void subseq(CharBuffer cb, int begin, int end) { int pos = getIndex(); char ch = setIndex(begin); for (int i = begin; i < end; i++) { if (ch != DONE) cb.append(ch); ch = next(); } setIndex(pos); } public void subseq(CharBuffer cb, int length) { char ch = current(); for (int i = 0; i < length; i++) { if (ch != DONE) cb.append(ch); ch = next(); } } /** * True if the cursor matches the character buffer * * If match fails, return the pointer to its original. */ public boolean regionMatches(char []cb, int offset, int length) { int pos = getIndex(); char ch = current(); for (int i = 0; i < length; i++) { if (cb[i + offset] != ch) { setIndex(pos); return false; } ch = next(); } return true; } /** * True if the cursor matches the character buffer * * If match fails, return the pointer to its original. */ public boolean regionMatchesIgnoreCase(char []cb, int offset, int length) { int pos = getIndex(); char ch = current(); for (int i = 0; i < length; i++) { if (ch == DONE) { setIndex(pos); return false; } if (Character.toLowerCase(cb[i + offset]) != Character.toLowerCase(ch)) { setIndex(pos); return false; } ch = next(); } return true; } }
3,603
Java
.java
142
21.267606
79
0.647076
baratine/baratine
66
13
16
GPL-2.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,603
4,598,527
Jugador.java
storrealbac_USM-INF253/Tarea3/src/tarea3/Jugador.java
package tarea3; import java.util.ArrayList; import java.util.List; public class Jugador extends Personaje { private List<Item> items_aplicados = new ArrayList<Item>(); // Crear un jugador por defecto Jugador(String nombre) { super(); this.setNombre(nombre); this.setDinero(500); this.setHPActual(20); this.setHPTotal(20); this.setDanio(5); this.setDefensa(1); } /** * Ver estado del jugador por la consola * * @return void */ void verEstado() { System.out.println(); System.out.println(" - Estadisticas actuales -"); System.out.println(" Dinero: " + this.getDinero()); System.out.println(" HP: " + this.getHPActual() + "/" + this.getHPTotal()); System.out.println(" DMG: " + this.getDanio()); System.out.println(" Defensa: " + this.getDefensa()); } /** * Ver lista de items por consola * * @return void */ void verItems() { System.out.println(); System.out.println(" - Items adquiridos -"); Integer i = 1; // Numero de item for (Item it : items_aplicados) { System.out.println(i++ + ".-"); System.out.println(" Recuperacion de HP: " + it.getRecuperarHP()); System.out.println(" Aumento de HP Total: " + it.getAumentarHPTotal()); System.out.println(" Aumento de DMG: " + it.getAumentarDanio()); System.out.println(" Aumento de defensa: " + it.getAumentarDefensa()); } } // Todos los getters List<Item> getItemsAplicados() { return this.items_aplicados; } // Todos los setters void agregarItem(Item item) { items_aplicados.add(item); } }
1,783
Java
.java
54
25.888889
86
0.587653
storrealbac/USM-INF253
2
0
0
GPL-3.0
9/5/2024, 12:18:46 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,783
4,089,786
SimpleMeasurementHandler.java
kszbcss_rhq-websphere-plugin/rhq-websphere-agent-plugin/src/main/java/be/fgov/kszbcss/rhq/websphere/support/measurement/SimpleMeasurementHandler.java
/* * RHQ WebSphere Plug-in * Copyright (C) 2012 Crossroads Bank for Social Security * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation, and/or the GNU Lesser * General Public License, version 2.1, also 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 and the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU General Public License * and the GNU Lesser 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 be.fgov.kszbcss.rhq.websphere.support.measurement; import javax.management.JMException; import org.rhq.core.domain.measurement.MeasurementReport; import org.rhq.core.domain.measurement.MeasurementScheduleRequest; import be.fgov.kszbcss.rhq.websphere.process.WebSphereServer; import com.ibm.websphere.management.exception.ConnectorException; public abstract class SimpleMeasurementHandler implements MeasurementHandler { public final void getValue(WebSphereServer server, MeasurementReport report, MeasurementScheduleRequest request) throws InterruptedException, JMException, ConnectorException { Object value = getValue(); if (value != null) { JMXMeasurementDataUtils.addData(report, request, value); } } protected abstract Object getValue() throws InterruptedException, JMException, ConnectorException; }
1,849
Java
.java
37
46.837838
179
0.791343
kszbcss/rhq-websphere-plugin
2
1
10
GPL-2.0
9/5/2024, 12:02:29 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,849
1,921,383
HasId.java
kit-ifv_mobitopp/mobitopp/src/test/java/edu/kit/ifv/mobitopp/publictransport/matcher/connection/HasId.java
package edu.kit.ifv.mobitopp.publictransport.matcher.connection; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import edu.kit.ifv.mobitopp.publictransport.model.Connection; import edu.kit.ifv.mobitopp.publictransport.model.ConnectionId; public class HasId extends TypeSafeMatcher<Connection> { private final ConnectionId id; public HasId(ConnectionId id) { super(); this.id = id; } @Override public void describeTo(Description description) { description.appendText("has id "); description.appendValue(id); } @Override protected boolean matchesSafely(Connection connection) { return id == connection.id(); } @Override protected void describeMismatchSafely(Connection item, Description mismatchDescription) { mismatchDescription.appendText("has id "); mismatchDescription.appendValue(item.id()); } }
858
Java
.java
26
30.615385
90
0.815085
kit-ifv/mobitopp
16
5
1
GPL-3.0
9/4/2024, 8:23:21 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
858
1,384,871
Transaction.java
Archistar_archistar-bft/src/main/java/at/archistar/bft/server/Transaction.java
package at.archistar.bft.server; import java.util.HashSet; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import at.archistar.bft.exceptions.InconsistentResultsException; import at.archistar.bft.messages.AbstractCommand; import at.archistar.bft.messages.ClientCommand; import at.archistar.bft.messages.ClientFragmentCommand; import at.archistar.bft.messages.CommitCommand; import at.archistar.bft.messages.PrepareCommand; import at.archistar.bft.messages.PreprepareCommand; import at.archistar.bft.messages.TransactionResult; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Arrays; import java.util.Objects; /** * This is used to store transaction information for an operation. It contains a * simple state model (INCOMING -> PRECOMMITED, COMMITED, JOURNAL) that actually * mirrors the collection that the transaction is currently in. * * TODO: investigate if there's some memory structure that would allow to store * all transactions within one 'tree' * * @author andy */ public class Transaction implements Comparable<Transaction> { /** those are the possible states a transaction could be in */ public enum State { INCOMING, PREPREPARED, PREPARED, COMMITED }; private State state = State.INCOMING; /** * all exchanged precommit commands, should be replicaCount */ private Set<PrepareCommand> preparedCmds = new HashSet<>(); private Set<CommitCommand> commitedCmds = new HashSet<>(); /** * the expected error model */ private int f = 1; private final Logger logger = LoggerFactory.getLogger(Transaction.class); /** * fragment id */ private String fragmentid; /** * my sequence number (from primary) */ private int sequenceNr; /** * sequence number of previous operation (from primary) */ private int priorSequenceNr; private String clientOperationId; private final ReentrantLock lock = new ReentrantLock(); private boolean executed = false; private boolean primaryReceived = false; private final int replica; private ClientCommand clientCmd = null; private byte[] result = null; private BftEngineCallbacks callbacks = null; /** * output a more readable id for debug output */ public String readableId() { if (clientCmd == null) { return "" + this.replica + "/" + this.sequenceNr + "/?/?"; } else { return "" + this.replica + "/" + this.sequenceNr + "/" + this.clientCmd.getClientId() + "/" + this.clientCmd.getClientSequence(); } } public Transaction(AbstractCommand cmd, int replicaId, int f, BftEngineCallbacks callbacks) { /* default stuff, valid for all commands */ this.f = f; this.replica = replicaId; this.callbacks = callbacks; /* if there's a fragment-id, record it */ if (cmd instanceof ClientFragmentCommand) { this.fragmentid = ((ClientFragmentCommand) cmd).getFragmentId(); } else { this.fragmentid = null; } if (cmd instanceof PreprepareCommand) { PreprepareCommand c = (PreprepareCommand) cmd; this.clientOperationId = c.getClientOperationId(); this.primaryReceived = true; this.priorSequenceNr = c.getPriorSequence(); this.sequenceNr = c.getSequence(); } else if (cmd instanceof PrepareCommand) { PrepareCommand c = (PrepareCommand) cmd; this.clientOperationId = c.getClientOperationId(); this.priorSequenceNr = -1; this.sequenceNr = c.getSequence(); } else if (cmd instanceof ClientCommand) { this.clientCmd = (ClientCommand) cmd; this.clientOperationId = this.clientCmd.getClientOperationId(); } else { assert (false); } } private boolean canAdvanceToPreprepared() { return state == State.INCOMING && clientCmd != null && primaryReceived; } AbstractCommand getClientCommand() { return this.clientCmd; } private boolean canAdvanceToPrepared(int lastCommited) { logger.debug("{}: {} - {} - {}", readableId(), state, preparedCmds.size(), priorSequenceNr == -1 || priorSequenceNr <= lastCommited); if (state == State.PREPREPARED && preparedCmds.size() >= 2 * f) { if (priorSequenceNr == -1 || priorSequenceNr <= lastCommited) { return true; } } return false; } private boolean canAdvanceToCommited() { logger.debug("{}: {} - {}/{} - {}/{} - {}", readableId(), state, preparedCmds.size(), commitedCmds.size(), clientCmd != null, primaryReceived, priorSequenceNr); return state == State.PREPARED && commitedCmds.size() >= (2 * f + 1) && !executed; } public void outputState() { logger.warn("{}: {} - {}/{} - {}/{} - {}", readableId(), state, preparedCmds.size(), commitedCmds.size(), clientCmd != null, primaryReceived, priorSequenceNr); } /** * execute operation and return result */ private byte[] execute() { assert (state == State.PREPARED); state = State.COMMITED; this.executed = true; return callbacks.executeClientCommand(clientCmd); } public String getFragmentId() { return this.fragmentid; } public int getSequenceNr() { return this.sequenceNr; } public int getPriorSequenceNr() { return this.priorSequenceNr; } public void lock() { this.lock.lock(); } public void unlock() { this.lock.unlock(); } public void setDataFromPreprepareCommand(int sequence, int priorSequence) { this.priorSequenceNr = priorSequence; this.sequenceNr = sequence; } public PreprepareCommand createPreprepareCommand() { PreprepareCommand seq = new PreprepareCommand(0, sequenceNr, replica, clientOperationId, priorSequenceNr); if (this.state == State.INCOMING) { this.state = State.PREPREPARED; } else { assert (false); } this.primaryReceived = true; return seq; } @Override public int compareTo(Transaction o) { return sequenceNr - o.getSequenceNr(); } @Override public boolean equals(Object o) { if (o instanceof Transaction) { /* TODO: should we compare the transactions too? */ return ((Transaction)o).sequenceNr == this.sequenceNr; } else { return false; } } @Override public int hashCode() { int hash = 7; hash = 37 * hash + Objects.hashCode(this.state); hash = 37 * hash + Objects.hashCode(this.preparedCmds); hash = 37 * hash + Objects.hashCode(this.commitedCmds); hash = 37 * hash + this.f; hash = 37 * hash + Objects.hashCode(this.fragmentid); hash = 37 * hash + this.sequenceNr; hash = 37 * hash + this.priorSequenceNr; hash = 37 * hash + Objects.hashCode(this.clientOperationId); hash = 37 * hash + (this.executed ? 1 : 0); hash = 37 * hash + (this.primaryReceived ? 1 : 0); hash = 37 * hash + this.replica; hash = 37 * hash + Objects.hashCode(this.clientCmd); hash = 37 * hash + Arrays.hashCode(this.result); return hash; } public boolean tryMarkDelete() { if (state == State.COMMITED && commitedCmds.size() == (3 * f + 1)) { logger.debug("{} advance commited -> to-delete", readableId()); return true; } else { return false; } } public void setPrepreparedReceived() { this.primaryReceived = true; } public void addPrepareCommand(PrepareCommand c) throws InconsistentResultsException { /* verify that the digest matches */ if (this.preparedCmds.size() > 0) { for (PrepareCommand i : preparedCmds) { if (!c.getClientOperationId().equalsIgnoreCase(i.getClientOperationId())) { throw new InconsistentResultsException(); } } } this.preparedCmds.add(c); } public void addCommitCommand(CommitCommand cmd) { this.commitedCmds.add(cmd); } public void addClientCommand(ClientCommand cmd) { this.clientCmd = cmd; if (cmd instanceof ClientFragmentCommand) { this.fragmentid = ((ClientFragmentCommand) cmd).getFragmentId(); } } public Set<PrepareCommand> getPreparedCommands() { return this.preparedCmds; } public Set<CommitCommand> getCommitedCommands() { return this.commitedCmds; } public void setClientOperationId(String clientOperationId) { this.clientOperationId = clientOperationId; } public String getClientOperationId() { return this.clientOperationId; } public void tryAdvanceToPreprepared(boolean primary) { if (canAdvanceToPreprepared()) { logger.debug("{} advance incoming -> (pre-)prepared", readableId()); assert (this.state == State.INCOMING); if (primary) { /* primary can directly jump to prepared */ this.state = State.PREPARED; } else { PrepareCommand cmd = new PrepareCommand(0, sequenceNr, replica, clientOperationId); this.preparedCmds.add(cmd); this.state = State.PREPREPARED; callbacks.sendToReplicas(cmd); } } } public boolean tryAdvanceToPrepared(int lastCommited) { if (canAdvanceToPrepared(lastCommited)) { logger.debug("{} advance prepared -> precommited", replica, readableId()); CommitCommand cmd = new CommitCommand(0, sequenceNr, replica); this.commitedCmds.add(cmd); assert (this.state == State.PREPREPARED); this.state = State.PREPARED; callbacks.sendToReplicas(cmd); return true; } else { return false; } } public boolean tryAdvanceToCommited() { if (canAdvanceToCommited()) { logger.debug("{} advance precommited -> commited", readableId()); result = execute(); this.callbacks.answerClient(new TransactionResult(this.clientCmd, this.replica, result)); return true; } else { return false; } } @SuppressFBWarnings("EI_EXPOSE_REP") public byte[] getResult() { return this.result; } public boolean hasClientInteraction() { return clientCmd != null; } public void reset() { this.state = State.INCOMING; this.preparedCmds.clear(); this.commitedCmds.clear(); this.primaryReceived = false; } public void merge(Transaction tmp) { tmp.lock(); setDataFromPreprepareCommand(tmp.getSequenceNr(), tmp.getPriorSequenceNr()); preparedCmds = tmp.getPreparedCommands(); commitedCmds = tmp.getCommitedCommands(); tmp.unlock(); } }
11,314
Java
.java
295
30.386441
168
0.63589
Archistar/archistar-bft
20
3
0
LGPL-2.1
9/4/2024, 7:47:52 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,314
2,816,534
SdmxStructureBeanImpl.java
epam_sdmxsource/SdmxBeans/src/main/java/org/sdmxsource/sdmx/sdmxbeans/model/beans/base/SdmxStructureBeanImpl.java
/******************************************************************************* * Copyright (c) 2013 Metadata Technology Ltd. * * All rights reserved. This program and the accompanying materials are made * available under the terms of the GNU Lesser General Public License v 3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is part of the SDMX Component Library. * * The SDMX Component Library is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * The SDMX Component Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with The SDMX Component Library If not, see * http://www.gnu.org/licenses/lgpl. * * Contributors: * Metadata Technology - initial API and implementation ******************************************************************************/ package org.sdmxsource.sdmx.sdmxbeans.model.beans.base; import org.sdmxsource.sdmx.api.constants.SDMX_STRUCTURE_TYPE; import org.sdmxsource.sdmx.api.constants.TERTIARY_BOOL; import org.sdmxsource.sdmx.api.model.beans.base.IdentifiableBean; import org.sdmxsource.sdmx.api.model.beans.base.MaintainableBean; import org.sdmxsource.sdmx.api.model.beans.base.SDMXBean; import org.sdmxsource.sdmx.api.model.beans.base.SdmxStructureBean; import org.sdmxsource.sdmx.api.model.mutable.base.MutableBean; import org.sdmxsource.sdmx.util.beans.SDMXBeanUtil; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * The type Sdmx structure bean. */ public abstract class SdmxStructureBeanImpl extends SDMXBeanImpl implements SdmxStructureBean { private static final long serialVersionUID = 1L; /** * The Parent. */ protected SdmxStructureBean parent; /** * The Identifiable composites. */ transient Set<IdentifiableBean> identifiableComposites; /** * Instantiates a new Sdmx structure bean. * * @param structureType the structure type * @param parent the parent */ /////////////////////////////////////////////////////////////////////////////////////////////////// ////////////BUILD FROM ITSELF, CREATES STUB BEAN ////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// protected SdmxStructureBeanImpl(SDMX_STRUCTURE_TYPE structureType, SdmxStructureBean parent) { super(structureType, parent); this.structureType = structureType; this.parent = parent; } /** * Instantiates a new Sdmx structure bean. * * @param bean the bean */ protected SdmxStructureBeanImpl(SdmxStructureBean bean) { super(bean); this.structureType = bean.getStructureType(); this.parent = bean.getParent(); } /** * Instantiates a new Sdmx structure bean. * * @param mutableBean the mutable bean * @param parent the parent */ /////////////////////////////////////////////////////////////////////////////////////////////////// ////////////BUILD FROM MUTABLE BEAN ////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// public SdmxStructureBeanImpl(MutableBean mutableBean, SdmxStructureBean parent) { super(mutableBean, parent); this.parent = parent; } /** * Create tertiary tertiary bool. * * @param isSet the is set * @param value the value * @return the tertiary bool */ protected static TERTIARY_BOOL createTertiary(boolean isSet, boolean value) { return SDMXBeanUtil.createTertiary(isSet, value); } /////////////////////////////////////////////////////////////////////////////////////////////////// ////////////COMPOSITES ////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// @Override protected Set<SDMXBean> getCompositesInternal() { return new HashSet<SDMXBean>(); } @Override public SDMX_STRUCTURE_TYPE getStructureType() { return structureType; } @Override public SdmxStructureBean getParent() { return parent; } @Override public MaintainableBean getMaintainableParent() { if (this instanceof MaintainableBean) { return (MaintainableBean) this; } if (parent instanceof MaintainableBean) { return (MaintainableBean) parent; } return parent.getMaintainableParent(); } @Override public final Set<IdentifiableBean> getIdentifiableComposites() { if (identifiableComposites == null) { identifiableComposites = new HashSet<IdentifiableBean>(); for (SDMXBean currentComposite : getComposites()) { if (currentComposite.getStructureType().isIdentifiable() && !currentComposite.getStructureType().isMaintainable()) { identifiableComposites.add((IdentifiableBean) currentComposite); } } identifiableComposites = Collections.unmodifiableSet(identifiableComposites); } return identifiableComposites; } @Override public IdentifiableBean getIdentifiableParent() { SDMXBean currentParent = getParent(); while (currentParent != null) { if (currentParent.getStructureType().isIdentifiable()) { return (IdentifiableBean) currentParent; } currentParent = currentParent.getParent(); } return null; } }
6,202
Java
.java
150
35.466667
103
0.590721
epam/sdmxsource
6
12
4
LGPL-3.0
9/4/2024, 10:17:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,202
2,395,356
QueryTransaction.java
zowe_ims-operations-api/ims/src/main/java/application/rest/responses/tran/query/QueryTransaction.java
/** * This program and the accompanying materials are made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v20.html * * SPDX-License-Identifier: EPL-2.0 * * Copyright IBM Corporation 2019 */ package application.rest.responses.tran.query; import java.lang.reflect.Field; import io.swagger.v3.oas.annotations.media.Schema; @Schema(description = "POJO from a Query TRAN command that represents output for one transaction") public class QueryTransaction { @Schema(description = "Affinity of the transaction messages on the shared queues, or affinity registration of the transactions for this IMS.") String afin; @Schema(description = "Transaction supports AOI CMD calls (CMD, TRAN, or Y) or not (N). The output value is obtained from the local IMS.") String aocmd; @Schema(description = "Completion code. The completion code indicates whether IMS was able to process the command for the specified resource. The completion code is always returned. ") String cc; @Schema(description = " Completion code text that briefly explains the meaning of the nonzero completion code.") String cctxt; @Schema(description = "Commit mode for the transaction: commit after a single message (SNGL) or multiple messages (MULT). The output value is obtained from the local IMS.") String cmtm; @Schema(description = "Conversation option. Transaction is conversational (Y), or not (N). The output value is obtained from the local IMS.") String conv; @Schema(description = "Conversation ID for transaction that has a conversation in progress.") String convid; @Schema(description = "Perform log write-ahead for recoverable, nonresponse mode input messages and transaction output messages (Y) or not (N). The output value is obtained from the local IMS.") String dclw; @Schema(description = "Definition type") String dfnt; @Schema(description = "Supports MSC directed routing (Y) or not (N). The output value is obtained from the local IMS.") String drrt; @Schema(description = "Input edit routine name.") String edtr; @Schema(description = "Input data is to be translated to uppercase (Y) or not (N). The output value is obtained from the local IMS.") String edtt; @Schema(description = "EMH buffer size. The output value is obtained from the local IMS.") String emhbs; @Schema(description = "Indicates whether the transaction has been exported to the IMSRSC repository. The value can be Y or N.") String expn; @Schema(description = "Transaction expiration time. The output value is obtained from the local IMS.") String exprt; @Schema(description = "Fast Path potential candidate (P), Fast Path exclusive (E), or FP option not enabled (N). The output value is obtained from the local IMS.") String fp; @Schema(description = "Returns the IMSIDs that have the resource defined. The output value is obtained from the repository.") String imsid; @Schema(description = "Inquiry transaction (Y) or not (N). The output value is obtained from the local IMS.") String inq; @Schema(description = "Scheduling class used to determine which message regions can process the transaction locally on a particular IMS.") String lcls; @Schema(description = "Local current scheduling priority. The current scheduling priority is used to calculate which transaction is selected for scheduling.") String lcp; @Schema(description = "Limit count in the local IMS. The limit count is the number that, when compared to the number of input transactions queued and waiting to be processed, determines whether the normal or limit priority value is assigned to this transaction.") String llct; @Schema(description = "Local limit scheduling priority. The limit scheduling priority is the priority to which this transaction is raised when the number of input transactions enqueued and waiting to be processed is equal to or greater than the limit count value.") String llp; @Schema(description = "Local maximum region count. The maximum region count is the maximum number of message processing program (MPP) regions that can be concurrently scheduled to process a transaction that is eligible for parallel scheduling.") String lmrg; @Schema(description = "Local normal scheduling priority. The normal scheduling priority is the priority assigned to this transaction when the number of input transactions enqueued and waiting to be processed is less than the limit count value.") String lnp; @Schema(description = "Local processing limit count. The processing limit count is the number of transaction messages a program can process in a single scheduling.") String lplct; @Schema(description = "Local parallel processing limit count. The parallel limit count is the maximum number of messages that can currently be queued, but not yet processed, by each active message region currently scheduled for this transaction. An additional message region is scheduled whenever the transaction queue count exceeds the PARLIM value multiplied by the number of regions currently scheduled for this transaction.") String lplm; @Schema(description = "Local transaction message queue count.") String lq; @Schema(description = "Local application program output segment limit allowed in message queues for each GU call.") String lsno; @Schema(description = "Local application program output segment size limit allowed in the message queues for each GU call.") String lssz; @Schema(description = "Local transaction status.") String lstt; @Schema(description = "APPC LU name that initiated conversation.") String lu; @Schema(description = "Model name. Name of the resource used as a model to create this resource. DFSDSTR1 is the IMS descriptor name for transactions.") String mdln; @Schema(description = "Model type, either RSC or DESC. RSC means that the resource was created using another resource as a model. DESC means that the resource was created using a descriptor as a model.") String mdlt; @Schema(description = "IMSplex member that built the output line. IMS identifier of IMS that built the output. The IMS identifier is always returned.") String mbr; @Schema(description = "Message type of single segment (SNGLSEG) or multiple segment (MULTSEG). The output value is obtained from the local IMS.") String msgt; @Schema(description = "Logical link path name. The output value is obtained from the local IMS.") String msn; @Schema(description = "Node name that initiated conversation.") String node; @Schema(description = "Processing limit count time.") String plctt; @Schema(description = "PSB name associated with the transaction. The output value is obtained from the local IMS.") String psb; @Schema(description = "Global transaction message queue count on the shared queues. Q is displayed only if shared queues are used.") String qcnt; @Schema(description = "Transaction supports AOI CMD calls (CMD, TRAN, or Y) or not (N). The output value is obtained from the repository.") String raocmd; @Schema(description = " Class value in the repository.") String rcls; @Schema(description = "Commit mode for the transaction: commit after a single message (SNGL) or multiple messages (MULT). The output value is obtained from the repository.") String rcmtm; @Schema(description = "Conversation ID if a conversation is in progress in the repository.") String rconv; @Schema(description = "Recovered during an IMS emergency or normal restart (Y) or not (N). The output value is obtained from the local IMS.") String rcv; @Schema(description = "Perform log write-ahead for recoverable, nonresponse mode input messages and transaction output messages (Y) or not (N). The output value is obtained from the repository.") String rdclw; @Schema(description = "Supports MSC directed routing (Y) or not (N). The output value is obtained from the repository.") String rdrrt; @Schema(description = "Edit routine value obtained from the repository.") String redtr; @Schema(description = "Input data is to be translated to uppercase (Y) or not (N). The output value is obtained from the repository. For the values to be returned, see LEditUC in this table.") String redtt; @Schema(description = "EMH buffer size. The output value is obtained from the repository.") String remhbs; @Schema(description = "Indicates whether the output line contains the stored resource definitions.") String repo; @Schema(description = "Transaction expiration time. The output value is obtained from the repository.") String rexprt; @Schema(description = "Fast Path potential candidate (P), Fast Path exclusive (E), or FP option not enabled (N). The output value is obtained from the repository. For the values to be returned, see the description for LFP in this table.") String rfp; @Schema(description = "Number of regions the transaction is currently scheduled in the local IMS. The output value is obtained from the local IMS.") String rgc; @Schema(description = "Inquiry transaction (Y) or not (N). The output value is obtained from the repository. For the values to be returned, see the description for LInq in this table.") String rinq; @Schema(description = "Limit count value in the repository. The limit count is the number that, when compared to the number of input transactions queued and waiting to be processed, determines whether the normal or limit priority value is assigned to this transaction.") String rlct; @Schema(description = "Local limit scheduling priority value in the repository. The limit scheduling priority is the priority to which this transaction is raised when the number of input transactions enqueued and waiting to be processed is equal to or greater than the limit count value.") String rlp; @Schema(description = "Maximum region count obtained from the repository. The maximum region count is the maximum number of message processing program (MPP) regions that can be concurrently scheduled to process a transaction that is eligible for parallel scheduling.") String rmrg; @Schema(description = "Message type of single segment (SNGLSEG) or multiple segment (MULTSEG). The output value is obtained from the repository. For the values to be returned, see the description for LMsgType in this table.") String rmsgt; @Schema(description = "Remote transaction (Y) or not (N). The output value is obtained from the local IMS.") String rmt; @Schema(description = "Normal scheduling priority value obtained from the repository. The normal scheduling priority is the priority assigned to this transaction when the number of input transactions enqueued and waiting to be processed is less than the limit count value.") String rnp; @Schema(description = "Processing limit count obtained from the repository. The processing limit count is the number of transaction messages a program can process in a single scheduling.") String rplct; @Schema(description = "Processing limit count time value in the repository.") String rplctt; @Schema(description = " Parallel processing limit count obtained from the repository. The parallel limit count is the maximum number of messages that can currently be queued, but not yet processed, by each active message region currently scheduled for this transaction. An additional message region is scheduled whenever the transaction queue count exceeds the PARLIM value multiplied by the number of regions currently scheduled for this transaction.") String rplm; @Schema(description = "PSB name associated with the transaction. The output value is obtained from the repository.") String rpsb; @Schema(description = "Recovered during an IMS emergency or normal restart (Y) or not (N). The output value is obtained from the repository. For the values to be returned, see the description for LRecover in this table.") String rrcv; @Schema(description = "Remote transaction (Y) or not (N). The output value is obtained from the repository. For the values to be returned, see the description for LRemote in this table.") String rrmt; @Schema(description = "Response mode transaction (Y) or not (N). The output value is obtained from the repository. For the values to be returned, see the description for LResp in this table.") String rrsp; @Schema(description = "Transaction is processed serially (Y) or not (N). The output value is obtained from the repository. For the values to be returned, see the description for LSerial in this table.") String rser; @Schema(description = "Local system ID. The output value is obtained from the repository.") String rsidl; @Schema(description = "Remote system ID. The output value is obtained from the repository.") String rsidr; @Schema(description = "Application program output segment limit allowed in message queues for each GU call. The value is obtained from the repository.") String rsno; @Schema(description = "Response mode transaction (Y) or not (N). The output value is obtained from the local IMS.") String rsp; @Schema(description = "Conversational transaction scratchpad area size. The output value is obtained from the repository.") String rspasz; @Schema(description = "Conversational transaction SPA data should be truncated (R) or preserved (S) across a program switch to a transaction that is defined with a smaller SPA. ") String rspatr; @Schema(description = "Application program output segment size limit allowed in the message queues for each GU call. The value is obtained from the repository.") String rsssz; @Schema(description = "Transaction level statistics logged (Y) or not (N). The output value is obtained from the repository. For the values to be returned, see the description for LTranStat in this table.") String rtls; @Schema(description = "Create time from the repository. This is the time the resource was first created in the repository.") String rtmcr; @Schema(description = "Update time from the repository. This is the time the resource was last updated in the repository.") String rtmup; @Schema(description = "Wait-for-input transaction (Y) or not (N). The output value is obtained from the repository. For the values to be returned, see the description for LWFI in this table.") String rwfi; @Schema(description = "Transaction is processed serially (Y) or not (N). The output value is obtained from the local IMS.") String ser; @Schema(description = "Local system ID. The output value is obtained from the local IMS.") String sidl; @Schema(description = "Remote system ID. The output value is obtained from the local IMS.") String sidr; @Schema(description = "Conversational transaction scratchpad area size. The output value is obtained from the local IMS.") String spasz; @Schema(description = "Conversational transaction SPA data should be truncated (R) or preserved (S) across a program switch to a transaction that is defined with a smaller SPA. The output value is obtained from the local IMS.") String spatr; @Schema(description = "Global transaction status") String stt; @Schema(description = "Transaction level statistics logged (Y) or not (N). The output value is obtained from the local IMS.") String tls; @Schema(description = "The time that the resource was last accessed. The output value is obtained from the local IMS.") String tmac; @Schema(description = "The time that the resource was created. The output value is obtained from the local IMS.") String tmcr; @Schema(description = "OTMA tmember that initiated conversation.") String tmem; @Schema(description = "The time that the resource was last imported. The import time is retained across warm start and emergency restart. The output value is obtained from the local IMS.") String tmim; @Schema(description = "The last time the attributes of the runtime resource definition were updated as a result of the UPDATE TRAN, a type-1 command, or the IMPORT command. The update time is retained across warm start and emergency restart. The output value is obtained from the local IMS.") String tmup; @Schema(description = "OTMA tpipe that initiated conversation.") String tpip; @Schema(description = "Transaction name. A transaction defines the processing characteristics of messages destined for an application program.") String tran; @Schema(description = "User that initiated conversation.") String user; @Schema(description = "Wait-for-input transaction (Y) or not (N). The output value is obtained from the local IMS.") String wfi; @Schema(description = "Work is in progress for the transaction or one of its associated resources.") String wrk; public String getAfin() { return afin; } public void setAfin(String afin) { this.afin = afin; } public String getAocmd() { return aocmd; } public void setAocmd(String aocmd) { this.aocmd = aocmd; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public String getCctxt() { return cctxt; } public void setCctxt(String cctxt) { this.cctxt = cctxt; } public String getCmtm() { return cmtm; } public void setCmtm(String cmtm) { this.cmtm = cmtm; } public String getConv() { return conv; } public void setConv(String conv) { this.conv = conv; } public String getConvid() { return convid; } public void setConvid(String convid) { this.convid = convid; } public String getDclw() { return dclw; } public void setDclw(String dclw) { this.dclw = dclw; } public String getDfnt() { return dfnt; } public void setDfnt(String dfnt) { this.dfnt = dfnt; } public String getDrrt() { return drrt; } public void setDrrt(String drrt) { this.drrt = drrt; } public String getEdtr() { return edtr; } public void setEdtr(String edtr) { this.edtr = edtr; } public String getEdtt() { return edtt; } public void setEdtt(String edtt) { this.edtt = edtt; } public String getEmhbs() { return emhbs; } public void setEmhbs(String emhbs) { this.emhbs = emhbs; } public String getExpn() { return expn; } public void setExpn(String expn) { this.expn = expn; } public String getExprt() { return exprt; } public void setExprt(String exprt) { this.exprt = exprt; } public String getFp() { return fp; } public void setFp(String fp) { this.fp = fp; } public String getImsid() { return imsid; } public void setImsid(String imsid) { this.imsid = imsid; } public String getInq() { return inq; } public void setInq(String inq) { this.inq = inq; } public String getLcls() { return lcls; } public void setLcls(String lcls) { this.lcls = lcls; } public String getLcp() { return lcp; } public void setLcp(String lcp) { this.lcp = lcp; } public String getLlct() { return llct; } public void setLlct(String llct) { this.llct = llct; } public String getLlp() { return llp; } public void setLlp(String llp) { this.llp = llp; } public String getLmrg() { return lmrg; } public void setLmrg(String lmrg) { this.lmrg = lmrg; } public String getLnp() { return lnp; } public void setLnp(String lnp) { this.lnp = lnp; } public String getLplct() { return lplct; } public void setLplct(String lplct) { this.lplct = lplct; } public String getLplm() { return lplm; } public void setLplm(String lplm) { this.lplm = lplm; } public String getLq() { return lq; } public void setLq(String lq) { this.lq = lq; } public String getLsno() { return lsno; } public void setLsno(String lsno) { this.lsno = lsno; } public String getLssz() { return lssz; } public void setLssz(String lssz) { this.lssz = lssz; } public String getLstt() { return lstt; } public void setLstt(String lstt) { this.lstt = lstt; } public String getLu() { return lu; } public void setLu(String lu) { this.lu = lu; } public String getMdln() { return mdln; } public void setMdln(String mdln) { this.mdln = mdln; } public String getMdlt() { return mdlt; } public void setMdlt(String mdlt) { this.mdlt = mdlt; } public String getMbr() { return mbr; } public void setMbr(String mbr) { this.mbr = mbr; } public String getMsgt() { return msgt; } public void setMsgt(String msgt) { this.msgt = msgt; } public String getMsn() { return msn; } public void setMsn(String msn) { this.msn = msn; } public String getNode() { return node; } public void setNode(String node) { this.node = node; } public String getPlctt() { return plctt; } public void setPlctt(String plctt) { this.plctt = plctt; } public String getPsb() { return psb; } public void setPsb(String psb) { this.psb = psb; } public String getQcnt() { return qcnt; } public void setQcnt(String qcnt) { this.qcnt = qcnt; } public String getRaocmd() { return raocmd; } public void setRaocmd(String raocmd) { this.raocmd = raocmd; } public String getRcls() { return rcls; } public void setRcls(String rcls) { this.rcls = rcls; } public String getRcmtm() { return rcmtm; } public void setRcmtm(String rcmtm) { this.rcmtm = rcmtm; } public String getRconv() { return rconv; } public void setRconv(String rconv) { this.rconv = rconv; } public String getRcv() { return rcv; } public void setRcv(String rcv) { this.rcv = rcv; } public String getRdclw() { return rdclw; } public void setRdclw(String rdclw) { this.rdclw = rdclw; } public String getRdrrt() { return rdrrt; } public void setRdrrt(String rdrrt) { this.rdrrt = rdrrt; } public String getRedtr() { return redtr; } public void setRedtr(String redtr) { this.redtr = redtr; } public String getRedtt() { return redtt; } public void setRedtt(String redtt) { this.redtt = redtt; } public String getRemhbs() { return remhbs; } public void setRemhbs(String remhbs) { this.remhbs = remhbs; } public String getRepo() { return repo; } public void setRepo(String repo) { this.repo = repo; } public String getRexprt() { return rexprt; } public void setRexprt(String rexprt) { this.rexprt = rexprt; } public String getRfp() { return rfp; } public void setRfp(String rfp) { this.rfp = rfp; } public String getRgc() { return rgc; } public void setRgc(String rgc) { this.rgc = rgc; } public String getRinq() { return rinq; } public void setRinq(String rinq) { this.rinq = rinq; } public String getRlct() { return rlct; } public void setRlct(String rlct) { this.rlct = rlct; } public String getRlp() { return rlp; } public void setRlp(String rlp) { this.rlp = rlp; } public String getRmrg() { return rmrg; } public void setRmrg(String rmrg) { this.rmrg = rmrg; } public String getRmsgt() { return rmsgt; } public void setRmsgt(String rmsgt) { this.rmsgt = rmsgt; } public String getRmt() { return rmt; } public void setRmt(String rmt) { this.rmt = rmt; } public String getRnp() { return rnp; } public void setRnp(String rnp) { this.rnp = rnp; } public String getRplct() { return rplct; } public void setRplct(String rplct) { this.rplct = rplct; } public String getRplctt() { return rplctt; } public void setRplctt(String rplctt) { this.rplctt = rplctt; } public String getRplm() { return rplm; } public void setRplm(String rplm) { this.rplm = rplm; } public String getRpsb() { return rpsb; } public void setRpsb(String rpsb) { this.rpsb = rpsb; } public String getRrcv() { return rrcv; } public void setRrcv(String rrcv) { this.rrcv = rrcv; } public String getRrmt() { return rrmt; } public void setRrmt(String rrmt) { this.rrmt = rrmt; } public String getRrsp() { return rrsp; } public void setRrsp(String rrsp) { this.rrsp = rrsp; } public String getRser() { return rser; } public void setRser(String rser) { this.rser = rser; } public String getRsidl() { return rsidl; } public void setRsidl(String rsidl) { this.rsidl = rsidl; } public String getRsidr() { return rsidr; } public void setRsidr(String rsidr) { this.rsidr = rsidr; } public String getRsno() { return rsno; } public void setRsno(String rsno) { this.rsno = rsno; } public String getRsp() { return rsp; } public void setRsp(String rsp) { this.rsp = rsp; } public String getRspasz() { return rspasz; } public void setRspasz(String rspasz) { this.rspasz = rspasz; } public String getRspatr() { return rspatr; } public void setRspatr(String rspatr) { this.rspatr = rspatr; } public String getRsssz() { return rsssz; } public void setRsssz(String rsssz) { this.rsssz = rsssz; } public String getRtls() { return rtls; } public void setRtls(String rtls) { this.rtls = rtls; } public String getRtmcr() { return rtmcr; } public void setRtmcr(String rtmcr) { this.rtmcr = rtmcr; } public String getRtmup() { return rtmup; } public void setRtmup(String rtmup) { this.rtmup = rtmup; } public String getRwfi() { return rwfi; } public void setRwfi(String rwfi) { this.rwfi = rwfi; } public String getSer() { return ser; } public void setSer(String ser) { this.ser = ser; } public String getSidl() { return sidl; } public void setSidl(String sidl) { this.sidl = sidl; } public String getSidr() { return sidr; } public void setSidr(String sidr) { this.sidr = sidr; } public String getSpasz() { return spasz; } public void setSpasz(String spasz) { this.spasz = spasz; } public String getSpatr() { return spatr; } public void setSpatr(String spatr) { this.spatr = spatr; } public String getStt() { return stt; } public void setStt(String stt) { this.stt = stt; } public String getTls() { return tls; } public void setTls(String tls) { this.tls = tls; } public String getTmac() { return tmac; } public void setTmac(String tmac) { this.tmac = tmac; } public String getTmcr() { return tmcr; } public void setTmcr(String tmcr) { this.tmcr = tmcr; } public String getTmem() { return tmem; } public void setTmem(String tmem) { this.tmem = tmem; } public String getTmim() { return tmim; } public void setTmim(String tmim) { this.tmim = tmim; } public String getTmup() { return tmup; } public void setTmup(String tmup) { this.tmup = tmup; } public String getTpip() { return tpip; } public void setTpip(String tpip) { this.tpip = tpip; } public String getTran() { return tran; } public void setTran(String tran) { this.tran = tran; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getWfi() { return wfi; } public void setWfi(String wfi) { this.wfi = wfi; } public String getWrk() { return wrk; } public void setWrk(String wrk) { this.wrk = wrk; } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty("line.separator"); result.append(newLine); //determine fields declared in this class only (no fields of superclass) Field[] fields = this.getClass().getDeclaredFields(); //print field names paired with their values for ( Field field : fields ) { result.append(" "); try { result.append( field.getName() ); result.append(": "); //requires access to private field: result.append( field.get(this) ); } catch ( IllegalAccessException ex ) { System.out.println(ex); } result.append(newLine); } return result.toString(); } }
27,412
Java
.java
813
31.426814
454
0.751806
zowe/ims-operations-api
8
2
12
EPL-2.0
9/4/2024, 9:19:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27,412
543,177
ItemDioriteDoubleSlabStack.java
AllayMC_Allay/api/src/main/java/org/allaymc/api/item/interfaces/slab/ItemDioriteDoubleSlabStack.java
package org.allaymc.api.item.interfaces.slab; import org.allaymc.api.item.ItemStack; public interface ItemDioriteDoubleSlabStack extends ItemStack { }
153
Java
.java
4
36.75
63
0.863946
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
153
3,916,162
DoagPluginTest.java
McPringle_apus/src/test/java/swiss/fihlon/apus/plugin/event/doag/DoagPluginTest.java
/* * Apus - A social wall for conferences with additional features. * Copyright (C) Marcus Fihlon and the individual contributors to Apus. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package swiss.fihlon.apus.plugin.event.doag; import org.junit.jupiter.api.Test; import swiss.fihlon.apus.event.Language; import swiss.fihlon.apus.event.Room; import swiss.fihlon.apus.event.Session; import swiss.fihlon.apus.event.SessionImportException; import swiss.fihlon.apus.event.Speaker; import swiss.fihlon.apus.configuration.Configuration; import java.time.LocalDateTime; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class DoagPluginTest { @Test void isEnabled() { final var configuration = mock(Configuration.class); final var doagConfig = new DoagConfig(1, ""); when(configuration.getDoag()).thenReturn(doagConfig); final var doagPlugin = new DoagPlugin(configuration); assertTrue(doagPlugin.isEnabled()); } @Test void isDisabled() { final var configuration = mock(Configuration.class); final var doagConfig = new DoagConfig(0, ""); when(configuration.getDoag()).thenReturn(doagConfig); final var doagPlugin = new DoagPlugin(configuration); assertFalse(doagPlugin.isEnabled()); } @Test void getSessions() { final var configuration = mock(Configuration.class); final var doagConfig = new DoagConfig(1, "file:src/test/resources/DOAG.json?eventId=%d"); when(configuration.getDoag()).thenReturn(doagConfig); final var doagPlugin = new DoagPlugin(configuration); final var sessions = doagPlugin.getSessions().toList(); assertEquals(8, sessions.size()); final var sessionIds = sessions.stream().map(Session::id).toList(); for (int counter = 1; counter <= 8; counter++) { final var sessionId = String.format("BBAD:%d", counter); assertTrue(sessionIds.contains(sessionId)); } // full check of session with ID "BBAD:5" final var session = sessions.get(5); assertEquals("BBAD:5", session.id()); assertEquals(LocalDateTime.of(2024, 1, 3, 19, 0), session.startDate()); assertEquals(LocalDateTime.of(2024, 1, 3, 19, 45), session.endDate()); assertEquals(new Room("Room A"), session.room()); assertEquals("Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat", session.title()); assertEquals(2, session.speakers().size()); assertEquals(new Speaker("Saul Goodman"), session.speakers().get(0)); assertEquals(new Speaker("Mike Ehrmantraut"), session.speakers().get(1)); assertEquals(Language.DE, session.language()); } @Test void exceptionWithBrokenTitle() { final var configuration = mock(Configuration.class); final var doagConfig = new DoagConfig(1, "file:src/test/resources/DOAG-broken-title.json?eventId=%d"); when(configuration.getDoag()).thenReturn(doagConfig); final var doagPlugin = new DoagPlugin(configuration); final var exception = assertThrows(SessionImportException.class, doagPlugin::getSessions); assertEquals("Error parsing slot 1: No title with language 'de' or 'en' for session '1'", exception.getMessage()); } @Test void exceptionWithBlankTitle() { final var configuration = mock(Configuration.class); final var doagConfig = new DoagConfig(1, "file:src/test/resources/DOAG-blank-title.json?eventId=%d"); when(configuration.getDoag()).thenReturn(doagConfig); final var doagPlugin = new DoagPlugin(configuration); final var exception = assertThrows(SessionImportException.class, doagPlugin::getSessions); assertEquals("Error parsing slot 1: No title with language 'de' or 'en' for session '1'", exception.getMessage()); } }
4,796
Java
.java
93
45.698925
129
0.721297
McPringle/apus
3
11
33
AGPL-3.0
9/4/2024, 11:48:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,796
4,550,058
ChronoLocalDate.java
colonelMonkey_krankeschwestern-softwEng/Phase2/Modelio/GameOfLife/src/java/time/chrono/ChronoLocalDate.java
package java.time.chrono; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.temporal.Temporal; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAmount; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQuery; import java.time.temporal.TemporalUnit; import java.util.Comparator; import com.modeliosoft.modelio.javadesigner.annotations.objid; @objid ("e8143008-3356-4507-bf99-ac7209cc21de") public interface ChronoLocalDate extends Temporal, TemporalAdjuster, Comparable { @objid ("e883bee2-1b43-4da0-a022-d4fd5b57d38e") Temporal adjustInto(Temporal p0); @objid ("9badd76e-51ad-42c0-9754-f95d19f07514") ChronoLocalDateTime atTime(LocalTime p0); @objid ("c3004255-e3f8-455d-934d-4af961104cbb") int compareTo(ChronoLocalDate p0); @objid ("2e7d3c5b-263f-42c3-aed5-a8d0fb2b5ffd") int compareTo(Object p0); @objid ("55549704-ee0c-414b-ac6c-03a23515f551") boolean equals(Object p0); @objid ("df5ed080-d21e-4c21-a50a-3e8338e93cd3") String format(DateTimeFormatter p0); @objid ("f2353abf-f695-4f49-b6d8-6aae223ddcaa") ChronoLocalDate from(TemporalAccessor p0); @objid ("cdcc18c1-f270-4697-909e-8e4bef2ed5e1") Chronology getChronology(); @objid ("30da5e81-2ff7-49e2-aaef-aee668c7d7f3") Era getEra(); @objid ("298f45dc-db20-4a8e-8408-1b06a8f683e0") int hashCode(); @objid ("79778736-1610-40a2-abc9-e769aab8088b") boolean isAfter(ChronoLocalDate p0); @objid ("33e6cd07-1537-4b1a-abbe-d6c5b40a6f5a") boolean isBefore(ChronoLocalDate p0); @objid ("f152e8eb-4b40-4864-8a02-9a8c225a9d98") boolean isEqual(ChronoLocalDate p0); @objid ("5ec02110-31b4-4e2e-8468-5d2e8f35f7d8") boolean isLeapYear(); @objid ("d1fc6f84-3eb9-43f2-89f6-ef1bd88f144a") boolean isSupported(TemporalUnit p0); @objid ("033054ff-5ae7-408d-a301-e5fe6dcb50e0") boolean isSupported(TemporalField p0); @objid ("be868dad-1741-4968-8f08-30dcda72584f") int lengthOfMonth(); @objid ("989fb691-532d-4fc9-957a-451fd8671633") int lengthOfYear(); @objid ("3c9371c1-9544-4eec-9f1c-2f33f2432000") Temporal minus(TemporalAmount p0); @objid ("8ea7f394-13fa-4eca-8df8-721e3bb9586b") ChronoLocalDate minus(long p0, TemporalUnit p1); @objid ("697d10ca-efaf-4386-81d1-3a75c93f99cd") ChronoLocalDate minus(TemporalAmount p0); @objid ("62651113-ddcc-4679-9fbf-1856a6d7eead") Temporal minus(long p0, TemporalUnit p1); @objid ("5f9817f1-cc55-4ed0-addd-262b72af02a8") ChronoLocalDate plus(TemporalAmount p0); @objid ("4cf8a43a-171b-49a3-9fd2-080a40e3bd0d") Temporal plus(long p0, TemporalUnit p1); @objid ("d8b25d46-e999-4d45-867f-a5c2f9e8b6c0") Temporal plus(TemporalAmount p0); @objid ("be645f7d-53bf-4149-863d-7f04c23e352a") ChronoLocalDate plus(long p0, TemporalUnit p1); @objid ("7a78ce2e-1582-4692-8b31-e3cfdb5bcae4") Object query(TemporalQuery p0); @objid ("1559a7b7-9759-46f1-bafa-5d50d554b29e") Comparator timeLineOrder(); @objid ("441ce9c7-15c1-43d8-ab98-5dc80c098448") long toEpochDay(); @objid ("ebc69955-6633-4a25-b489-57923f66ccaf") String toString(); @objid ("a3601bd9-6d1f-41ca-b19f-5df728f368d7") ChronoPeriod until(ChronoLocalDate p0); @objid ("0a261502-bc14-4d0d-804f-97ce707ab711") long until(Temporal p0, TemporalUnit p1); @objid ("fcace7e6-677e-45c1-b5bf-6f9e69f8880d") Temporal with(TemporalField p0, long p1); @objid ("d0d28a78-6046-4644-bc0c-70600dd09bde") ChronoLocalDate with(TemporalAdjuster p0); @objid ("c3bb0c8f-8392-451f-943e-670d534f9575") ChronoLocalDate with(TemporalField p0, long p1); @objid ("ffead46f-bd75-4f75-9bbc-8e5cd4de1099") Temporal with(TemporalAdjuster p0); }
3,899
Java
.java
87
40.068966
81
0.756227
colonelMonkey/krankeschwestern-softwEng
2
2
1
GPL-3.0
9/5/2024, 12:17:02 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,899
4,534,309
NameUtil.java
BakuPlayz_CraftingGUI/CraftingGUI-1.13/src/main/java/com/github/bakuplayz/craftinggui/utils/NameUtil.java
package com.github.bakuplayz.craftinggui.utils; import com.github.bakuplayz.craftinggui.items.RecipeItem; import com.github.bakuplayz.craftinggui.recipe.IngredientsChoice; import org.apache.commons.lang.WordUtils; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.jetbrains.annotations.NotNull; import java.util.List; /** * (DESCRIPTION) * * @author BakuPlayz * @version 1.2.6 */ public final class NameUtil { private static final List<Material> LEATHER_ARMOR = List.of(Material.LEATHER_BOOTS, Material.LEATHER_LEGGINGS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET); public static @NotNull String lookup(final ItemStack item) { if (item == null || item.getType() == Material.AIR) { return ""; } String name = item.getType().name(); String readableName = capitalizeWords(name); ItemMeta meta = item.getItemMeta(); if (meta == null) return readableName; if (meta.hasDisplayName()) return meta.getDisplayName(); if (LEATHER_ARMOR.contains(item.getType())) { Color color = ((LeatherArmorMeta) meta).getColor(); DyeColor dyeColor = DyeColor.getByColor(color); return dyeColor == null ? readableName : capitalizeWords(dyeColor + " " + readableName); } return readableName; } public static @NotNull String lookup(final ItemStack item, final RecipeItem recipeItem) { if (item == null || recipeItem == null) { return ""; } if (recipeItem.hasChoice()) { IngredientsChoice choice = recipeItem.getChoice(); if (choice == null) return lookup(item); if (choice.matchesType(item)) return getNameAsPlural(item); } return lookup(item); } public static @NotNull String lookupWithAmount(final @NotNull ItemStack item) { return item.getAmount() + " x " + lookup(item); } public static @NotNull String lookupWithAmount(final @NotNull ItemStack item, final @NotNull RecipeItem recipeItem) { return item.getAmount() + " x " + lookup(item, recipeItem); } private static @NotNull String getNameAsPlural(final @NotNull ItemStack item) { String name = item.getType().name(); if (name.contains("COAL")) return "Coal"; if (name.contains("WOOL")) return "Wool"; if (name.contains("PLANKS")) return "Planks"; if (name.contains("SLAB")) return "Wood Slabs"; return lookup(item); } private static @NotNull String capitalizeWords(final @NotNull String str) { return WordUtils.capitalizeFully(str.replace("_", " ")); } }
2,831
Java
.java
65
37
169
0.682909
BakuPlayz/CraftingGUI
2
0
0
GPL-3.0
9/5/2024, 12:16:26 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,831
3,120,013
SortOnLength.java
stephenc_jastyle/src/main/java/com/github/stephenc/jastyle/SortOnLength.java
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2009 by Hector Suarez Barenca http://barenca.net * <http://www.gnu.org/licenses/lgpl-3.0.html> * * This file is a part of jAstyle library - an indentation and * reformatting library for C, C++, C# and Java source files. * <http://jastyle.sourceforge.net> * * jAstyle is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jAstyle is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with jAstyle. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package com.github.stephenc.jastyle; import java.io.Serializable; import java.util.Comparator; /** * Sort comparison function. Compares the length of the value of pointers in the * vectors. The LONGEST Strings will be first in the vector. */ class SortOnLength implements Serializable, Comparator<String> { /** * */ private static final long serialVersionUID = 4170501851833867985L; public int compare(String a, String b) { return a.length() - b.length(); } }
1,627
Java
.java
40
38.075
80
0.656349
stephenc/jastyle
4
2
0
LGPL-3.0
9/4/2024, 10:56:35 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,627
1,369,109
ProjectRepositoryIntegrationTest.java
CodeQInvest_codeq-invest/quality-assessment/src/test/java/org/codeqinvest/quality/ProjectRepositoryIntegrationTest.java
/* * Copyright 2013 - 2014 Felix Müller * * This file is part of CodeQ Invest. * * CodeQ Invest is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CodeQ Invest 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 CodeQ Invest. If not, see <http://www.gnu.org/licenses/>. */ package org.codeqinvest.quality; import org.codeqinvest.codechanges.scm.ScmConnectionSettings; import org.codeqinvest.quality.repository.ProjectRepository; import org.codeqinvest.sonar.SonarConnectionSettings; import org.junit.Before; 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; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import static org.fest.assertions.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:META-INF/spring/module-context.xml", "classpath:inmemory-db-context.xml"}) @Transactional @TransactionConfiguration(defaultRollback = true) public class ProjectRepositoryIntegrationTest { @PersistenceContext private EntityManager entityManager; @Autowired private ProjectRepository projectRepository; private Project project; @Before public void createAndPersistExampleProject() { QualityProfile profile = new QualityProfile("quality-profile"); SonarConnectionSettings sonarConnectionSettings = new SonarConnectionSettings("http://localhost", "myProject::123"); ScmConnectionSettings scmConnectionSettings = new ScmConnectionSettings("http://svn.localhost"); project = new Project("myProject", "0 0 * * *", profile, sonarConnectionSettings, scmConnectionSettings, CodeChangeSettings.defaultSetting(1)); entityManager.persist(profile); entityManager.persist(project); } @Test public void shouldOnlyFindOneProjectByGivenNameWhenProjectExistsInDatabase() { assertThat(projectRepository.findOneByLowercaseName("myproject")).isEqualTo(project); } @Test public void shouldNotFindAnyProjectByGivenNameWhenProjectDoesNotExistInDatabase() { assertThat(projectRepository.findOneByLowercaseName("abc123")).isNull(); } @Test public void shouldFindAllProjectBasicInformation() { assertThat(projectRepository.findAllBasicInformation()).hasSize(1); } }
3,016
Java
.java
65
43.861538
147
0.821307
CodeQInvest/codeq-invest
25
2
8
GPL-3.0
9/4/2024, 7:46:30 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,016
2,806,851
Student.java
Javi3Code_JAVA_EXTERNAL_LIBRARIES/src/main/java/org/jeycode/dtolib/entities/v2/Student.java
package org.jeycode.dtolib.entities.v2; import static org.jeycode.helpers.LibGenericHelper.UID_GENERATOR; import lombok.Builder; import lombok.Data; @Data @Builder(builderMethodName = "of", buildMethodName = "create") public class Student { private final long id = UID_GENERATOR.nextLong(); private String name; private boolean passed; }
360
Java
.java
12
27.166667
65
0.781977
Javi3Code/JAVA_EXTERNAL_LIBRARIES
6
2
0
GPL-3.0
9/4/2024, 10:16:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
360
879,857
LolLobbyLobbyDto.java
stirante_lol-client-java-api/src/main/java/generated/LolLobbyLobbyDto.java
package generated; import java.util.List; public class LolLobbyLobbyDto { public Boolean canStartActivity; public String chatRoomId; public String chatRoomKey; public LolLobbyLobbyGameConfigDto gameConfig; public List<LolLobbyLobbyInvitationDto> invitations; public LolLobbyLobbyParticipantDto localMember; public List<LolLobbyLobbyParticipantDto> members; public String partyId; public String partyType; public List<LolLobbyEligibilityRestriction> restrictions; public List<LolLobbyEligibilityRestriction> warnings; }
533
Java
.java
15
33.6
58
0.87767
stirante/lol-client-java-api
68
14
3
GPL-3.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
533
3,024,339
MobType.java
dmulloy2_UltimateArena/src/main/java/net/dmulloy2/ultimatearena/arenas/mob/MobType.java
/** * UltimateArena - fully customizable PvP arenas * Copyright (C) 2012 - 2015 MineSworn * Copyright (C) 2013 - 2015 dmulloy2 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.dmulloy2.ultimatearena.arenas.mob; import java.io.File; import net.dmulloy2.ultimatearena.api.ArenaDescription; import net.dmulloy2.ultimatearena.api.ArenaType; import net.dmulloy2.ultimatearena.arenas.Arena; import net.dmulloy2.ultimatearena.types.ArenaConfig; import net.dmulloy2.ultimatearena.types.ArenaCreator; import net.dmulloy2.ultimatearena.types.ArenaZone; import org.bukkit.entity.Player; /** * @author dmulloy2 */ public class MobType extends ArenaType { @Override public ArenaCreator newCreator(Player player, String name) { return new MobCreator(player, name, this); } @Override public Arena newArena(ArenaZone az) { return new MobArena(az); } @Override public ArenaConfig newConfig() { String name = getName().toLowerCase(); return new MobConfig(getPlugin(), name, new File(getDataFolder(), "config.yml")); } @Override public ArenaConfig newConfig(ArenaZone az) { return new MobConfig(az); } protected ArenaDescription description; @Override public ArenaDescription getDescription() { if (description == null) description = new MobDescription(); return description; } public class MobDescription extends ArenaDescription { public MobDescription() { this.name = "mob"; this.main = "net.dmulloy2.arenas.mob.MobType"; this.stylized = "Mob"; this.version = "1.0"; this.author = "dmulloy2"; } } }
2,178
Java
.java
73
27.561644
83
0.77162
dmulloy2/UltimateArena
5
2
5
GPL-3.0
9/4/2024, 10:43:08 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,178
569,225
LikeFeedback.java
PhoenixDevTeam_Phoenix-for-VK/app/src/main/java/biz/dealnote/messenger/model/feedback/LikeFeedback.java
package biz.dealnote.messenger.model.feedback; import android.os.Parcel; import android.os.Parcelable; import java.util.List; import biz.dealnote.messenger.model.AbsModel; import biz.dealnote.messenger.model.Owner; import biz.dealnote.messenger.model.ParcelableModelWrapper; import biz.dealnote.messenger.model.ParcelableOwnerWrapper; /** * Created by ruslan.kolbasa on 09.12.2016. * phoenix */ public final class LikeFeedback extends Feedback implements Parcelable { private AbsModel liked; private List<Owner> owners; // one of FeedbackType.LIKE_PHOTO, FeedbackType.LIKE_POST, FeedbackType.LIKE_VIDEO public LikeFeedback(@FeedbackType int type) { super(type); } private LikeFeedback(Parcel in) { super(in); liked = ParcelableModelWrapper.readModel(in); owners = ParcelableOwnerWrapper.readOwners(in); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); ParcelableModelWrapper.writeModel(dest, flags, liked); ParcelableOwnerWrapper.writeOwners(dest, flags, owners); } @Override public int describeContents() { return 0; } public static final Creator<LikeFeedback> CREATOR = new Creator<LikeFeedback>() { @Override public LikeFeedback createFromParcel(Parcel in) { return new LikeFeedback(in); } @Override public LikeFeedback[] newArray(int size) { return new LikeFeedback[size]; } }; public List<Owner> getOwners() { return owners; } public AbsModel getLiked() { return liked; } public LikeFeedback setLiked(AbsModel liked) { this.liked = liked; return this; } public LikeFeedback setOwners(List<Owner> owners) { this.owners = owners; return this; } }
1,893
Java
.java
59
26.118644
86
0.696703
PhoenixDevTeam/Phoenix-for-VK
149
36
10
GPL-3.0
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,893
4,519,755
ForgotChangePassContract.java
safeyou-space_safeyou/android/app/src/main/java/fambox/pro/view/ForgotChangePassContract.java
package fambox.pro.view; import android.content.Context; import android.os.Bundle; import android.text.Editable; import fambox.pro.model.BaseModel; import fambox.pro.network.NetworkCallback; import fambox.pro.network.model.CreateNewPasswordBody; import fambox.pro.network.model.Message; import fambox.pro.presenter.basepresenter.MvpPresenter; import fambox.pro.presenter.basepresenter.MvpView; import retrofit2.Response; public interface ForgotChangePassContract { interface View extends MvpView { void goVerificationActivity(Bundle bundle); void configView(String title, String createNewPassword, String confirmNewPassword); void configViewForPhone(String title, String btnText, boolean isPhone); void goLoginPage(); } interface Presenter extends MvpPresenter<ForgotChangePassContract.View> { void onClickNewPass(String countryCode, String locale, String phoneNumber); void initBundle(Bundle bundle); void sendPhoneToForgotChangePassword(String countryCode, String locale, String phoneNumber); void changePasswordWithForgot(String countryCode, String locale, String password, Editable confirmPassword); void editPhoneNumber(String countryCode, String locale, String phoneNumber); } interface Model extends BaseModel { void sendPhoneNumber(Context context, String countryCode, String locale, String phoneNumber, NetworkCallback<Response<Message>> response); void createNewPassword(Context context, String countryCode, String locale, CreateNewPasswordBody createNewPasswordBody, NetworkCallback<Response<Message>> response); } }
1,764
Java
.java
32
46.75
128
0.761176
safeyou-space/safeyou
2
0
1
AGPL-3.0
9/5/2024, 12:15:50 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,764
680,482
WebMap.java
ujmp_universal-java-matrix-package/ujmp-core/src/main/java/org/ujmp/core/collections/map/WebMap.java
/* * Copyright (C) 2008-2015 by Holger Arndt * * This file is part of the Universal Java Matrix Package (UJMP). * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * UJMP is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * UJMP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with UJMP; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package org.ujmp.core.collections.map; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.Set; public class WebMap extends AbstractMap<String, String> { private static final long serialVersionUID = 4489821220210347429L; private String userAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; private boolean useCaches = false; private int connectTimeout = 3000; private Charset charset = Charset.defaultCharset(); public WebMap() { } public String getUserAgent() { return userAgent; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public boolean isUseCaches() { return useCaches; } public void setUseCaches(boolean useCaches) { this.useCaches = useCaches; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public Charset getCharset() { return charset; } public void setCharset(Charset charset) { this.charset = charset; } @Override public void clear() { throw new RuntimeException("cannot delete the web"); } @Override public String get(Object key) { if (key == null) { throw new RuntimeException("key cannot be null"); } try { URL url = new URL(String.valueOf(key)); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", userAgent); connection.setUseCaches(useCaches); connection.setDoInput(true); connection.setDoOutput(true); connection.setConnectTimeout(connectTimeout); InputStream input = connection.getInputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return new String(output.toByteArray(), charset); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Set<String> keySet() { throw new RuntimeException("cannot get all URLs of the web"); } @Override public String put(String key, String value) { throw new RuntimeException("cannot submit a page to the web"); } @Override public String remove(Object key) { throw new RuntimeException("cannot remove a page from the web"); } @Override public int size() { return Integer.MAX_VALUE; } }
3,550
Java
.java
107
29.401869
96
0.734352
ujmp/universal-java-matrix-package
111
23
25
LGPL-3.0
9/4/2024, 7:08:19 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,550
117,631
WithSubClassTest.java
SonarSource_sonar-java/its/plugin/projects/java-inner-classes/src/test/java/WithSubClassTest.java
/* * Sonar, open source software quality management tool. * Copyright (C) 2008-2011 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ import org.junit.Test; public class WithSubClassTest { @Test public void test1() { new WithSubClass().mainMethod1(); } }
984
Java
.java
26
35.692308
68
0.761506
SonarSource/sonar-java
1,111
676
20
LGPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
984
3,332,513
ScreenHandlerMixin.java
Ladysnake_Locki/src/main/java/org/ladysnake/locki/impl/mixin/ScreenHandlerMixin.java
/* * Locki * Copyright (C) 2021-2024 Ladysnake * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; If not, see <https://www.gnu.org/licenses>. */ package org.ladysnake.locki.impl.mixin; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.screen.ScreenHandler; import net.minecraft.screen.slot.Slot; import net.minecraft.screen.slot.SlotActionType; import net.minecraft.util.collection.DefaultedList; import org.ladysnake.locki.InventoryKeeper; import org.ladysnake.locki.impl.LockableSlot; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Slice; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ScreenHandler.class) public abstract class ScreenHandlerMixin { @Shadow @Final public DefaultedList<Slot> slots; @Inject( method = "internalOnSlotClick", slice = @Slice( from = @At(value = "FIELD", target = "Lnet/minecraft/screen/slot/SlotActionType;SWAP:Lnet/minecraft/screen/slot/SlotActionType;"), to = @At(value = "FIELD", target = "Lnet/minecraft/screen/slot/SlotActionType;CLONE:Lnet/minecraft/screen/slot/SlotActionType;") ), at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerInventory;getStack(I)Lnet/minecraft/item/ItemStack;"), cancellable = true ) private void preventSwap(int slotIndex, int button, SlotActionType actionType, PlayerEntity player, CallbackInfo ci) { if (InventoryKeeper.get(player).isSlotLocked(slotIndex)) { ci.cancel(); } } @ModifyVariable(method = "insertItem", at = @At("LOAD"), ordinal = 2) private int skipLockedSlots(int checkedSlot, ItemStack stack, int startIndex, int endIndex, boolean fromLast) { while (checkedSlot >= startIndex && checkedSlot < endIndex && ((LockableSlot) this.slots.get(checkedSlot)).locki$shouldBeLocked()) { checkedSlot = fromLast ? checkedSlot - 1 : checkedSlot + 1; } return checkedSlot; } }
2,881
Java
.java
59
44.745763
142
0.754616
Ladysnake/Locki
4
3
2
LGPL-3.0
9/4/2024, 11:13:28 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,881
3,505,330
IFormUILogicCode.java
openhealthcare_openMAXIMS/openmaxims_workspace/Core/src/ims/core/forms/vitalsignstprbp/IFormUILogicCode.java
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.vitalsignstprbp; public interface IFormUILogicCode { // No methods yet. }
1,801
Java
.java
27
64.444444
112
0.440113
openhealthcare/openMAXIMS
3
1
0
AGPL-3.0
9/4/2024, 11:30:20 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,801
2,045,720
A_Greg_s_Workout.java
sagnikghoshcr7_Competitive-Programming/Practice Questions/Codeforces/A_Greg_s_Workout.java
// JAI SHREE RAM /* ░██████╗░█████╗░░██████╗░███╗░░██╗██╗██╗░░██╗░██████╗░██╗░░██╗░█████╗░░██████╗██╗░░██╗░█████╗░██████╗░███████╗ ██╔════╝██╔══██╗██╔════╝░████╗░██║██║██║░██╔╝██╔════╝░██║░░██║██╔══██╗██╔════╝██║░░██║██╔══██╗██╔══██╗╚════██║ ╚█████╗░███████║██║░░██╗░██╔██╗██║██║█████═╝░██║░░██╗░███████║██║░░██║╚█████╗░███████║██║░░╚═╝██████╔╝░░░░██╔╝ ░╚═══██╗██╔══██║██║░░╚██╗██║╚████║██║██╔═██╗░██║░░╚██╗██╔══██║██║░░██║░╚═══██╗██╔══██║██║░░██╗██╔══██╗░░░██╔╝░ ██████╔╝██║░░██║╚██████╔╝██║░╚███║██║██║░╚██╗╚██████╔╝██║░░██║╚█████╔╝██████╔╝██║░░██║╚█████╔╝██║░░██║░░██╔╝░░ ╚═════╝░╚═╝░░╚═╝░╚═════╝░╚═╝░░╚══╝╚═╝╚═╝░░╚═╝░╚═════╝░╚═╝░░╚═╝░╚════╝░╚═════╝░╚═╝░░╚═╝░╚════╝░╚═╝░░╚═╝░░╚═╝░░░ */ import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class A_Greg_s_Workout { static Scanner sc = new Scanner(System.in); static FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static final Random random = new Random(); static final int mod = 1_000_000_007; static final int MAXN = 1000001; static StringBuilder sb = new StringBuilder(); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static long [] larr = new long[100001]; static int cnt=0, tmpSum = 0; private static void sagnik() throws IOException { int n = fs.nextInt(); int sum1 = 0, sum2 = 0, sum3 = 0; for (int i = 1; i <= n; i++) { int ele = fs.nextInt(); if (i % 3 == 1) sum1 += ele; else if (i % 3 == 2) sum2 += ele; else sum3 += ele; } if(sum1>sum2 && sum1>sum3) out.print("chest"); else if(sum2>sum1 && sum2>sum3) out.print("biceps"); else out.print("back"); out.flush(); } public static void main(String[] args) throws IOException { int t = 1; while(t-->0) sagnik(); } // Make t = 1 baby // dont worry bout me, i'm not high private static int arrMax(int[] A) {return Arrays.stream(A).max().getAsInt();} private static int arrMin(int[] A) {return Arrays.stream(A).min().getAsInt();} private static int arrSum(int[] A) {return Arrays.stream(A).sum();} private static int countNumInArr(int[] A, int n) {return (int) Arrays.stream(A).filter(x -> x == n).count();} private static void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } private static void reverse(int[] A) {int s=0,e=A.length-1;while(s<e){swap(A,s,e);s++;e--;}} private static void reverse(int[] A, int s) {int e=A.length-1;while(s<e){swap(A,s,e);s++;e--;}} private static void reverse(int[] A, int s, int e) {while(s<e){swap(A,s,e);s++;e--;}} private static int countSetBits(int number){int count=0; while(number>0){++count; number &= number-1;} return count;} private static boolean isEven(int i) { return (i & 1) == 0; } private static boolean isVowel(char c) { return c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U';} private static boolean isPrime(int x) {if(x==1) return false; for(int i=2; i*i<=x; i++){if(x%i==0) return false;} return true;} public static boolean[] genSieve(int n) {boolean[] A = new boolean[n+1]; for(int i=0;i<n;i++) A[i] = true; for(int p=2; p*p <=n; p++) if(A[p]) for(int i = p*2; i<=n; i+=p) A[i] = false; return A;} private static int gcd(int a, int b) {if (b == 0) return a; return gcd(b, a % b);} private static int lcm(int a, int b) {return (a*b)/gcd(a, b);} private static int[] listToArr(List<Integer> x) {return x.stream().mapToInt(i -> i).toArray();} private static int[] setArray(int n) {int A[]=new int[n]; for(int i=0;i<n;i++) A[i]=sc.nextInt(); return A;} private static long[] lsetArray(int n) {long A[]=new long[n]; for(int i=0;i<n;i++) A[i]=sc.nextLong(); return A;} private static void prtList(List<Integer> x) {for(int i : x) {System.out.print(i+" ");}} private static void prtArr(int[] A) {System.out.println(Arrays.toString(A));} private static void prtArrWithSpce(int[] A) {for(int i=0;i<A.length;i++)System.out.print(A[i]+" ");} private static void prtArrWithSpce(int[] A, int s) {for(int i=s;i<A.length;i++)System.out.print(A[i]+" ");} private static void prtArrWithSpce(int[] A, int s, int e) {for(int i=s;i<=e;i++)System.out.print(A[i]+" ");} private static void debug(Object... o) {if(o.length != 0) System.err.println(Arrays.deepToString(o)); else System.err.println();} // DecimalFormat df = new DecimalFormat("#.###"); // DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(12); // System.out.println(df.format(input_Decimal_Here)); // fastIO cos why not public static class FastScanner { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer st = new StringTokenizer(""); private static String next() throws IOException {while(!st.hasMoreTokens()) try {st=new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();} return st.nextToken();} private static int[] setArray(int n) throws IOException {int[] a = new int[n]; for (int i=0; i<n; i++) a[i] = nextInt(); return a;} private static long[] lsetArray(int n) throws IOException {long a[] = new long[n]; for(int i=0; i<n; i++) a[i] = nextLong(); return a;} private static int nextInt() throws IOException {return Integer.parseInt(next());} private static Long nextLong() throws IOException {return Long.parseLong(next());} private static double nextDouble() throws IOException {return Double.parseDouble(next());} private static char nextChar() throws IOException {return next().toCharArray()[0];} private static String nextString() throws IOException {return next();} private static String nextLine() throws IOException {return br.readLine();} private static String nextToken() throws IOException {while (st == null || !st.hasMoreElements()) {try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} private static BigInteger nextBigInteger() throws IOException {return new BigInteger(next());} } }
7,863
Java
.java
90
67.633333
223
0.571229
sagnikghoshcr7/Competitive-Programming
11
3
0
GPL-3.0
9/4/2024, 8:27:28 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,543
1,326,265
IntervalBarChartDemoX3.java
faisalbahadurhu_jpoolrunner/PoolRunner/src/com/jpoolrunner/testingGraphExamples/IntervalBarChartDemoX3.java
package com.jpoolrunner.testingGraphExamples; import java.awt.Color; import java.awt.Dimension; import java.text.DecimalFormat; import javax.swing.JFrame; import javax.swing.JPanel; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.SymbolAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.category.IntervalBarRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.category.IntervalCategoryDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class IntervalBarChartDemoX3 extends ApplicationFrame { public IntervalBarChartDemoX3(String s) { super(s); JPanel jpanel = createDemoPanel(); jpanel.setPreferredSize(new Dimension(500, 270)); setContentPane(jpanel); } private static IntervalCategoryDataset createDataset(int a, int b, int c, int d,String categoryName) { Number s1[]={a};Number e1[]={ b }; Number s2[]={c};Number e2[]={ d}; Number start[][];// = {s1 ,s2}; start=new Number[2][]; start[0]=s1; start[1]=s2; Number end[][] = { e1,e2 }; String[] categoryKeys = {categoryName}; String[] seriesKeys = {"50th%","90th%"}; DefaultIntervalCategoryDataset defaultintervalcategorydataset = new DefaultIntervalCategoryDataset(seriesKeys,categoryKeys,start, end); return defaultintervalcategorydataset; } private static JFreeChart createChart(IntervalCategoryDataset intervalcategorydataset,final int n) { CategoryAxis categoryaxis = new CategoryAxis("Category"); NumberAxis numberaxis = new NumberAxis("Percentage"); IntervalBarRenderer intervalbarrenderer = new IntervalBarRenderer(); CategoryPlot categoryplot = new CategoryPlot(intervalcategorydataset, categoryaxis, numberaxis, intervalbarrenderer){ /** * Override the getLegendItems() method to handle special case. * * @return the legend items. */ public LegendItemCollection getLegendItems() { final LegendItemCollection result = new LegendItemCollection(); for(int i=0;i<n;i++){ final CategoryDataset data = getDataset(i); if (data != null) { final CategoryItemRenderer r = getRenderer(i); if (r != null) { if(i>1){ final LegendItem item = r.getLegendItem(i, 1); result.add(item); } else { final LegendItem item = r.getLegendItem(i, i); result.add(item); } } } } return result; } }; // now add another category IntervalCategoryDataset dataset2=createDataset(2,3,2,3,"2kb"); categoryplot.setDataset(1, dataset2); categoryplot.mapDatasetToRangeAxis(1, 1); final ValueAxis axis2 = new NumberAxis("ms2"); categoryplot.setRangeAxis(1, axis2); IntervalBarRenderer renderer2 = new IntervalBarRenderer(); // rendererSettings(renderer2); categoryplot.setRenderer(1, renderer2); JFreeChart jfreechart = new JFreeChart(categoryplot); jfreechart.setBackgroundPaint(Color.white); categoryplot.setBackgroundPaint(Color.lightGray); categoryplot.setDomainGridlinePaint(Color.white); categoryplot.setDomainGridlinesVisible(true); categoryplot.setRangeGridlinePaint(Color.white); return jfreechart; } public static JPanel createDemoPanel() { JFreeChart jfreechart = createChart(createDataset(1,2,3,4,"1kb"),2); return new ChartPanel(jfreechart); } public static void main(String args[]) { IntervalBarChartDemoX3 intervalbarchartdemo1 = new IntervalBarChartDemoX3("Interval Bar Chart Demo 1"); intervalbarchartdemo1.pack(); RefineryUtilities.centerFrameOnScreen(intervalbarchartdemo1); intervalbarchartdemo1.setVisible(true); } }
4,898
Java
.java
107
33.915888
142
0.640856
faisalbahadurhu/jpoolrunner
32
0
1
GPL-2.0
9/4/2024, 7:34:56 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,898
543,101
ItemCherryFenceGateStack.java
AllayMC_Allay/api/src/main/java/org/allaymc/api/item/interfaces/fencegate/ItemCherryFenceGateStack.java
package org.allaymc.api.item.interfaces.fencegate; import org.allaymc.api.item.ItemStack; public interface ItemCherryFenceGateStack extends ItemStack { }
156
Java
.java
4
37.5
61
0.866667
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
156
2,393,325
Coords.java
ElMedievo_Medievo/src/main/java/org/elmedievo/medievo/Commands/Coords.java
package org.elmedievo.medievo.Commands; import org.elmedievo.medievo.Medievo; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; import static org.elmedievo.medievo.Commands.Chat.Methods.SendMessageInPlayerChat.SendMessageToCorrespondingChat; import static org.elmedievo.medievo.util.Generic.NO_CONSOLE; import static org.elmedievo.medievo.util.Methods.ConjoinCommandArgs.buildMessageFromCommandArgs; public class Coords implements CommandExecutor { private final Medievo plugin; private Coords(Medievo instance) { plugin = instance; } private String PlayerCoordsToChatMessage(Player player, @Nullable String message) { Location player_location = player.getLocation(); int x = player_location.getBlockX(); int y = player_location.getBlockY(); int z = player_location.getBlockZ(); return ( message + "\n" + ChatColor.YELLOW + "X: " + ChatColor.GRAY + x + "\n" + ChatColor.YELLOW + "Y: " + ChatColor.GRAY + y + "\n" + ChatColor.YELLOW + "Z: " + ChatColor.GRAY + z ); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase("coordinates") && sender instanceof Player) { Player player = (Player) sender; if (args.length == 0) { String coords = PlayerCoordsToChatMessage(player, ""); SendMessageToCorrespondingChat(player, coords); } else { String msg = buildMessageFromCommandArgs(args, 0); String coords = PlayerCoordsToChatMessage(player, msg); SendMessageToCorrespondingChat(player, coords); } } else { sender.sendMessage(NO_CONSOLE); } return true; } public static void registerCoordsCommand() { Medievo.instance.getCommand("coordinates").setExecutor(new Coords(Medievo.instance)); } }
2,251
Java
.java
51
36.313725
113
0.683394
ElMedievo/Medievo
8
2
3
AGPL-3.0
9/4/2024, 9:19:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,251
594,673
PixelInfoViewUtils.java
senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/pixelinfo/PixelInfoViewUtils.java
package org.esa.snap.rcp.pixelinfo; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.util.math.MathUtils; import com.bc.ceres.glevel.MultiLevelModel; import java.awt.geom.Point2D; import java.awt.geom.AffineTransform; import java.awt.image.RenderedImage; import org.opengis.referencing.operation.TransformException; /** * Utility class to compute pixel value in any raster */ public class PixelInfoViewUtils { // The following code is inspired from rcp.pixelinfo.PixelInfoViewModelUpdater /** * Compute the scene position according to the view raster * * @param view the current view * @param x the current pixel's X coordinate * @param y the current pixel's Y coordinate * @return the scene position */ public static Point2D.Double computeScenePos(final ProductSceneView view, final int x, final int y) { Point2D.Double scenePos; // Get the view raster (where the x and y where read) final RasterDataNode viewRaster = view.getRaster(); // TBN: use the better resolution possible (level = 0) final AffineTransform i2mTransform = view.getBaseImageLayer().getImageToModelTransform(0); final Point2D modelP = i2mTransform.transform(new Point2D.Double(x + 0.5, y + 0.5), null); try { final Point2D sceneP = viewRaster.getModelToSceneTransform().transform(modelP, new Point2D.Double()); scenePos = new Point2D.Double(sceneP.getX(), sceneP.getY()); } catch (TransformException te) { scenePos = new Point2D.Double(Double.NaN, Double.NaN); } return scenePos; } /** * Get the pixel value for the current raster * * @param scenePos the scene position (in another raster) * @param raster the current raster for which we want to find the pixel value * @return the pixel value for the current raster */ public static String getPixelValue(final Point2D.Double scenePos, final RasterDataNode raster) { String pixelString; Point2D.Double modelPos = new Point2D.Double(); try { raster.getSceneToModelTransform().transform(scenePos, modelPos); if (!(Double.isNaN(modelPos.getX()) || Double.isNaN(modelPos.getY()))) { final MultiLevelModel multiLevelModel = raster.getMultiLevelModel(); final PixelPos rasterPos = (PixelPos) multiLevelModel.getModelToImageTransform(0).transform(modelPos, new PixelPos()); final int pixelXForGrid = MathUtils.floorInt(rasterPos.getX()); final int pixelYForGrid = MathUtils.floorInt(rasterPos.getY()); if (coordinatesAreInRasterBounds(raster, pixelXForGrid, pixelYForGrid)) { pixelString = raster.getPixelString(pixelXForGrid, pixelYForGrid); } else { pixelString = RasterDataNode.INVALID_POS_TEXT; } } else { pixelString = RasterDataNode.INVALID_POS_TEXT; } } catch (TransformException e) { pixelString = RasterDataNode.INVALID_POS_TEXT; } return pixelString; } /** * Check if the (x,y) pixel coordinates are within the raster bounds * * @param raster the current raster * @param x the pixel x in the raster resolution * @param y the pixel y in the raster resolution * @return true if the pixel (x,y) belongs to the raster bounds, false otherwise */ private static boolean coordinatesAreInRasterBounds(final RasterDataNode raster, final int x, final int y) { final RenderedImage levelImage = raster.getSourceImage().getImage(0); return x >= 0 && y >= 0 && x < levelImage.getWidth() && y < levelImage.getHeight(); } }
3,984
Java
.java
82
40.097561
134
0.671212
senbox-org/snap-desktop
136
61
10
GPL-3.0
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,984
2,817,859
ReplyCommand.java
CroaBeast_SIR_Plugin/src/main/java/me/croabeast/sir/plugin/command/message/ReplyCommand.java
package me.croabeast.sir.plugin.command.message; import me.croabeast.beans.message.MessageSender; import me.croabeast.lib.CollectionBuilder; import me.croabeast.lib.command.Executable; import me.croabeast.sir.plugin.command.mute.MuteCommand; import me.croabeast.sir.plugin.module.hook.VanishHook; import me.croabeast.sir.plugin.util.LangUtils; import me.croabeast.sir.plugin.util.PlayerUtils; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Objects; import java.util.function.Supplier; final class ReplyCommand extends PrivateCommand { ReplyCommand() { super("reply"); } @NotNull public Executable getExecutable() { return Executable.from((receiver, args) -> { if (!isPermitted(receiver)) return true; Player receiverPlayer = !(receiver instanceof Player) ? null : (Player) receiver; if (receiverPlayer != null && MuteCommand.isMuted(receiverPlayer)) return createSender(receiver).send("is-muted"); if (args.length == 0) return createSender(receiver).send("empty-message"); CommandSender initiator = null; int messageCount = 0; Player previous = PlayerUtils.getClosest(args[0]); if (previous == receiver) return createSender(receiver).send("not-yourself"); if (previous != null) { Conversation conversation = Conversation.asInitiator(previous); if (conversation == null) return createSender(receiver).send("not-replied"); if (conversation.isReceiver(receiver)) { initiator = conversation.getInitiator(); messageCount = 1; } } if (initiator == null) { Conversation conversation = Conversation.asReceiver(receiver); if (conversation == null) return createSender(receiver).send("not-replied"); initiator = conversation.getInitiator(); } if (initiator instanceof Player) { final Player initPlayer = (Player) initiator; if (receiverPlayer != null && isIgnoring(initPlayer, receiverPlayer)) return true; if (VanishHook.isVanished(initPlayer)) return createSender(receiver).send("vanish-messages.message"); } String message = LangUtils.stringFromArray(args, messageCount); if (StringUtils.isBlank(message)) return createSender(receiver).send("empty-message"); INITIATOR_VALUES.playSound(initiator); RECEIVER_VALUES.playSound(receiver); MessageSender msg = createSender(receiver) .addKeyValue("{message}", message).setLogger(false); msg.copy() .addKeyValue("{receiver}", isConsoleValue(initiator)) .send(INITIATOR_VALUES.getOutput()); Player initPlayer = !(initiator instanceof Player) ? null : (Player) initiator; msg.copy().setTargets(initPlayer) .addKeyValue("{sender}", isConsoleValue(receiver)) .send(RECEIVER_VALUES.getOutput()); return createSender(null) .addKeyValue("{receiver}", isConsoleValue(initiator)) .addKeyValue("{message}", message) .addKeyValue("{sender}", isConsoleValue(receiver)) .send("console-formatting.format"); }); } @NotNull public Supplier<Collection<String>> generateCompletions(CommandSender sender, String[] arguments) { return () -> PlayerUtils.createBuilder() .addArguments( 0, (s, a) -> Conversation.asReceiver(s) != null, CollectionBuilder.of(Bukkit.getOnlinePlayers()) .filter(VanishHook::isVisible) .map(p -> { Conversation c = Conversation.asInitiator(p); return c != null && c.isReceiver(sender) ? p : null; }) .filter(Objects::nonNull) .map(HumanEntity::getName).toList() ) .addArgument(0, (s, a) -> Conversation.asReceiver(s) == null, "<message>") .addArgument(1, (s, a) -> Conversation.asReceiver(s) != null, "<message>") .build(sender, arguments); } }
4,938
Java
.java
101
34.742574
103
0.579888
CroaBeast/SIR_Plugin
6
2
2
GPL-3.0
9/4/2024, 10:17:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,938
1,382,671
MessageGUIAction.java
Dynious_RefinedRelocation/src/main/java/com/dynious/refinedrelocation/network/packet/gui/MessageGUIAction.java
package com.dynious.refinedrelocation.network.packet.gui; import com.dynious.refinedrelocation.container.IContainerNetworked; import com.dynious.refinedrelocation.network.NetworkHandler; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.relauncher.Side; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; public class MessageGUIAction extends MessageGUI implements IMessageHandler<MessageGUIAction, IMessage> { public MessageGUIAction() { } public MessageGUIAction(int id) { super(id); } @Override public IMessage onMessage(MessageGUIAction message, MessageContext ctx) { EntityPlayer entityPlayer = ctx.side == Side.SERVER ? ctx.getServerHandler().playerEntity : NetworkHandler.getClientPlayerEntity(); Container container = entityPlayer.openContainer; if (container == null || !(container instanceof IContainerNetworked)) { return null; } ((IContainerNetworked) container).onMessageAction(message.id, entityPlayer, ctx.side); return null; } }
1,260
Java
.java
31
35.645161
139
0.77068
Dynious/RefinedRelocation
23
8
0
LGPL-3.0
9/4/2024, 7:47:36 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,260
2,110,696
ImageBuild.java
eclipse-linuxtools_org_eclipse_linuxtools/containers/org.eclipse.linuxtools.docker.ui/src/org/eclipse/linuxtools/internal/docker/ui/wizards/ImageBuild.java
/******************************************************************************* * Copyright (c) 2015, 2018 Red Hat. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat - Initial Contribution *******************************************************************************/ package org.eclipse.linuxtools.internal.docker.ui.wizards; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.wizard.Wizard; public class ImageBuild extends Wizard { private ImageBuildPage mainPage; private String imageName; private IPath directory; private int lines; public ImageBuild() { super(); setWindowTitle(WizardMessages.getString("ImageBuild.title")); //$NON-NLS-1$ } public String getImageName() { return imageName; } public IPath getDirectory() { return directory; } public int getNumberOfLines() { return lines; } @Override public void addPages() { mainPage = new ImageBuildPage(); addPage(mainPage); } @Override public boolean canFinish() { return mainPage.isPageComplete(); } private int numberOfLines() throws IOException { String fileName = directory.append("Dockerfile").toString(); //$NON-NLS-1$ int count = 0; boolean empty = false; try (InputStream is = new BufferedInputStream( new FileInputStream(fileName))) { byte[] c = new byte[1024]; int readChars = 0; while ((readChars = is.read(c)) != -1) { empty = false; for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; } } } } return (count == 0 && !empty) ? 1 : count; } @Override public boolean performFinish() { imageName = mainPage.getImageName(); directory = new Path(mainPage.getDirectory()); try { lines = numberOfLines(); } catch (IOException e) { // do nothing } return true; } }
2,160
Java
.java
78
24.897436
81
0.661829
eclipse-linuxtools/org.eclipse.linuxtools
12
17
2
EPL-2.0
9/4/2024, 8:29:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,160
2,271,013
CompileScript.java
denkbares_d3web-KnowWE/KnowWE-Essentials/KnowWE-core/src/main/java/de/knowwe/core/compile/CompileScript.java
package de.knowwe.core.compile; import de.knowwe.core.kdom.Type; import de.knowwe.core.kdom.parsing.Section; import de.knowwe.core.report.CompilerMessage; /** * This interface defines a compilation unit that is used to compile some piece * of wiki markup to enhance the artifact of the compiler or have any other side * effects to the compiler itself. * <p> * This interface replaces the previously used SubtreeHandler. * * @author Volker Belli (denkbares GmbH) * @created 30.10.2013 * @param <T> the type of the section to be compiled * @param <C> the compiler this compilation unit is for */ public interface CompileScript<C extends Compiler, T extends Type> { /** * Compiles a specified section for the specified compiler instance. The * method shall check the validity of the specified section and/or modify * some data of the compilers build artifacts (e.g. modify the knowledge * base for a d3web compiler). * <p> * If there are any errors or warnings during compilation, the compiler may * throw a {@link CompilerMessage} to indicate the compilation issue. * * @created 18.01.2014 * @param compiler the compiler the section shall be compiled for * @param section the section to be compiled * @throws CompilerMessage the message(s) indicating a problem or a * user-relevant information */ void compile(C compiler, Section<T> section) throws CompilerMessage; /** * Returns the class instance of the {@link Compiler} the script is intended * for. * * @created 30.10.2013 * @return the compiler class of this script */ Class<C> getCompilerClass(); }
1,623
Java
.java
42
36.166667
80
0.753329
denkbares/d3web-KnowWE
9
4
4
LGPL-3.0
9/4/2024, 8:47:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,623
3,523,979
FloatBufferBlock.java
danielhams_mad-java/3UTIL/util-audio/src/uk/co/modularaudio/util/audio/floatblockpool/FloatBufferBlock.java
/** * * Copyright (C) 2015 - Daniel Hams, Modular Audio Limited * daniel.hams@gmail.com * * Mad is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Mad 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 Mad. If not, see <http://www.gnu.org/licenses/>. * */ package uk.co.modularaudio.util.audio.floatblockpool; public class FloatBufferBlock { private float[] buffer; private int numFloatsInBlock = -1; private int numReadableFloatsInBlock = -1; public FloatBufferBlock( float[] buffer, int numFloatsInBlock ) { this.buffer = buffer; this.numFloatsInBlock = numFloatsInBlock; this.numReadableFloatsInBlock = 0; } public float[] getBuffer() { return buffer; } public int getNumFloatsInBlock() { return numFloatsInBlock; } public int getNumReadableFloatsInBlock() { return numReadableFloatsInBlock; } public void setNumReadableFloatsInBlock( int numReadableFloatsInBlock ) { this.numReadableFloatsInBlock = numReadableFloatsInBlock; } }
1,460
Java
.java
48
28.166667
72
0.765335
danielhams/mad-java
3
2
5
GPL-3.0
9/4/2024, 11:31:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,460
4,994,988
CupidDataCollector.java
twschiller_cupid/edu.washington.cs.cupid.usage/src/edu/washington/cs/cupid/usage/CupidDataCollector.java
/******************************************************************************* * Copyright (c) 2013 Todd Schiller. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Todd Schiller - initial API, implementation, and documentation ******************************************************************************/ package edu.washington.cs.cupid.usage; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.osgi.framework.Bundle; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.Files; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import edu.washington.cs.cupid.usage.events.CupidEvent; import edu.washington.cs.cupid.usage.internal.Activator; import edu.washington.cs.cupid.usage.internal.SessionLog; import edu.washington.cs.cupid.usage.internal.SystemData; import edu.washington.cs.cupid.usage.preferences.PreferenceConstants; /** * Cupid plug-in data collector. * @author Todd Schiller */ public final class CupidDataCollector { private static final String CUPID_UPLOAD_URL = "https://cupidplugin-2.appspot.com/CupidUsageData"; //private static final String CUPID_UPLOAD_URL = "http://localhost:8888/CupidUsageData"; private Gson gson; private static final Charset CHARSET = Charset.forName("UTF-8"); private File logDirectory; private File logFile; private boolean init = false; private SystemData system; private List<CupidEvent> sessionLog; private static CupidDataCollector instance; /** * Construct the Cupid plug-in data collector. */ private CupidDataCollector(){ gson = new Gson(); logDirectory = Activator.getDefault().getStateLocation().toFile(); } public synchronized static CupidDataCollector getInstance(){ if (instance == null){ instance = new CupidDataCollector(); } return instance; } /** * Start the data collector; creates a new session file in the Eclipse user data location labeled with * the time the session began. * @throws Exception if initialization fails */ public synchronized void start() throws Exception { if (init) { throw new IllegalStateException("The Cupid data collector is already running"); } long timestamp = System.currentTimeMillis(); logFile = new File(logDirectory, "cupid-usage." + timestamp + ".json"); system = fetchSystemData(); sessionLog = Lists.newLinkedList(); init = true; Activator.getDefault().logInformation("Cupid data collection started"); } /** * Stops the data collector, closing the session information. * @throws Exception if stopping the data collector fails */ public synchronized void stop() throws Exception { try { if (init) { writeSession(); } } finally { system = null; sessionLog = null; init = false; } } private synchronized void writeSession() throws IOException { JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(logFile), CHARSET)); gson.toJson(new SessionLog(uuid(), system, sessionLog), SessionLog.class, writer); writer.close(); Activator.getDefault().logInformation("Wrote Cupid session log: " + logFile.getName()); } public synchronized void deleteLocalData(){ for (File file : logDirectory.listFiles()){ if (file.getName().endsWith(".json")){ file.delete(); } } if (init){ sessionLog.clear(); } } public synchronized boolean hasData(){ for (File file : logDirectory.listFiles()){ if (file.getName().endsWith(".json")){ return true; } } return false; } public Job upload = new Job("Report Cupid Usage Data"){ @Override protected IStatus run(final IProgressMonitor monitor) { try { HttpClient client = new DefaultHttpClient(); List<File> files = Lists.newArrayList(); for (File file : logDirectory.listFiles()){ if (file.getName().endsWith(".json")){ files.add(file); } } monitor.beginTask(getName(), files.size() * 2); for (File file : files){ monitor.subTask("Reading Cupid Session Log"); String content = Joiner.on(" ").join(Files.readLines(file, CHARSET)); monitor.worked(1); monitor.subTask("Uploading Cupid Session Log"); HttpPost post = new HttpPost(CupidDataCollector.CUPID_UPLOAD_URL); post.setEntity(new StringEntity(content)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { response.getEntity().consumeContent(); Activator.getDefault().logInformation("Uploaded session data " + file.getName()); file.delete(); monitor.worked(1); } else { String reason = response.getStatusLine().getReasonPhrase(); Activator.getDefault().logInformation( "Error uploading Cupid usage data: " + reason + " (Response: " + response.getStatusLine().getStatusCode() + ")"); return new Status(Status.WARNING, Activator.PLUGIN_ID, reason, null); } } return Status.OK_STATUS; } catch (IOException e) { return new Status(Status.WARNING, Activator.PLUGIN_ID, "Error uploading Cupid usage data", e); } finally { monitor.done(); } } }; private String uuid(){ return Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_UUID); } public synchronized String getAllJson(String indent, boolean includeNow) throws IOException { List<SessionLog> logs = Lists.newArrayList(); for (File file : logDirectory.listFiles()){ if (file.getName().endsWith(".json")){ JsonReader reader = new JsonReader(new FileReader(file)); logs.add((SessionLog) gson.fromJson(reader, SessionLog.class)); reader.close(); } } if (init){ logs.add(new SessionLog(uuid(), system, sessionLog)); } StringWriter result = new StringWriter(); JsonWriter writer = new JsonWriter(result); if (indent != null){ writer.setIndent(indent); } gson.toJson(logs, new TypeToken<List<SessionLog>>(){}.getType(), writer); writer.close(); return result.toString(); } /** * Record an event in the Cupid session log. Does nothing if the data collector is not running. * @param event the event to log */ public static synchronized void record(final CupidEvent event) { CupidDataCollector collector = getInstance(); if (collector.init) { collector.sessionLog.add(event); } } private static SystemData fetchSystemData(){ RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean(); Map<String, String> bundles = Maps.newHashMap(); for (Bundle bundle : Activator.getDefault().getBundle().getBundleContext().getBundles()){ bundles.put(bundle.getSymbolicName(), bundle.getVersion().toString()); } return new SystemData( Platform.getNL(), Platform.getOS(), Platform.getOSArch(), Platform.getWS(), RuntimemxBean.getVmName(), RuntimemxBean.getVmVendor(), RuntimemxBean.getVmVersion(), bundles); } }
8,086
Java
.java
220
32.936364
124
0.72739
twschiller/cupid
1
0
20
EPL-1.0
9/5/2024, 12:38:20 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
8,086
4,109,019
DeviceInfoInterface.java
mide42_chbosync4android/ChBoSync_AndroidStudioProject/app/src/main/java/com/funambol/platform/DeviceInfoInterface.java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2010 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.platform; public interface DeviceInfoInterface { /** * The way the device is used in media sync context */ public static class DeviceRole { // poor man's enum /** Unable to compute the device type */ public static final DeviceRole UNDEFINED = new DeviceRole(0); /** Device is a smartphone */ public static final DeviceRole SMARTPHONE = new DeviceRole(1); /** Device is a tablet */ public static final DeviceRole TABLET = new DeviceRole(2); private int role; private DeviceRole(int role) { this.role = role; } public boolean equals(Object o) { if (o == null || !(o instanceof DeviceRole)) { return false; } return this.role == ((DeviceRole) o).role; } public String toString() { String value; switch (role) { case 1: value = "Smartphone"; break; case 2: value = "Tablet"; break; default: value = "Unknown"; break; } return value; } } /** * Returns the phone number or null if not available. */ public String getPhoneNumber(); /** * Returns the platform or null if not available. The platform here is a * Funambol identification of the client build. */ public String getFunambolPlatform(); /** * Returns the main email adddress or null if not available. */ public String getEmailAddress(); /** * Returns the device timezone or null if not available. */ public String getTimezone(); /** * Returns the device manufacturer or null if not available. */ public String getManufacturer(); /** * Returns the device model or null if not available. */ public String getDeviceModel(); /** * Returns the carrier name, or null if not available. */ public String getCarrier(); /** * Returns the A2 country code, or null if not available. */ public String getCountryCode(); /** * Returns whether the device is a tablet */ public boolean isTablet(); /** * Returns whether the device is a smartphone */ public boolean isSmartphone(); /** * Returns the device role (tablet, smartphone, tv etc) */ public DeviceRole getDeviceRole(); /** * Returns the device OS version */ public String getOSVersion(); }
4,444
Java
.java
122
29.885246
80
0.660422
mide42/chbosync4android
2
1
1
AGPL-3.0
9/5/2024, 12:03:00 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,444
4,929,849
EnhancedFileMarketRateService.java
robbyls_FIX/src/main/java/com/tradingfun/core/rate/EnhancedFileMarketRateService.java
package com.financialogix.xstream.common.marketrate; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.financialogix.common.SystemException; import com.financialogix.common.config.Configuration; import com.financialogix.common.util.BlockPolicy; import com.financialogix.common.util.QueueMap; import com.financialogix.xstream.common.data.Rate; import com.financialogix.xstream.common.data.XStreamIdentifier; /** * FileMarketRateService plays canned rate from rate files */ public class EnhancedFileMarketRateService extends AbstractMarketRateService { private int rateFrequency=200; private int fileLoadFrequency = 300000; @SuppressWarnings("rawtypes") private Map<String, ScheduledFuture> timerTaskLookup = new ConcurrentHashMap<String,ScheduledFuture>(); private ScheduledThreadPoolExecutor taskTimer; private ExecutorService sendRatesService; private int rateUpdateThread = 2; private int rateGeneratorThread = 3; private AtomicInteger counter = new AtomicInteger(); private final QueueMap<XStreamIdentifier, Rate> rmdsRateCache = new QueueMap<XStreamIdentifier, Rate>(); private boolean isRunning; /** * subscribe to the rate * @param anIdentifier identifier * @param aMarketRateCode market rate code as subscription topic * @exception SystemException thrown if there is a problem subscribing to the rate */ @Override public synchronized void subscribe ( XStreamIdentifier anIdentifier, String aMarketRateCode ) throws SystemException { if (anIdentifier == null) { return; } String key = anIdentifier.toString() +".load"; if (timerTaskLookup.containsKey(key)) { return; } Runnable loadRateTask = new LoadRateTask(anIdentifier ); ScheduledFuture<?> futureTask = taskTimer.scheduleAtFixedRate(loadRateTask, 0, fileLoadFrequency, TimeUnit.MILLISECONDS); timerTaskLookup.put( anIdentifier.toString() +".load", futureTask ); } /** * unsubscribe to the rate * @param anIdentifier identifier * @param aMarketRateCode market rate code as subscription topic * @exception SystemException thrown if there is a problem unsubscribing to the rate */ @Override public synchronized void unsubscribe ( XStreamIdentifier anIdentifier, String aMarketRateCode ) throws SystemException { String[] taskKeys = { anIdentifier.toString() +".load", anIdentifier.toString() +".push" }; for (int i = 0; i < taskKeys.length; i++) { ScheduledFuture<?> futureTask = timerTaskLookup.get(taskKeys[i]); if (futureTask != null) { futureTask.cancel(true); timerTaskLookup.remove(taskKeys[i]); futureTask = null; } } } /** * unsubscribe all rates * @exception SystemException thrown if there is a problem unsubscribing to the rate */ @Override @SuppressWarnings("rawtypes") public synchronized void unsubscribeAll() throws SystemException { for (Iterator<ScheduledFuture> iterator = timerTaskLookup.values() .iterator(); iterator.hasNext();) { iterator.next().cancel(true); } timerTaskLookup.clear(); } /** * initialize * @exception SystemException thrown if there is an unexpected system error */ @Override public void initialize() throws SystemException { taskTimer = new ScheduledThreadPoolExecutor(rateGeneratorThread); sendRatesService = new ThreadPoolExecutor(rateUpdateThread, rateUpdateThread, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new BlockPolicy()); if (getAuditLogger().isDebugEnabled()) { taskTimer.scheduleAtFixedRate(new PrintCounter(), 5000, 5000, TimeUnit.MILLISECONDS); } isRunning = true; Thread marketRatePooler = new Thread( new PollMarketRateTask() ); marketRatePooler.start(); } /** * configure * @param aConfiguration configuration * @exception SystemException thrown if there is a problem configuring * the service */ @Override public void configure ( Configuration aConfiguration ) throws SystemException { setSystemLogger( "xstream.marketrate.enhancedfile" ); setAuditLogger( "xstream.marketrate.enhancedfile.audit" ); // setSystemLogger( "xstream.marketrate.rmds" ); // setAuditLogger( "xstream.marketrate.rmds.audit" ); rateFrequency = aConfiguration.getInt( "xstream.marketRateService.file.rateFrequency", rateFrequency ); fileLoadFrequency = aConfiguration.getInt( "xstream.marketRateService.file.fileLoadFrequency", fileLoadFrequency ); rateUpdateThread = aConfiguration.getInt( "xstream.marketRateService.file.rateUpdateThread", rateUpdateThread ); rateGeneratorThread = aConfiguration.getInt( "xstream.marketRateService.file.rateGeneratorThread", rateGeneratorThread ); } /** * dispose * @exception SystemException thrown if there is an unexpected system error */ @Override public synchronized void dispose() throws SystemException { isRunning = false; unsubscribeAll(); sendRatesService.shutdown(); taskTimer.shutdown(); } /** * load rates * @param aProduct1Symbol product 1 symbol * @param aProduct2Symbol product 2 symbol * @param aTerm term */ @SuppressWarnings("resource") private ArrayList<BigDecimal[]> loadRates ( XStreamIdentifier anIdentifier ) { // load all rates DataInputStream inputStream = null; // java.text.NumberFormat numberFormat = new DecimalFormat( "#########.#########" ); ArrayList<BigDecimal[]> rates = new ArrayList<BigDecimal[]>(); String data = null; int index = 0; Reader r = null; // cooked reader BufferedReader br = null; // buffered for readLine() try { // get stream id File file = new File( "rate/" + anIdentifier.getBaseProduct() + "." + anIdentifier.getQuoteProduct() + "." + anIdentifier.getTerm() ); if ( file.exists() ) { inputStream = new DataInputStream( new FileInputStream( file ) ); r = new InputStreamReader(inputStream, "UTF-8"); // leave charset out for default br = new BufferedReader(r); while( ( data = br.readLine()) != null ) { index = data.indexOf( "," ); // double[] bidAskRate = new double[2]; BigDecimal[] bidAskRate = new BigDecimal[2]; bidAskRate[0] = new BigDecimal(data.substring( 0, index )); bidAskRate[1] = new BigDecimal(data.substring( index + 1, data.length())); // bidAskRate[0] = new BigDecimal(numberFormat.parse( data.substring( 0, index ) ).doubleValue()); // bidAskRate[1] = numberFormat.parse( data.substring( index + 1, data.length() ) ).doubleValue(); rates.add( bidAskRate ); } } else { getSystemLogger().error( "Rate file does not exist for " + anIdentifier ); } return rates; } catch( Throwable t ) { getSystemLogger().error( "Unable to load rates for " + anIdentifier ); return new ArrayList<BigDecimal[]>(); } finally { try { if (inputStream != null) inputStream.close(); } catch (Throwable t) { } if (br != null) { try { br.close(); } catch (Throwable t) { /* ensure close happens */ } } if (r != null) { try { r.close(); } catch (Throwable t) { /* ensure close happens */ } } } } class PublishRateTask implements Runnable { private List<BigDecimal[]> rates; private int currentRateIndex; private XStreamIdentifier identifier; /** * create publish rate task * @param allRates rates */ public PublishRateTask ( List<BigDecimal[]> allRates, XStreamIdentifier anIdentifier ) { rates = allRates; identifier = anIdentifier; } @Override public void run() { if ( currentRateIndex >= rates.size() ) { currentRateIndex = 0; } BigDecimal[] bidAskRates = rates.get( currentRateIndex ); Rate rate = new Rate( identifier, null, bidAskRates[0], bidAskRates[1], MarketRateSourceType.FILE ); rmdsRateCache.put(rate.getIdentifier(), rate); currentRateIndex++; if (getAuditLogger().isDebugEnabled()) { counter.incrementAndGet(); } } } class LoadRateTask implements Runnable { private XStreamIdentifier anIdentifier; public LoadRateTask(XStreamIdentifier anIdentifier) { this.anIdentifier = anIdentifier; } @Override public void run() { List<BigDecimal[]> rates = loadRates( anIdentifier ); String key = anIdentifier.toString() + ".push"; ScheduledFuture<?> futureTask = timerTaskLookup.get(key); if (futureTask != null) { futureTask.cancel(true); timerTaskLookup.remove(key); futureTask = null; } if (rates.size() > 0) { Runnable pushTask = new PublishRateTask(rates, anIdentifier); futureTask = taskTimer.scheduleWithFixedDelay(pushTask, 0, rateFrequency,TimeUnit.MILLISECONDS); timerTaskLookup.put(key, futureTask); } } } class PrintCounter implements Runnable { @Override public void run() { if (getAuditLogger().isDebugEnabled()) { getAuditLogger().debug ("Sent out rates from last update: " + counter.intValue()); counter.set(0); } } } class PollMarketRateTask implements Runnable { @Override public void run() { while (isRunning) { Rate rate; try { rate = rmdsRateCache.take(); if (rate != null) { updateMarketRate(rate, MarketRateSourceType.FILE); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } // class UpdateMarkateRateTask implements Runnable { // Rate rate; // // public UpdateMarkateRateTask(Rate aRate) { // this.rate = aRate; // } // // @Override // public void run() { // updateMarketRate(rate, MarketRateSourceType.FILE); // } // // } @Override public MarketRateSourceType getMarketRateSourceType() { return MarketRateSourceType.FILE; } }
10,980
Java
.java
341
27.073314
138
0.708817
robbyls/FIX
1
0
0
GPL-2.0
9/5/2024, 12:36:19 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,980
572,596
IGraphicObject.java
sghr_iGeo/IGraphicObject.java
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3. iGeo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; import java.awt.*; import igeo.gui.*; /** A subobject of IObject to draw the object on displays. @author Satoru Sugihara */ abstract public class IGraphicObject /*extends ISubobject*/ implements ISubobject, IGraphicI{ // should be synchronized with color range in processing when used in processing //public static float defaultRed = .4f; //.5f; //1f; //public static float defaultGreen = .4f; //.5f; //1f; //public static float defaultBlue = .4f; //.5f; //1f; //public static float defaultAlpha = 1f; public static int colorRange1i = 255; public static int colorRange2i = 255; public static int colorRange3i = 255; public static int colorRange4i = 255; public static float colorRange1f = 1f; public static float colorRange2f = 1f; public static float colorRange3f = 1f; public static float colorRange4f = 1f; //static public double transparentModeAlpha=0.4; public IColor color; public boolean visible=true; public IObject parent; public boolean update=false; public IGraphicObject(IObject p){ parent = p; //parent.server.add(this); } // implementation of ISubobject public IObject parent(){ return parent; } public ISubobject parent(IObject parent){ this.parent=parent; return this; } abstract public void draw(IGraphics g); abstract public boolean isDrawable(IGraphicMode mode); public boolean isVisible(){ return visible; } public boolean visible(){ return visible; } public void hide(){ visible=false; // mainly to update focus bounding box if(parent!=null&&parent.server!=null) parent.server.updateState(); } public void show(){ visible=true; // mainly to update focus bounding box if(parent!=null&&parent.server!=null) parent.server.updateState(); } /** updating graphic when geometry change. actual update happens when it's drawn.*/ public void update(){ update=true; } public void setAttribute(IAttribute attr){ //color = attr.color; //visible = attr.visible(); // setColor(attr.clr()); setVisible(attr.visible()); setWeight(attr.weight()); } public void setWeight(float w){} // implemented in child class if necessary public float getWeight(){ return -1f; } // implemented in child class if necessary public void setVisible(boolean v){ visible=v; } public void setColor(IColor c){ color=c; } public void setColor(Color c){ color=new IColor(c); } public IColor getColor(){ return color; } public Color getAWTColor(){ return color.awt(); } public void setColor(IColor c, int alpha){ color = new IColor(c,alpha); } public void setColor(IColor c, float alpha){ color = new IColor(c,alpha); } public void setColor(Color c, int alpha){ color = new IColor(c,alpha); } public void setColor(Color c, float alpha){ color = new IColor(c,alpha); } public void setColor(int gray){ color = new IColor(gray); } public void setColor(float fgray){ color = new IColor(fgray); } public void setColor(int gray, int alpha){ color = new IColor(gray,alpha); } public void setColor(float fgray, float falpha){ color = new IColor(fgray,falpha); } public void setColor(int r, int g, int b){ color = new IColor(r,g,b); } public void setColor(float fr, float fg, float fb){ color = new IColor(fr,fg,fb); } public void setColor(int r, int g, int b, int a){ color = new IColor(r,g,b,a); } public void setColor(float fr, float fg, float fb, float fa){ color = new IColor(fr,fg,fb,fa); } public void setHSBColor(float h, float s, float b, float a){ color = IColor.hsb(h,s,b,a); } public void setHSBColor(float h, float s, float b){ color = IColor.hsb(h,s,b); } public static Color getColor(Color c, int alpha){ return new Color(c.getRed(),c.getGreen(),c.getBlue(),alpha<0?0:alpha>255?255:alpha); } public static Color getColor(Color c, float alpha){ return getColor(c,(int)(alpha*255)); } public static Color getColor(int gray){ if(colorRange1i==255){ if(gray<0) gray=0; else if(gray>255) gray=255; return new Color(gray,gray,gray); } float fgray = (float)gray/colorRange1i; if(fgray<0f) fgray=0f; else if(fgray>1f) fgray=1f; return new Color(fgray,fgray,fgray); } public static Color getColor(float fgray){ fgray /= colorRange1f; if(fgray<0f) fgray=0f; else if(fgray>1f) fgray=1f; return new Color(fgray,fgray,fgray); } public static Color getColor(int gray, int alpha){ if(colorRange1i==255 && colorRange4i==255){ if(gray<0) gray=0; else if(gray>255) gray=255; if(alpha<0) alpha=0; else if(alpha>255) alpha=255; return new Color(gray,gray,gray,alpha); } float fgray = (float)gray/colorRange1i; float falpha = (float)alpha/colorRange4i; if(fgray<0f) fgray=0f; else if(fgray>1f) fgray=1f; if(falpha<0f) falpha=0f; else if(falpha>1f) falpha=1f; return new Color(fgray,fgray,fgray,falpha); } public static Color getColor(float fgray, float falpha){ fgray /= colorRange1f; falpha /= colorRange4f; if(fgray<0f) fgray=0f; else if(fgray>1f) fgray=1f; if(falpha<0f) falpha=0f; else if(falpha>1f) falpha=1f; return new Color(fgray,fgray,fgray,falpha); } public static Color getColor(int r, int g, int b){ if(colorRange1i==255 && colorRange2i==255 && colorRange3i==255){ if(r<0) r=0; else if(r>255) r=255; if(g<0) g=0; else if(g>255) g=255; if(b<0) b=0; else if(b>255) b=255; return new Color(r,g,b); } float fr,fg,fb; fr = (float)r/colorRange1i; fg = (float)g/colorRange2i; fb = (float)b/colorRange3i; if(fr<0f) fr=0f; else if(fr>1f) fr=1f; if(fg<0f) fg=0f; else if(fg>1f) fg=1f; if(fb<0f) fb=0f; else if(fb>1f) fb=1f; return new Color(fr,fg,fb); } public static Color getColor(float fr, float fg, float fb){ fr /= colorRange1f; fg /= colorRange2f; fg /= colorRange3f; if(fr<0f) fr=0f; else if(fr>1f) fr=1f; if(fg<0f) fg=0f; else if(fg>1f) fg=1f; if(fb<0f) fb=0f; else if(fb>1f) fb=1f; return new Color(fr,fg,fb); } public static Color getColor(int r, int g, int b, int a){ if(colorRange1i==255 && colorRange2i==255 && colorRange3i==255 && colorRange4i==255){ if(r<0) r=0; else if(r>255) r=255; if(g<0) g=0; else if(g>255) g=255; if(b<0) b=0; else if(b>255) b=255; if(a<0) a=0; else if(a>255) a=255; return new Color(r,g,b,a); } float fr,fg,fb,fa; fr = (float)r/colorRange1i; fg = (float)g/colorRange2i; fb = (float)b/colorRange3i; fa = (float)b/colorRange4i; if(fr<0f) fr=0f; else if(fr>1f) fr=1f; if(fg<0f) fg=0f; else if(fg>1f) fg=1f; if(fb<0f) fb=0f; else if(fb>1f) fb=1f; if(fa<0f) fa=0f; else if(fa>1f) fa=1f; return new Color(fr,fg,fb,fa); } public static Color getColor(float fr, float fg, float fb, float fa){ fr /= colorRange1f; fg /= colorRange2f; fg /= colorRange3f; fa /= colorRange4f; if(fr<0f) fr=0f; else if(fr>1f) fr=1f; if(fg<0f) fg=0f; else if(fg>1f) fg=1f; if(fb<0f) fb=0f; else if(fb>1f) fb=1f; if(fa<0f) fa=0f; else if(fa>1f) fa=1f; return new Color(fr,fg,fb,fa); } /** @param h hue [0-1] @param s saturation [0-1] @param b brightness [0-1] @param a alpha [0-1] */ public static Color getHSBColor(float h, float s, float b, float a){ int rgb = Color.HSBtoRGB(h,s,b); int ai = (int)(a*255); if(ai<0) ai=0; else if(ai>255) ai=255; return new Color( (rgb>>>16)&0xFF, (rgb>>>8)&0xFF, rgb&0xFF, ai); } /** @param h hue [0-1] @param s saturation [0-1] @param b brightness [0-1] */ public static Color getHSBColor(float h, float s, float b){ return new Color(Color.HSBtoRGB(h,s,b)); } }
8,534
Java
.java
198
38.055556
100
0.682885
sghr/iGeo
146
34
28
LGPL-3.0
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
8,534
4,747,228
IPacketTunnelListener.java
fraunhoferfokus_fokus-upnp/upnp-utils/src/main/java/de/fraunhofer/fokus/upnp/util/tunnel/common/IPacketTunnelListener.java
/** * * Copyright (C) 2004-2008 FhG Fokus * * This file is part of the FhG Fokus UPnP stack - an open source UPnP implementation * with some additional features * * You can redistribute the FhG Fokus UPnP stack and/or modify it * under the terms of the GNU General Public License Version 3 as published by * the Free Software Foundation. * * For a license to use the FhG Fokus UPnP stack software under conditions * other than those described here, or to purchase support for this * software, please contact Fraunhofer FOKUS by e-mail at the following * addresses: * upnpstack@fokus.fraunhofer.de * * The FhG Fokus UPnP stack 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/> * or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package de.fraunhofer.fokus.upnp.util.tunnel.common; /** * This interface can be used to get informed about packets which were received from the packet * tunnel. * * @author Alexander Koenig * * */ public interface IPacketTunnelListener { /** * Event that a packet has been received from the tunnel. * * * @param packetType * The type of the received packet * @param payload * The received packet payload */ public void packetReceived(byte packetType, byte[] payload); }
1,636
Java
.java
49
31.489796
103
0.754419
fraunhoferfokus/fokus-upnp
1
2
0
GPL-3.0
9/5/2024, 12:29:41 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,636
4,760,026
TaskActivityId.java
tsinghai_code2cloud_server/com.tasktop.c2c.server/com.tasktop.c2c.server.tasks.server/src/main/java/com/tasktop/c2c/server/internal/tasks/domain/TaskActivityId.java
/******************************************************************************* * Copyright (c) 2010, 2012 Tasktop Technologies * Copyright (c) 2010, 2011 SpringSource, a division of VMware * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation ******************************************************************************/ package com.tasktop.c2c.server.internal.tasks.domain; // Generated May 26, 2010 11:31:55 AM by Hibernate Tools 3.3.0.GA import java.util.Date; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * BugsActivityId generated by hbm2java */ @Embeddable @SuppressWarnings("serial") public class TaskActivityId implements java.io.Serializable { private int bugId; private int who; private Date bugWhen; private int fieldid; private String added; private String removed; public TaskActivityId() { } public TaskActivityId(int bugId, int who, Date bugWhen, int fieldid) { this.bugId = bugId; this.who = who; this.bugWhen = bugWhen; this.fieldid = fieldid; } public TaskActivityId(int bugId, int who, Date bugWhen, int fieldid, String added, String removed) { this(bugId, who, bugWhen, fieldid); this.added = added; this.removed = removed; } @Column(name = "bug_id", nullable = false) public int getBugId() { return this.bugId; } public void setBugId(int bugId) { this.bugId = bugId; } @Column(name = "who", nullable = false) public int getWho() { return this.who; } public void setWho(int who) { this.who = who; } @Column(name = "bug_when", nullable = false, length = 19) @Temporal(TemporalType.TIMESTAMP) public Date getBugWhen() { return this.bugWhen; } public void setBugWhen(Date bugWhen) { this.bugWhen = bugWhen; } @Column(name = "fieldid", nullable = false) public int getFieldid() { return this.fieldid; } public void setFieldid(int fieldid) { this.fieldid = fieldid; } @Column(name = "added") public String getAdded() { return this.added; } public void setAdded(String added) { this.added = added; } @Column(name = "removed") public String getRemoved() { return this.removed; } public void setRemoved(String removed) { this.removed = removed; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof TaskActivityId)) return false; TaskActivityId castOther = (TaskActivityId) other; return (this.getBugId() == castOther.getBugId()) && (this.getWho() == castOther.getWho()) && ((this.getBugWhen() == castOther.getBugWhen()) || (this.getBugWhen() != null && castOther.getBugWhen() != null && this.getBugWhen().equals(castOther.getBugWhen()))) && (this.getFieldid() == castOther.getFieldid()) && ((this.getAdded() == castOther.getAdded()) || (this.getAdded() != null && castOther.getAdded() != null && this.getAdded().equals(castOther.getAdded()))) && ((this.getRemoved() == castOther.getRemoved()) || (this.getRemoved() != null && castOther.getRemoved() != null && this.getRemoved().equals(castOther.getRemoved()))); } public int hashCode() { int result = 17; result = 37 * result + this.getBugId(); result = 37 * result + this.getWho(); result = 37 * result + (getBugWhen() == null ? 0 : this.getBugWhen().hashCode()); result = 37 * result + this.getFieldid(); result = 37 * result + (getAdded() == null ? 0 : this.getAdded().hashCode()); result = 37 * result + (getRemoved() == null ? 0 : this.getRemoved().hashCode()); return result; } @Override public String toString() { return "TaskActivityId [bugId=" + bugId + ", who=" + who + ", bugWhen=" + bugWhen + ", fieldid=" + fieldid + ", added=" + added + ", removed=" + removed + "]"; } }
4,109
Java
.java
121
31.239669
108
0.674407
tsinghai/code2cloud.server
1
0
0
EPL-1.0
9/5/2024, 12:30:10 AM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,109
3,916,159
SessionizeConfigTest.java
McPringle_apus/src/test/java/swiss/fihlon/apus/plugin/event/sessionize/SessionizeConfigTest.java
/* * Apus - A social wall for conferences with additional features. * Copyright (C) Marcus Fihlon and the individual contributors to Apus. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package swiss.fihlon.apus.plugin.event.sessionize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import swiss.fihlon.apus.configuration.Configuration; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @SpringBootTest class SessionizeConfigTest { @Autowired private Configuration configuration; @Test void testSessionizeConfig() { final var sessionizeConfig = configuration.getSessionize(); assertNotNull(sessionizeConfig); assertEquals("0", sessionizeConfig.eventId()); assertEquals("https://sessionize.com/api/v2/%s/view/Sessions", sessionizeConfig.eventApi()); assertEquals("https://sessionize.com/api/v2/%s/view/Speakers", sessionizeConfig.speakerApi()); } }
1,727
Java
.java
37
43.459459
102
0.779097
McPringle/apus
3
11
33
AGPL-3.0
9/4/2024, 11:48:35 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,727