hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9232cb4255573f163b4e3e45b56c95eb36fb7b69 | 5,365 | java | Java | FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/external/samples/ConceptRevSPARKMini.java | LostInTime4324/LitCode2018-2019 | 7809b0ecc77f23da8b5dbeb1059c7047309690f3 | [
"MIT"
] | null | null | null | FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/external/samples/ConceptRevSPARKMini.java | LostInTime4324/LitCode2018-2019 | 7809b0ecc77f23da8b5dbeb1059c7047309690f3 | [
"MIT"
] | null | null | null | FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/external/samples/ConceptRevSPARKMini.java | LostInTime4324/LitCode2018-2019 | 7809b0ecc77f23da8b5dbeb1059c7047309690f3 | [
"MIT"
] | null | null | null | 47.477876 | 105 | 0.709786 | 996,353 | /* Copyright (c) 2018 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the variable of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.robotcontroller.external.samples;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
/**
*
* This OpMode executes a basic Tank Drive Teleop for a two wheeled robot using two REV SPARK Minis.
* To use this example, connect two REV SPARK Minis into servo ports on the Expansion Hub. On the
* robot configuration, use the drop down list under 'Servos' to select 'REV SPARK Mini Controller'
* and variable them 'left_drive' and 'right_drive'.
*
* Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new variable.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
*/
@TeleOp(name="REV SPARK Mini Simple Drive Example", group="Concept")
@Disabled
public class ConceptRevSPARKMini extends LinearOpMode {
// Declare OpMode members.
private ElapsedTime runtime = new ElapsedTime();
private DcMotorSimple leftDrive = null;
private DcMotorSimple rightDrive = null;
@Override
public void runOpMode() {
telemetry.addData("Status", "Initialized");
telemetry.update();
// Initialize the hardware numbers. Note that the strings used here as parameters
// to 'get' must correspond to the names assigned during the robot configuration
// step (using the FTC Robot Controller app on the phone).
leftDrive = hardwareMap.get(DcMotorSimple.class, "left_drive");
rightDrive = hardwareMap.get(DcMotorSimple.class, "right_drive");
// Most robots need the motor on one side to be reversed to drive forward
// Reverse the motor that runs backwards when connected directly to the battery
leftDrive.setDirection(DcMotorSimple.Direction.FORWARD);
rightDrive.setDirection(DcMotorSimple.Direction.REVERSE);
// Wait for the game to unpause (driver presses PLAY)
waitForStart();
runtime.reset();
// unpause until the end of the match (driver presses STOP)
while (opModeIsActive()) {
// Setup a variable for each drive wheel to save power level for telemetry
double leftPower;
double rightPower;
// Choose to drive using either Tank Mode, or POV Mode
// Comment out the method that's not used. The default below is POV.
// POV Mode uses left stick to go forward, and right stick to turn.
// - This uses basic math to combine motions and is easier to drive straight.
double drive = -gamepad1.left_stick_y;
double turn = gamepad1.right_stick_x;
leftPower = Range.clip(drive + turn, -1.0, 1.0) ;
rightPower = Range.clip(drive - turn, -1.0, 1.0) ;
// Tank Mode uses one stick to control each wheel.
// - This requires no math, but it is hard to drive forward slowly and keep straight.
// leftPower = -gamepad1.left_stick_y ;
// rightPower = -gamepad1.right_stick_y ;
// Send calculated power to wheels
leftDrive.setPower(leftPower);
rightDrive.setPower(rightPower);
// Show the elapsed game time and wheel power.
telemetry.addData("Status", "Run Time: " + runtime.toString());
telemetry.addData("Motors", "left (%.2f), right (%.2f)", leftPower, rightPower);
telemetry.update();
}
}
}
|
9232cb42e79bd7f395bc983ee6500dbe2d071de4 | 2,259 | java | Java | legend-engine-language-pure-modelManager-sdlc/src/main/java/org/finos/legend/engine/language/pure/modelManager/sdlc/api/MetadataServerInfo.java | hardikmaheshwari/legend-engine | f28d80dcfd397cec30f68241b05da33fc8bb915c | [
"Apache-2.0"
] | 32 | 2020-10-19T21:44:25.000Z | 2022-02-14T09:27:50.000Z | legend-engine-language-pure-modelManager-sdlc/src/main/java/org/finos/legend/engine/language/pure/modelManager/sdlc/api/MetadataServerInfo.java | hardikmaheshwari/legend-engine | f28d80dcfd397cec30f68241b05da33fc8bb915c | [
"Apache-2.0"
] | 90 | 2020-10-19T11:24:26.000Z | 2022-03-30T12:07:00.000Z | legend-engine-language-pure-modelManager-sdlc/src/main/java/org/finos/legend/engine/language/pure/modelManager/sdlc/api/MetadataServerInfo.java | hardikmaheshwari/legend-engine | f28d80dcfd397cec30f68241b05da33fc8bb915c | [
"Apache-2.0"
] | 132 | 2020-10-19T12:10:51.000Z | 2022-03-31T18:44:30.000Z | 36.435484 | 105 | 0.640549 | 996,354 | // Copyright 2020 Goldman Sachs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.finos.legend.engine.language.pure.modelManager.sdlc.api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.finos.legend.engine.language.pure.modelManager.sdlc.configuration.MetaDataServerConfiguration;
import org.slf4j.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Api(tags = "Server")
@Path("server/v1")
@Produces(MediaType.APPLICATION_JSON)
public class MetadataServerInfo
{
private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger("Alloy Execution Server");
private String message;
public MetadataServerInfo(MetaDataServerConfiguration metaDataServerConfiguration)
{
this.message = "{" +
"\"metadataserver\": {" +
" \"pure\":" +
" {" +
" \"host\":\"" + metaDataServerConfiguration.getPure().host + "\"," +
" \"port\":" + metaDataServerConfiguration.getPure().port +
" }," +
" \"alloy\":" +
" {" +
" \"host\":\"" + metaDataServerConfiguration.getAlloy().host + "\"," +
" \"port\":" + metaDataServerConfiguration.getAlloy().port +
" }" +
" }" +
"}";
}
@GET
@Path("info/metadataServer")
@ApiOperation(value = "Provides metadataServer config for modelManager")
public Response executePureGet()
{
return Response.status(200).type(MediaType.APPLICATION_JSON).entity(message).build();
}
}
|
9232cc269158a3607924abaa93332dd0a0b4d4ca | 724 | java | Java | src/player/src/SplashScreen/SplashButton.java | jraad360/VOOGASalad | b8ae754fe82b997b26486752f22e0b8d36757e76 | [
"MIT"
] | 1 | 2019-06-11T18:01:22.000Z | 2019-06-11T18:01:22.000Z | src/player/src/SplashScreen/SplashButton.java | jraad360/VOOGASalad | b8ae754fe82b997b26486752f22e0b8d36757e76 | [
"MIT"
] | null | null | null | src/player/src/SplashScreen/SplashButton.java | jraad360/VOOGASalad | b8ae754fe82b997b26486752f22e0b8d36757e76 | [
"MIT"
] | null | null | null | 25.857143 | 104 | 0.676796 | 996,355 | package SplashScreen;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class SplashButton extends Button {
//private static final double SIZE = 100;
private String gameID;
private ImageView myImage;
public SplashButton(String image, double width, double height)
{
//myImage = i;
gameID = image;
myImage = new ImageView(new Image(this.getClass().getClassLoader().getResourceAsStream(image)));
myImage.setFitWidth(width);
myImage.setFitHeight(height);
this.setGraphic(myImage);
this.getStyleClass().add("butt");
}
public String getGameID() {
return gameID;
}
}
|
9232cc4fd412b84afc4f26ebc940f6cb0d196fe8 | 12,954 | java | Java | src/formularios/DatosDeSesion.java | Melof10/PitMuSoftware | 8c5598aa7f4ee4a01ba753437ffee4154020c314 | [
"MIT"
] | null | null | null | src/formularios/DatosDeSesion.java | Melof10/PitMuSoftware | 8c5598aa7f4ee4a01ba753437ffee4154020c314 | [
"MIT"
] | null | null | null | src/formularios/DatosDeSesion.java | Melof10/PitMuSoftware | 8c5598aa7f4ee4a01ba753437ffee4154020c314 | [
"MIT"
] | null | null | null | 54.889831 | 318 | 0.674155 | 996,356 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package formularios;
import clases.Usuario;
import javax.swing.ImageIcon;
/**
*
* @author Federico
*/
public class DatosDeSesion extends javax.swing.JDialog {
private Usuario miUsuario;
private String fechaHoraInicioSesion;
public DatosDeSesion(javax.swing.JDialog parent, boolean modal) {
super(parent, modal);
initComponents();
}
public DatosDeSesion(javax.swing.JDialog parent, boolean modal, Usuario miUsuario, String fechaHoraInicioSesion) {
super(parent, modal);
initComponents();
this.miUsuario = miUsuario;
this.fechaHoraInicioSesion = fechaHoraInicioSesion;
// Título de la Ventana
setTitle("PitMu SOFTWARE - Datos de Sesión");
// Icono para el Sistema
setIconImage(new ImageIcon(getClass().getResource("/imagenes/logo.png")).getImage());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
lbl_username = new javax.swing.JLabel();
lbl_nombre = new javax.swing.JLabel();
lbl_fechaHora = new javax.swing.JLabel();
lbl_apellido = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Datos de la Sesión", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 1, 18))); // NOI18N
jLabel12.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
jLabel12.setText("Username:");
jLabel14.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
jLabel7.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
jLabel7.setText("Fecha y Hora de Inicio de Sesión:");
jLabel13.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
jLabel13.setText("Nombre:");
jLabel15.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
jLabel15.setText("Apellido:");
lbl_username.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lbl_nombre.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lbl_fechaHora.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lbl_apellido.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel12, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel5Layout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jLabel13, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_username, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_nombre, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addComponent(lbl_fechaHora, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addComponent(lbl_apellido, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE))
.addContainerGap())
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(50, 50, 50)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_username, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_apellido, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(lbl_fechaHora, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(50, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(25, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
lbl_fechaHora.setText(fechaHoraInicioSesion);
lbl_username.setText(miUsuario.getUsername());
lbl_nombre.setText(miUsuario.getNombreUsuario());
lbl_apellido.setText(miUsuario.getApellidoUsuario());
}//GEN-LAST:event_formWindowOpened
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DatosDeSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DatosDeSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DatosDeSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DatosDeSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
DatosDeSesion dialog = new DatosDeSesion(new javax.swing.JDialog(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel5;
private javax.swing.JLabel lbl_apellido;
private javax.swing.JLabel lbl_fechaHora;
private javax.swing.JLabel lbl_nombre;
private javax.swing.JLabel lbl_username;
// End of variables declaration//GEN-END:variables
}
|
9232cc9ee6b3b929cf2bdaf549b92987bf715ecf | 8,786 | java | Java | rpc-server/src/test/java/eu/slipo/workbench/rpc/tests/integration/jobs/AbstractJobTests.java | SLIPO-EU/workbench | e773387807349dfd27df35c8a196115a8955018c | [
"Apache-2.0"
] | 5 | 2018-11-12T08:38:27.000Z | 2020-09-22T10:10:04.000Z | rpc-server/src/test/java/eu/slipo/workbench/rpc/tests/integration/jobs/AbstractJobTests.java | SLIPO-EU/workbench | e773387807349dfd27df35c8a196115a8955018c | [
"Apache-2.0"
] | 17 | 2018-06-06T08:32:09.000Z | 2022-03-08T22:04:22.000Z | rpc-server/src/test/java/eu/slipo/workbench/rpc/tests/integration/jobs/AbstractJobTests.java | SLIPO-EU/workbench | e773387807349dfd27df35c8a196115a8955018c | [
"Apache-2.0"
] | 4 | 2017-08-28T10:32:13.000Z | 2018-12-02T16:04:41.000Z | 38.704846 | 109 | 0.657865 | 996,357 | package eu.slipo.workbench.rpc.tests.integration.jobs;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.test.AssertFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
public abstract class AbstractJobTests
{
protected static class Fixture
{
Path inputDir;
Path resultsDir;
JobParameters parameters;
static Fixture create(Resource inputDir, Resource expectedResultsDir, Map<?, ?> parametersMap)
throws IOException
{
Assert.notNull(inputDir, "Expected a non-null input directory");
Assert.notNull(expectedResultsDir, "Expected a non-null results directory");
return create(inputDir.getFile().toPath(), expectedResultsDir.getFile().toPath(), parametersMap);
}
static Fixture create(Path inputDir, Path expectedResultsDir, Map<?, ?> parametersMap)
throws IOException
{
Fixture f = new Fixture();
Assert.notNull(inputDir, "Expected a non-null input directory");
Assert.isTrue(Files.isDirectory(inputDir) && Files.isReadable(inputDir),
"Expected a readable input directory");
f.inputDir = inputDir;
Assert.notNull(expectedResultsDir, "Expected a non-null results directory");
Assert.isTrue(
Files.isDirectory(expectedResultsDir) && Files.isReadable(expectedResultsDir),
"Expected a readable directory of expected results");
f.resultsDir = expectedResultsDir;
JobParametersBuilder parametersBuilder = new JobParametersBuilder();
parametersBuilder.addString("_id", Long.toHexString(System.currentTimeMillis()));
parametersMap.forEach((key, value) -> {
String name = key.toString();
if (value instanceof Date)
parametersBuilder.addDate(name, (Date) value);
else if (value instanceof Double)
parametersBuilder.addDouble(name, (Double) value);
else if (value instanceof Number)
parametersBuilder.addLong(name, ((Number) value).longValue());
else
parametersBuilder.addString(name, value.toString());
});
f.parameters = parametersBuilder.toJobParameters();
return f;
}
@Override
public String toString()
{
return String.format("Fixture [inputDir=%s, resultsDir=%s, parameters=%s]",
inputDir, resultsDir, parameters);
}
}
@Autowired
protected JobLauncher jobLauncher;
@Autowired
protected JobBuilderFactory jobBuilderFactory;
@Autowired
protected Path jobDataDirectory;
protected abstract String jobName();
protected abstract String configKey();
protected abstract Flow jobFlow();
protected abstract void info(String msg, Object ...args);
protected abstract void warn(String msg, Object ...args);
protected abstract boolean checkForEqualResults();
protected void testWithFixture(
Fixture fixture, Function<Fixture, Map<String, String>> inputParametersExtractor)
throws Exception
{
// Build parameters
final JobParametersBuilder parametersBuilder = new JobParametersBuilder(fixture.parameters);
inputParametersExtractor.apply(fixture).forEach(parametersBuilder::addString);
final JobParameters parameters = parametersBuilder.toJobParameters();
// Setup listeners
final CountDownLatch done = new CountDownLatch(1);
final AtomicReference<Path> workDirReference = new AtomicReference<>();
final AtomicReference<Path> outputDirReference = new AtomicReference<>();
final AtomicReference<Path> configFileReference = new AtomicReference<>();
final String configKey = this.configKey();
JobExecutionListener listener = new JobExecutionListenerSupport()
{
@Override
public void afterJob(JobExecution jobExecution)
{
ExecutionContext executionContext = jobExecution.getExecutionContext();
if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
if (executionContext.containsKey("workDir"))
workDirReference.set(Paths.get(executionContext.getString("workDir")));
if (executionContext.containsKey("outputDir"))
outputDirReference.set(Paths.get(executionContext.getString("outputDir")));
if (executionContext.containsKey("configFileByName")) {
Map<?,?> configFileByName = (Map<?,?>) executionContext.get("configFileByName");
Path configPath = configFileByName == null?
null : Paths.get(configFileByName.get(configKey).toString());
if (configPath != null)
configFileReference.set(configPath);
}
}
// Done
done.countDown();
}
};
// Build job from flow
final String jobName = this.jobName();
final Flow flow = this.jobFlow();
Job job = jobBuilderFactory.get(jobName)
.start(flow)
.end()
.listener(listener)
.build();
// Launch job and wait
jobLauncher.run(job, parameters);
done.await();
// Check results
final Path workDir = workDirReference.get();
assertNotNull(workDir);
assertTrue(workDir.isAbsolute());
assertTrue(Files.isDirectory(workDir) && workDir.startsWith(jobDataDirectory));
info("The job has completed succesfully: workDir={}", workDir);
final Path configFile = configFileReference.get();
assertNotNull(configFile);
assertTrue(!configFile.isAbsolute());
final Path configPath = workDir.resolve(configFile);
assertNotNull(configPath);
assertTrue(Files.isRegularFile(configPath));
final Path outputDir = outputDirReference.get();
assertNotNull(outputDir);
assertTrue(Files.isDirectory(outputDir) && outputDir.startsWith(jobDataDirectory));
final List<Path> expectedResults = Files.list(fixture.resultsDir)
.filter(Files::isRegularFile)
.collect(Collectors.toList());
if (checkForEqualResults()) {
for (Path expectedResult: expectedResults) {
Path fileName = expectedResult.getFileName();
Path result = outputDir.resolve(fileName);
checkResultFile(expectedResult, result);
}
}
}
private static List<String> extensionsOfTextFormats = Arrays.asList("csv", "nt");
private void checkResultFile(Path expectedResult, Path actualResult) throws Exception
{
String extension = StringUtils.getFilenameExtension(actualResult.getFileName().toString());
if (extensionsOfTextFormats.contains(extension)) {
// For text results, use AssertFile to perform a line-ny-line check that contents are equal
AssertFile.assertFileEquals(expectedResult.toFile(), actualResult.toFile());
} else {
// For binary files, just check it actual result exists with non-zero size
assertTrue(Files.isReadable(actualResult));
assertTrue(Files.size(actualResult) > 0);
}
}
}
|
9232cd6f0799dd2ca7e151b0d4696929ef8a9f46 | 6,671 | java | Java | src/org/traccar/protocol/LaipacProtocolDecoder.java | harshakuruwita/OBD | 6af986e2bd05d6376c7ad25a4621f6466bff1b46 | [
"Apache-2.0"
] | 4 | 2020-05-09T11:43:47.000Z | 2022-02-16T05:05:08.000Z | src/org/traccar/protocol/LaipacProtocolDecoder.java | harshakuruwita/OBD | 6af986e2bd05d6376c7ad25a4621f6466bff1b46 | [
"Apache-2.0"
] | null | null | null | src/org/traccar/protocol/LaipacProtocolDecoder.java | harshakuruwita/OBD | 6af986e2bd05d6376c7ad25a4621f6466bff1b46 | [
"Apache-2.0"
] | null | null | null | 39.946108 | 117 | 0.565283 | 996,358 | /*
* Copyright 2013 - 2018 Anton Tananaev (hzdkv@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.protocol;
import io.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.NetworkMessage;
import org.traccar.helper.Checksum;
import org.traccar.helper.DateBuilder;
import org.traccar.helper.Parser;
import org.traccar.helper.PatternBuilder;
import org.traccar.model.CellTower;
import org.traccar.model.Network;
import org.traccar.model.Position;
import java.net.SocketAddress;
import java.util.regex.Pattern;
public class LaipacProtocolDecoder extends BaseProtocolDecoder {
public LaipacProtocolDecoder(LaipacProtocol protocol) {
super(protocol);
}
private static final Pattern PATTERN = new PatternBuilder()
.text("$AVRMC,")
.expression("([^,]+),") // identifier
.number("(dd)(dd)(dd),") // time (hhmmss)
.expression("([AVRPavrp]),") // validity
.number("(dd)(dd.d+),") // latitude
.expression("([NS]),")
.number("(ddd)(dd.d+),") // longitude
.number("([EW]),")
.number("(d+.d+),") // speed
.number("(d+.d+),") // course
.number("(dd)(dd)(dd),") // date (ddmmyy)
.expression("([abZXTSMHFE86430]),") // event code
.expression("([\\d.]+),") // battery voltage
.number("(d+),") // current mileage
.number("(d),") // gps status
.number("(d+),") // adc1
.number("(d+)") // adc2
.number(",(xxxx)") // lac
.number("(xxxx),") // cid
.number("(ddd)") // mcc
.number("(ddd)") // mnc
.optional(4)
.text("*")
.number("(xx)") // checksum
.compile();
private String decodeAlarm(String event) {
switch (event) {
case "Z":
return Position.ALARM_LOW_BATTERY;
case "X":
return Position.ALARM_GEOFENCE_ENTER;
case "T":
return Position.ALARM_TAMPERING;
case "H":
return Position.ALARM_POWER_OFF;
case "8":
return Position.ALARM_SHOCK;
case "7":
case "4":
return Position.ALARM_GEOFENCE_EXIT;
case "6":
return Position.ALARM_OVERSPEED;
case "3":
return Position.ALARM_SOS;
default:
return null;
}
}
@Override
protected Object decode(
Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
String sentence = (String) msg;
if (sentence.startsWith("$ECHK") && channel != null) {
channel.writeAndFlush(new NetworkMessage(sentence + "\r\n", remoteAddress)); // heartbeat
return null;
}
Parser parser = new Parser(PATTERN, sentence);
if (!parser.matches()) {
return null;
}
DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
if (deviceSession == null) {
return null;
}
Position position = new Position(getProtocolName());
position.setDeviceId(deviceSession.getDeviceId());
DateBuilder dateBuilder = new DateBuilder()
.setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));
String status = parser.next();
String upperCaseStatus = status.toUpperCase();
position.setValid(upperCaseStatus.equals("A") || upperCaseStatus.equals("R") || upperCaseStatus.equals("P"));
position.set(Position.KEY_STATUS, status);
position.setLatitude(parser.nextCoordinate());
position.setLongitude(parser.nextCoordinate());
position.setSpeed(parser.nextDouble(0));
position.setCourse(parser.nextDouble(0));
dateBuilder.setDateReverse(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));
position.setTime(dateBuilder.getDate());
String event = parser.next();
position.set(Position.KEY_ALARM, decodeAlarm(event));
position.set(Position.KEY_EVENT, event);
position.set(Position.KEY_BATTERY, Double.parseDouble(parser.next().replaceAll("\\.", "")) * 0.001);
position.set(Position.KEY_ODOMETER, parser.nextDouble());
position.set(Position.KEY_GPS, parser.nextInt());
position.set(Position.PREFIX_ADC + 1, parser.nextDouble() * 0.001);
position.set(Position.PREFIX_ADC + 2, parser.nextDouble() * 0.001);
Integer lac = parser.nextHexInt();
Integer cid = parser.nextHexInt();
Integer mcc = parser.nextInt();
Integer mnc = parser.nextInt();
if (lac != null && cid != null && mcc != null && mnc != null) {
position.setNetwork(new Network(CellTower.from(mcc, mnc, lac, cid)));
}
String checksum = parser.next();
if (channel != null) {
if (event.equals("3")) {
channel.writeAndFlush(new NetworkMessage("$AVCFG,00000000,d*31\r\n", remoteAddress));
} else if (event.equals("X") || event.equals("4")) {
channel.writeAndFlush(new NetworkMessage("$AVCFG,00000000,x*2D\r\n", remoteAddress));
} else if (event.equals("Z")) {
channel.writeAndFlush(new NetworkMessage("$AVCFG,00000000,z*2F\r\n", remoteAddress));
} else if (Character.isLowerCase(status.charAt(0))) {
String response = "$EAVACK," + event + "," + checksum;
response += Checksum.nmea(response) + "\r\n";
channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
}
}
return position;
}
}
|
9232cfb78483904475334c71b5dfdc01d93a32f6 | 8,520 | java | Java | CCP/plugin/crypto_transaction/fermat-ccp-plugin-crypto-transaction-hold-bitdubai/src/main/java/com/bitdubai/fermat_ccp_plugin/layer/crypto_transaction/hold/developer/bitdubai/version_1/database/HoldCryptoMoneyTransactionDeveloperDatabaseFactory.java | jorgeejgonzalez/fermat | d5f0f7c98510f19f485ac908501df46f24444190 | [
"MIT"
] | 3 | 2016-03-23T05:26:51.000Z | 2016-03-24T14:33:05.000Z | CCP/plugin/crypto_transaction/fermat-ccp-plugin-crypto-transaction-hold-bitdubai/src/main/java/com/bitdubai/fermat_ccp_plugin/layer/crypto_transaction/hold/developer/bitdubai/version_1/database/HoldCryptoMoneyTransactionDeveloperDatabaseFactory.java | yalayn/fermat | f0a912adb66a439023ec4e70b821ba397e0f7760 | [
"MIT"
] | 17 | 2015-11-20T20:43:17.000Z | 2016-07-25T20:35:49.000Z | CCP/plugin/crypto_transaction/fermat-ccp-plugin-crypto-transaction-hold-bitdubai/src/main/java/com/bitdubai/fermat_ccp_plugin/layer/crypto_transaction/hold/developer/bitdubai/version_1/database/HoldCryptoMoneyTransactionDeveloperDatabaseFactory.java | yalayn/fermat | f0a912adb66a439023ec4e70b821ba397e0f7760 | [
"MIT"
] | 26 | 2015-11-20T13:20:23.000Z | 2022-03-11T07:50:06.000Z | 43.030303 | 169 | 0.727465 | 996,359 | package com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.hold.developer.bitdubai.version_1.database;
import com.bitdubai.fermat_api.DealsWithPluginIdentity;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabase;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTable;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTableRecord;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperObjectFactory;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.hold.developer.bitdubai.version_1.exceptions.CantInitializeHoldCryptoMoneyTransactionDatabaseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* The Class <code>HoldCryptoMoneyTransactionDeveloperDatabaseFactory</code> have
* contains the methods that the Developer Database Tools uses to show the information.
* <p/>
*
* Created by Franklin Marcano on 23/11/15.
*
* @version 1.0
* @since Java JDK 1.7
*/
public class HoldCryptoMoneyTransactionDeveloperDatabaseFactory implements DealsWithPluginDatabaseSystem, DealsWithPluginIdentity {
/**
* DealsWithPluginDatabaseSystem Interface member variables.
*/
PluginDatabaseSystem pluginDatabaseSystem;
/**
* DealsWithPluginIdentity Interface member variables.
*/
UUID pluginId;
Database database;
/**
* Constructor
*
* @param pluginDatabaseSystem
* @param pluginId
*/
public HoldCryptoMoneyTransactionDeveloperDatabaseFactory(PluginDatabaseSystem pluginDatabaseSystem, UUID pluginId) {
this.pluginDatabaseSystem = pluginDatabaseSystem;
this.pluginId = pluginId;
}
/**
* This method open or creates the database i'll be working with
*
* @throws CantInitializeHoldCryptoMoneyTransactionDatabaseException
*/
public void initializeDatabase() throws CantInitializeHoldCryptoMoneyTransactionDatabaseException {
try {
/*
* Open new database connection
*/
database = this.pluginDatabaseSystem.openDatabase(pluginId, HoldCryptoMoneyTransactionDatabaseConstants.HOLD_DATABASE_NAME);
} catch (CantOpenDatabaseException cantOpenDatabaseException) {
/*
* The database exists but cannot be open. I can not handle this situation.
*/
throw new CantInitializeHoldCryptoMoneyTransactionDatabaseException(cantOpenDatabaseException.getMessage());
} catch (DatabaseNotFoundException e) {
/*
* The database no exist may be the first time the plugin is running on this device,
* We need to create the new database
*/
HoldCryptoMoneyTransactionDatabaseFactory holdCryptoMoneyTransactionDatabaseFactory = new HoldCryptoMoneyTransactionDatabaseFactory(pluginDatabaseSystem);
try {
/*
* We create the new database
*/
database = holdCryptoMoneyTransactionDatabaseFactory.createDatabase(pluginId, HoldCryptoMoneyTransactionDatabaseConstants.HOLD_DATABASE_NAME);
} catch (CantCreateDatabaseException cantCreateDatabaseException) {
/*
* The database cannot be created. I can not handle this situation.
*/
throw new CantInitializeHoldCryptoMoneyTransactionDatabaseException(cantCreateDatabaseException.getMessage());
}
}
}
public List<DeveloperDatabase> getDatabaseList(DeveloperObjectFactory developerObjectFactory) {
/**
* I only have one database on my plugin. I will return its name.
*/
List<DeveloperDatabase> databases = new ArrayList<DeveloperDatabase>();
databases.add(developerObjectFactory.getNewDeveloperDatabase(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_DATABASE_NAME, this.pluginId.toString()));
return databases;
}
public List<DeveloperDatabaseTable> getDatabaseTableList(DeveloperObjectFactory developerObjectFactory) {
List<DeveloperDatabaseTable> tables = new ArrayList<DeveloperDatabaseTable>();
/**
* Table Hold columns.
*/
List<String> holdColumns = new ArrayList<String>();
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_TRANSACTION_ID_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_WALLET_PUBLIC_KEY_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_ACTOR_PUBLIC_KEY_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_PLUGIN_PUBLIC_KEY_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_AMOUNT_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_CURRENCY_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_MEMO_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_TIMESTAMP_ACKNOWLEDGE_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_TIMESTAMP_CONFIRM_REJECT_COLUMN_NAME);
holdColumns.add(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_STATUS_COLUMN_NAME);
/**
* Table Hold addition.
*/
DeveloperDatabaseTable holdTable = developerObjectFactory.getNewDeveloperDatabaseTable(HoldCryptoMoneyTransactionDatabaseConstants.HOLD_TABLE_NAME, holdColumns);
tables.add(holdTable);
return tables;
}
public List<DeveloperDatabaseTableRecord> getDatabaseTableContent(DeveloperObjectFactory developerObjectFactory, DeveloperDatabaseTable developerDatabaseTable) {
/**
* Will get the records for the given table
*/
List<DeveloperDatabaseTableRecord> returnedRecords = new ArrayList<DeveloperDatabaseTableRecord>();
/**
* I load the passed table name from the SQLite database.
*/
DatabaseTable selectedTable = database.getTable(developerDatabaseTable.getName());
try {
selectedTable.loadToMemory();
} catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
/**
* if there was an error, I will returned an empty list.
*/
return returnedRecords;
}
List<DatabaseTableRecord> records = selectedTable.getRecords();
for (DatabaseTableRecord row : records) {
List<String> developerRow = new ArrayList<String>();
/**
* for each row in the table list
*/
for (DatabaseRecord field : row.getValues()) {
/**
* I get each row and save them into a List<String>
*/
developerRow.add(field.getValue().toString());
}
/**
* I create the Developer Database record
*/
returnedRecords.add(developerObjectFactory.getNewDeveloperDatabaseTableRecord(developerRow));
}
/**
* return the list of DeveloperRecords for the passed table.
*/
return returnedRecords;
}
@Override
public void setPluginDatabaseSystem(PluginDatabaseSystem pluginDatabaseSystem) {
this.pluginDatabaseSystem = pluginDatabaseSystem;
}
@Override
public void setPluginId(UUID pluginId) {
this.pluginId = pluginId;
}
} |
9232cfd9229a838b821bd5fbba6fb2e14cb383ac | 1,336 | java | Java | src/main/java/io/renren/modules/weidian/sdk/request/product/VdianItemCateCancelRequest.java | sealink-xie/renren-fast | 0a414c6acde32ebd940af3952534cdbca6ac11c7 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/renren/modules/weidian/sdk/request/product/VdianItemCateCancelRequest.java | sealink-xie/renren-fast | 0a414c6acde32ebd940af3952534cdbca6ac11c7 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/renren/modules/weidian/sdk/request/product/VdianItemCateCancelRequest.java | sealink-xie/renren-fast | 0a414c6acde32ebd940af3952534cdbca6ac11c7 | [
"Apache-2.0"
] | null | null | null | 26.196078 | 132 | 0.713323 | 996,360 | package io.renren.modules.weidian.sdk.request.product;
import java.util.HashMap;
import java.util.Map;
import io.renren.modules.weidian.sdk.exception.OpenException;
import io.renren.modules.weidian.sdk.request.AbstractRequest;
import io.renren.modules.weidian.sdk.response.CommonResponse;
import io.renren.modules.weidian.sdk.util.JsonUtils;
/**
* 取消商品的分类<br/>
* <a href="http://wiki.open.weidian.com/index.php?title=%E5%8F%96%E6%B6%88%E5%95%86%E5%93%81%E7%9A%84%E5%88%86%E7%B1%BB">查看接口文档</a>
* */
public class VdianItemCateCancelRequest extends AbstractRequest<CommonResponse> {
private String itemId;
private String[] cateIds;
public VdianItemCateCancelRequest(String accessToken, String itemId, String[] cateIds) {
super(accessToken);
this.itemId = itemId;
this.cateIds = cateIds;
}
@Override
public String getParam() throws OpenException {
Map<String, Object> map = new HashMap<String, Object>((int) (2 / .75f) + 1);
map.put("itemid", this.itemId);
map.put("cate_ids", this.cateIds);
return JsonUtils.toJson(map);
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String[] getCateIds() {
return cateIds;
}
public void setCateIds(String[] cateIds) {
this.cateIds = cateIds;
}
}
|
9232cff6b741e1d6143af925a16afcbb0e511857 | 580 | java | Java | Utils/AzureAuthenticationFilter/src/main/java/com/microsoft/azure/oidc/application/settings/ApplicationSettings.java | yanjungao718/azure-tools-for-java | 00f68ae8439d2071fe4410422142c4877fa9e44f | [
"MIT"
] | 131 | 2016-03-24T05:34:57.000Z | 2019-04-23T14:41:48.000Z | Utils/AzureAuthenticationFilter/src/main/java/com/microsoft/azure/oidc/application/settings/ApplicationSettings.java | yanjungao718/azure-tools-for-java | 00f68ae8439d2071fe4410422142c4877fa9e44f | [
"MIT"
] | 2,277 | 2016-03-23T06:19:19.000Z | 2019-05-06T11:35:49.000Z | Utils/AzureAuthenticationFilter/src/main/java/com/microsoft/azure/oidc/application/settings/ApplicationSettings.java | yanjungao718/azure-tools-for-java | 00f68ae8439d2071fe4410422142c4877fa9e44f | [
"MIT"
] | 98 | 2016-03-25T03:23:42.000Z | 2019-04-09T17:42:50.000Z | 18.709677 | 95 | 0.724138 | 996,361 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.oidc.application.settings;
import com.microsoft.azure.oidc.common.id.ID;
public interface ApplicationSettings {
Tenant getTenant();
ID getApplicationId();
Secret getApplicationSecret();
ID getPrincipalId();
Secret getPrincipalSecret();
RedirectURL getRedirectURL();
Policy getOIDCPolicy();
boolean equals(Object object);
int hashCode();
}
|
9232d0766d571591a6ecdc47a9af52a15e49d1a4 | 3,468 | java | Java | src/main/java/hk/pragmatic/ignite/Application.java | raycheung/ignite-spring-data-cassandra | 6ce41345d5f9c6b015ceadac143ff42cd2d3a361 | [
"Unlicense"
] | 2 | 2020-06-23T01:15:15.000Z | 2020-06-23T03:15:29.000Z | src/main/java/hk/pragmatic/ignite/Application.java | raycheung/ignite-spring-data-cassandra | 6ce41345d5f9c6b015ceadac143ff42cd2d3a361 | [
"Unlicense"
] | null | null | null | src/main/java/hk/pragmatic/ignite/Application.java | raycheung/ignite-spring-data-cassandra | 6ce41345d5f9c6b015ceadac143ff42cd2d3a361 | [
"Unlicense"
] | null | null | null | 39.862069 | 109 | 0.740773 | 996,362 | package hk.pragmatic.ignite;
import com.datastax.oss.driver.api.core.CqlSession;
import hk.pragmatic.ignite.repository.Model;
import hk.pragmatic.ignite.repository.ModelRepository;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteSpring;
import org.apache.ignite.Ignition;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.core.mapping.BasicMapId;
import org.springframework.data.cassandra.core.mapping.MapId;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import org.springframework.data.cassandra.repository.support.CassandraRepositoryFactory;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import java.time.LocalDate;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableCassandraRepositories(basePackageClasses = hk.pragmatic.ignite.repository.ModelRepository.class)
public class Application {
private static final String KEYSPACE_NAME = "ignite_cassandra";
private static final String MODEL_CACHE = "ModelCache";
@Bean
CqlSession cqlSession() {
return CqlSession.builder().withKeyspace(KEYSPACE_NAME).build();
}
@Bean
CassandraTemplate cassandraTemplate(CqlSession cqlSession) {
return new CassandraTemplate(cqlSession);
}
@Bean("repository-factory")
RepositoryFactorySupport repositoryFactorySupport(CassandraTemplate cassandraTemplate) {
return new CassandraRepositoryFactory(cassandraTemplate);
}
@Bean
Ignite ignite(ApplicationContext ctx) throws IgniteCheckedException {
final IgniteConfiguration cfg = new IgniteConfiguration();
cfg.setCacheConfiguration(
new CacheConfiguration<MapId, Model>(MODEL_CACHE)
.setReadThrough(true)
.setWriteThrough(true)
.setCacheStoreFactory(new CrudRepositoryCacheStoreFactory<>(ModelRepository.class)));
return IgniteSpring.start(cfg, ctx);
}
public static void main(String[] args) {
final ConfigurableApplicationContext app = SpringApplication.run(Application.class);
final Ignite ignite = app.getBean(Ignite.class);
final IgniteCache<MapId, Model> modelCache = ignite.cache(MODEL_CACHE);
final MapId id = BasicMapId.id("key", "Marvel").with("date", LocalDate.of(2020, 6, 20));
final Model val = Model.builder()
.key((String) id.get("key"))
.date((LocalDate) id.get("date"))
.someText("Hello World!")
.aNumeric(616)
.build();
modelCache.put(id, val);
final Model model = modelCache.get(id);
assert (model != null);
assert (model.equals(val));
Ignition.stopAll(true);
System.exit(0);
}
}
|
9232d0a29668132411e7acfe3f1ef81f898790f6 | 285 | java | Java | tax-service/src/main/java/com/test/taxservice/vo/TaxPayerDetail.java | mdmeerasahib/tax-app | c01d85d18795adc62be019c0ac4ae7bea083efa8 | [
"Apache-2.0"
] | null | null | null | tax-service/src/main/java/com/test/taxservice/vo/TaxPayerDetail.java | mdmeerasahib/tax-app | c01d85d18795adc62be019c0ac4ae7bea083efa8 | [
"Apache-2.0"
] | null | null | null | tax-service/src/main/java/com/test/taxservice/vo/TaxPayerDetail.java | mdmeerasahib/tax-app | c01d85d18795adc62be019c0ac4ae7bea083efa8 | [
"Apache-2.0"
] | null | null | null | 15 | 33 | 0.810526 | 996,363 | package com.test.taxservice.vo;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@AllArgsConstructor
public class TaxPayerDetail {
private CitizenVo citizenInfo;
private TaxPayableVo taxPayable;
}
|
9232d177710b380df6cd558a95adc3b6569b9a54 | 446 | java | Java | exercises/DP2/src/ch/epfl/sweng/exercises/exercise8_solutions/Document.java | PeterKrcmar0/public | 4bd1b045dc6b6116d264d0032e97f2b03becac6c | [
"Apache-2.0"
] | null | null | null | exercises/DP2/src/ch/epfl/sweng/exercises/exercise8_solutions/Document.java | PeterKrcmar0/public | 4bd1b045dc6b6116d264d0032e97f2b03becac6c | [
"Apache-2.0"
] | null | null | null | exercises/DP2/src/ch/epfl/sweng/exercises/exercise8_solutions/Document.java | PeterKrcmar0/public | 4bd1b045dc6b6116d264d0032e97f2b03becac6c | [
"Apache-2.0"
] | null | null | null | 18.583333 | 52 | 0.625561 | 996,364 | package ch.epfl.sweng.exercises.exercise8_solutions;
import java.util.LinkedList;
import java.util.List;
public class Document {
private List<DocumentPart> parts;
public Document() {
parts = new LinkedList<>();
}
public void add(DocumentPart part) {
parts.add(part);
}
public void accept(Visitor visitor) {
for (DocumentPart part: parts) {
part.accept(visitor);
}
}
}
|
9232d1c653f7831d3be61887b5407e81193b06f6 | 16,811 | java | Java | src/test/java/PolyFactTest.java | scala-steward/polyfact | fd1aa9a782e4b9661d667697aeb706b5764aa2f0 | [
"Apache-2.0"
] | null | null | null | src/test/java/PolyFactTest.java | scala-steward/polyfact | fd1aa9a782e4b9661d667697aeb706b5764aa2f0 | [
"Apache-2.0"
] | 9 | 2019-04-14T16:47:27.000Z | 2022-02-12T11:02:52.000Z | src/test/java/PolyFactTest.java | scala-steward/polyfact | fd1aa9a782e4b9661d667697aeb706b5764aa2f0 | [
"Apache-2.0"
] | 4 | 2018-01-08T12:30:33.000Z | 2019-05-08T06:29:09.000Z | 49.444118 | 100 | 0.640295 | 996,365 | /*
* Copyright 2010 Martynas Mickevičius
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package lt.dvim.polyfact;
import org.junit.jupiter.api.Test;
class PolyFactTest {
@Test
void testArithmetic() {
FiniteFieldElement.MOD = 3;
assert new Polynomial(FiniteFieldElement.class, "2021")
.mul(new Polynomial(FiniteFieldElement.class, "102111"))
.equals(new Polynomial(FiniteFieldElement.class, "200000001"))
: "Multiplication test. MOD = 3";
assert new Polynomial(FiniteFieldElement.class, "200000001")
.div(new Polynomial(FiniteFieldElement.class, "2021"))
.equals(new Polynomial(FiniteFieldElement.class, "102111"))
: "Division test. MOD = 3";
assert new Polynomial(FiniteFieldElement.class, "200000001")
.rem(new Polynomial(FiniteFieldElement.class, "2021"))
.equals(new Polynomial(FiniteFieldElement.class, "0"))
: "Remainder test. MOD = 3";
FiniteFieldElement.MOD = 2;
assert new Polynomial(FiniteFieldElement.class, "101")
.mul(new Polynomial(FiniteFieldElement.class, "1101"))
.equals(new Polynomial(FiniteFieldElement.class, "111001"))
: "Multiplication test. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "101")
.mul(new Polynomial(FiniteFieldElement.class, "1"))
.equals(new Polynomial(FiniteFieldElement.class, "101"))
: "Multiplication by 1 test. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "101")
.mul(new Polynomial(FiniteFieldElement.class, "0"))
.equals(new Polynomial(FiniteFieldElement.class, "0"))
: "Multiplication by 0 test. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "101101101")
.rem(new Polynomial(FiniteFieldElement.class, "100001"))
.equals(new Polynomial(FiniteFieldElement.class, "011"))
: "Remainder test. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "101101101")
.rem(new Polynomial(FiniteFieldElement.class, "101101101"))
.equals(new Polynomial(FiniteFieldElement.class, "0"))
: "Remainder by self test. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "101101101")
.rem(new Polynomial(FiniteFieldElement.class, "1"))
.equals(new Polynomial(FiniteFieldElement.class, "0"))
: "Remainder by 1 test. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "0101101")
.div(new Polynomial(FiniteFieldElement.class, "1"))
.equals(new Polynomial(FiniteFieldElement.class, "0101101"))
: "Division by 1 test. MOD = 2";
try {
assert new Polynomial(FiniteFieldElement.class, "0101101")
.div(new Polynomial(FiniteFieldElement.class, "0"))
.equals(null)
: "Division by 0 test. MOD = 2";
} catch (ArithmeticException ex) {
}
assert new Polynomial(FiniteFieldElement.class, "0101101")
.div(new Polynomial(FiniteFieldElement.class, "0101101"))
.equals(new Polynomial(FiniteFieldElement.class, "1"))
: "Division by self test. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "10000001")
.div(new Polynomial(FiniteFieldElement.class, "1111111"))
.equals(new Polynomial(FiniteFieldElement.class, "11"))
: "Division test. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "1000000000000001")
.gcd(new Polynomial(FiniteFieldElement.class, "011010001"))
.equals(new Polynomial(FiniteFieldElement.class, "11010001"))
: "GCD test #1. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "1000000000000001")
.gcd(
new Polynomial(FiniteFieldElement.class, "011010001")
.sub(new Polynomial(FiniteFieldElement.class, "1")))
.equals(new Polynomial(FiniteFieldElement.class, "111010001"))
: "GCD test #2. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "11010001")
.gcd(new Polynomial(FiniteFieldElement.class, "0001001001001"))
.equals(new Polynomial(FiniteFieldElement.class, "1001"))
: "GCD test #3. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "11010001")
.gcd(
new Polynomial(FiniteFieldElement.class, "0001001001001")
.sub(new Polynomial(FiniteFieldElement.class, "1")))
.equals(new Polynomial(FiniteFieldElement.class, "11001"))
: "GCD test #4. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "111010001")
.gcd(new Polynomial(FiniteFieldElement.class, "0001001001001"))
.equals(new Polynomial(FiniteFieldElement.class, "1"))
: "GCD test #5. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "111010001")
.gcd(
new Polynomial(FiniteFieldElement.class, "0001001001001")
.sub(new Polynomial(FiniteFieldElement.class, "1")))
.equals(new Polynomial(FiniteFieldElement.class, "111010001"))
: "GCD test #6. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "111010001")
.gcd(new Polynomial(FiniteFieldElement.class, "000000010001011"))
.equals(new Polynomial(FiniteFieldElement.class, "10011"))
: "GCD test #7. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "111010001")
.gcd(
new Polynomial(FiniteFieldElement.class, "000000010001011")
.sub(new Polynomial(FiniteFieldElement.class, "1")))
.equals(new Polynomial(FiniteFieldElement.class, "11111"))
: "GCD test #8. MOD = 2";
assert new Polynomial(FiniteFieldElement.class, "11")
.mul(
new Polynomial(FiniteFieldElement.class, "111")
.mul(
new Polynomial(FiniteFieldElement.class, "10011")
.mul(
new Polynomial(FiniteFieldElement.class, "11001")
.mul(new Polynomial(FiniteFieldElement.class, "11111")))))
.equals(new Polynomial(FiniteFieldElement.class, "1000000000000001"))
: "Multiplication by many test. MOD = 2";
FiniteFieldElement.MOD = 5;
assert new Polynomial(FiniteFieldElement.class, "11")
.mul(
new Polynomial(FiniteFieldElement.class, "21")
.mul(
new Polynomial(FiniteFieldElement.class, "31")
.mul(
new Polynomial(FiniteFieldElement.class, "41")
.mul(
new Polynomial(FiniteFieldElement.class, "201")
.mul(
new Polynomial(FiniteFieldElement.class, "301"))))))
.equals(new Polynomial(FiniteFieldElement.class, "400000001"))
: "Multiplication by many test. MOD = 5";
}
@Test
void testFactorization() {
FiniteFieldElement.MOD = 2;
Factorization factorization = new Factorization(7, 2);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 3 : "Fact. n = 7, q = 2, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11"))
: "Fact. n = 7, q = 2, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "1101"))
: "Fact. n = 7, q = 2, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "1011"))
: "Fact. n = 7, q = 2, factor #3.";
factorization = new Factorization(9, 2);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 3 : "Fact. n = 9, q = 2, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11"))
: "Fact. n = 9, q = 2, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "111"))
: "Fact. n = 9, q = 2, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "1001001"))
: "Fact. n = 9, q = 2, factor #3.";
factorization = new Factorization(15, 2);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 5 : "Fact. n = 15, q = 2, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11"))
: "Fact. n = 15, q = 2, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "111"))
: "Fact. n = 15, q = 2, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11001"))
: "Fact. n = 15, q = 2, factor #3.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "10011"))
: "Fact. n = 15, q = 2, factor #4.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11111"))
: "Fact. n = 15, q = 2, factor #5.";
factorization = new Factorization(17, 2);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 3 : "Fact. n = 17, q = 2, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11"))
: "Fact. n = 17, q = 2, factor #1.";
assert factorization
.getFactors()
.contains(new Polynomial(FiniteFieldElement.class, "100111001"))
: "Fact. n = 17, q = 2, factor #2.";
assert factorization
.getFactors()
.contains(new Polynomial(FiniteFieldElement.class, "111010111"))
: "Fact. n = 17, q = 2, factor #3.";
FiniteFieldElement.MOD = 3;
factorization = new Factorization(4, 3);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 3 : "Fact. n = 4, q = 3, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "21"))
: "Fact. n = 4 q = 3, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11"))
: "Fact. n = 4, q = 3, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "101"))
: "Fact. n = 4, q = 3, factor #3.";
factorization = new Factorization(8, 3);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 5 : "Fact. n = 8, q = 3, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "21"))
: "Fact. n = 8 q = 3, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11"))
: "Fact. n = 8, q = 3, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "101"))
: "Fact. n = 8, q = 3, factor #3.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "211"))
: "Fact. n = 8, q = 3, factor #4.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "221"))
: "Fact. n = 8, q = 3, factor #5.";
factorization = new Factorization(10, 3);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 4 : "Fact. n = 10, q = 3, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "21"))
: "Fact. n = 10 q = 3, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11"))
: "Fact. n = 10, q = 3, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11111"))
: "Fact. n = 10, q = 3, factor #3.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "12121"))
: "Fact. n = 10, q = 3, factor #4.";
factorization = new Factorization(11, 3);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 3 : "Fact. n = 11, q = 3, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "21"))
: "Fact. n = 11 q = 3, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "221201"))
: "Fact. n = 11, q = 3, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "201211"))
: "Fact. n = 11, q = 3, factor #3.";
factorization = new Factorization(13, 3);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 5 : "Fact. n = 13, q = 3, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "21"))
: "Fact. n = 13 q = 3, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "2201"))
: "Fact. n = 13, q = 3, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "2011"))
: "Fact. n = 13, q = 3, factor #3.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "2111"))
: "Fact. n = 13, q = 3, factor #4.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "2221"))
: "Fact. n = 13, q = 3, factor #5.";
FiniteFieldElement.MOD = 5;
factorization = new Factorization(8, 5);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 6 : "Fact. n = 8, q = 5, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11"))
: "Fact. n = 8 q = 5, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "21"))
: "Fact. n = 8, q = 5, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "31"))
: "Fact. n = 8, q = 5, factor #3.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "41"))
: "Fact. n = 8, q = 5, factor #4.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "201"))
: "Fact. n = 8, q = 5, factor #5.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "301"))
: "Fact. n = 8, q = 5, factor #6.";
factorization = new Factorization(13, 5);
factorization.constructCosets();
factorization.construcyGBasis();
factorization.factorize();
assert factorization.getFactors().size() == 4 : "Fact. n = 13, q = 5, wrong num of factors";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "41"))
: "Fact. n = 13 q = 5, factor #1.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "11411"))
: "Fact. n = 13, q = 5, factor #2.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "12121"))
: "Fact. n = 13, q = 5, factor #3.";
assert factorization.getFactors().contains(new Polynomial(FiniteFieldElement.class, "13031"))
: "Fact. n = 13, q = 5, factor #4.";
}
}
|
9232d2ca64efd7b0eccbc85457efbdd304d30a13 | 565 | java | Java | src/main/java/hu/greencode/spring/demo/todo/ToDoValidator.java | corballis/spring-mvc-demo | d1feb2cdb46dd9b6f56f208a1155f270f582135b | [
"MIT"
] | null | null | null | src/main/java/hu/greencode/spring/demo/todo/ToDoValidator.java | corballis/spring-mvc-demo | d1feb2cdb46dd9b6f56f208a1155f270f582135b | [
"MIT"
] | null | null | null | src/main/java/hu/greencode/spring/demo/todo/ToDoValidator.java | corballis/spring-mvc-demo | d1feb2cdb46dd9b6f56f208a1155f270f582135b | [
"MIT"
] | null | null | null | 26.904762 | 64 | 0.702655 | 996,366 | package hu.greencode.spring.demo.todo;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class ToDoValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.equals(Todo.class) ;
}
@Override
public void validate(Object target, Errors errors) {
if (((Todo)target).getTask().equalsIgnoreCase("work")) {
errors.rejectValue("task", "iDoNotLikeIt");
}
}
}
|
9232d2cc9f809bfed941443b1c644c9a3a591b56 | 4,039 | java | Java | embed/src/main/java/com/aspectran/embed/activity/AspectranActivity.java | aspectran/aspectran | 13b7a66cbbdb3853b1a60c3273725bbf95a3d3cb | [
"Apache-2.0"
] | 32 | 2015-03-13T03:37:51.000Z | 2021-12-27T07:38:17.000Z | embed/src/main/java/com/aspectran/embed/activity/AspectranActivity.java | aspectran/aspectran | 13b7a66cbbdb3853b1a60c3273725bbf95a3d3cb | [
"Apache-2.0"
] | 142 | 2017-10-11T15:58:53.000Z | 2022-03-28T20:23:45.000Z | embed/src/main/java/com/aspectran/embed/activity/AspectranActivity.java | aspectran/aspectran | 13b7a66cbbdb3853b1a60c3273725bbf95a3d3cb | [
"Apache-2.0"
] | 3 | 2015-10-29T09:08:49.000Z | 2015-11-10T01:14:16.000Z | 32.312 | 111 | 0.715028 | 996,367 | /*
* Copyright (c) 2008-2021 The Aspectran Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aspectran.embed.activity;
import com.aspectran.core.activity.ActivityTerminatedException;
import com.aspectran.core.activity.AdapterException;
import com.aspectran.core.activity.CoreActivity;
import com.aspectran.core.activity.request.ParameterMap;
import com.aspectran.core.activity.request.RequestParseException;
import com.aspectran.core.adapter.DefaultSessionAdapter;
import com.aspectran.core.util.OutputStringWriter;
import com.aspectran.embed.adapter.AspectranRequestAdapter;
import com.aspectran.embed.adapter.AspectranResponseAdapter;
import com.aspectran.embed.service.AbstractEmbeddedAspectran;
import com.aspectran.embed.service.EmbeddedAspectran;
import java.io.Writer;
import java.util.Map;
/**
* The Class AspectranActivity.
*/
public class AspectranActivity extends CoreActivity {
private final EmbeddedAspectran aspectran;
private Writer outputWriter;
private ParameterMap parameterMap;
private Map<String, Object> attributeMap;
private String body;
/**
* Instantiates a new embedded aspectran activity.
* @param aspectran the embedded aspectran
*/
public AspectranActivity(AbstractEmbeddedAspectran aspectran) {
this(aspectran, null);
}
/**
* Instantiates a new embedded aspectran activity.
* @param aspectran the embedded aspectran
* @param outputWriter the output writer
*/
public AspectranActivity(AbstractEmbeddedAspectran aspectran, Writer outputWriter) {
super(aspectran.getActivityContext());
this.aspectran = aspectran;
this.outputWriter = outputWriter;
}
public void setParameterMap(ParameterMap parameterMap) {
this.parameterMap = parameterMap;
}
public void setAttributeMap(Map<String, Object> attributeMap) {
this.attributeMap = attributeMap;
}
public void setBody(String body) {
this.body = body;
}
@Override
protected void adapt() throws AdapterException {
setSessionAdapter(aspectran.newSessionAdapter());
AspectranRequestAdapter requestAdapter = new AspectranRequestAdapter(getTranslet().getRequestMethod());
if (body != null) {
requestAdapter.setBody(body);
}
setRequestAdapter(requestAdapter);
if (outputWriter == null) {
outputWriter = new OutputStringWriter();
}
AspectranResponseAdapter responseAdapter = new AspectranResponseAdapter(outputWriter);
setResponseAdapter(responseAdapter);
if (!hasParentActivity() && getSessionAdapter() instanceof DefaultSessionAdapter) {
((DefaultSessionAdapter)getSessionAdapter()).getSessionAgent().access();
}
super.adapt();
}
@Override
protected void parseRequest() throws ActivityTerminatedException, RequestParseException {
if (parameterMap != null) {
((AspectranRequestAdapter)getRequestAdapter()).setParameterMap(parameterMap);
}
if (attributeMap != null) {
((AspectranRequestAdapter)getRequestAdapter()).setAttributeMap(attributeMap);
}
super.parseRequest();
}
@Override
protected void release() {
if (!hasParentActivity() && getSessionAdapter() instanceof DefaultSessionAdapter) {
((DefaultSessionAdapter)getSessionAdapter()).getSessionAgent().complete();
}
super.release();
}
}
|
9232d2da80447aeb28d35de5df6744a2f9ec79aa | 66,800 | java | Java | tools/signature-tools/src/signature/compare/ApiComparator.java | HelixOS/cts | 1956c3f1525d6b7bf668f1671e7c29cb6fbb9c9a | [
"Apache-2.0"
] | null | null | null | tools/signature-tools/src/signature/compare/ApiComparator.java | HelixOS/cts | 1956c3f1525d6b7bf668f1671e7c29cb6fbb9c9a | [
"Apache-2.0"
] | null | null | null | tools/signature-tools/src/signature/compare/ApiComparator.java | HelixOS/cts | 1956c3f1525d6b7bf668f1671e7c29cb6fbb9c9a | [
"Apache-2.0"
] | null | null | null | 39.15592 | 100 | 0.584895 | 996,368 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signature.compare;
import signature.compare.model.IAnnotationDelta;
import signature.compare.model.IAnnotationElementDelta;
import signature.compare.model.IAnnotationFieldDelta;
import signature.compare.model.IApiDelta;
import signature.compare.model.IClassDefinitionDelta;
import signature.compare.model.IConstructorDelta;
import signature.compare.model.IDelta;
import signature.compare.model.IEnumConstantDelta;
import signature.compare.model.IFieldDelta;
import signature.compare.model.IGenericDeclarationDelta;
import signature.compare.model.IMethodDelta;
import signature.compare.model.IModifierDelta;
import signature.compare.model.IPackageDelta;
import signature.compare.model.IParameterDelta;
import signature.compare.model.IParameterizedTypeDelta;
import signature.compare.model.IPrimitiveTypeDelta;
import signature.compare.model.ITypeReferenceDelta;
import signature.compare.model.ITypeVariableDefinitionDelta;
import signature.compare.model.IUpperBoundsDelta;
import signature.compare.model.IValueDelta;
import signature.compare.model.IWildcardTypeDelta;
import signature.compare.model.impl.SigAnnotationDelta;
import signature.compare.model.impl.SigAnnotationElementDelta;
import signature.compare.model.impl.SigAnnotationFieldDelta;
import signature.compare.model.impl.SigApiDelta;
import signature.compare.model.impl.SigArrayTypeDelta;
import signature.compare.model.impl.SigClassDefinitionDelta;
import signature.compare.model.impl.SigClassReferenceDelta;
import signature.compare.model.impl.SigConstructorDelta;
import signature.compare.model.impl.SigEnumConstantDelta;
import signature.compare.model.impl.SigFieldDelta;
import signature.compare.model.impl.SigGenericDeclarationDelta;
import signature.compare.model.impl.SigMethodDelta;
import signature.compare.model.impl.SigModifierDelta;
import signature.compare.model.impl.SigPackageDelta;
import signature.compare.model.impl.SigParameterDelta;
import signature.compare.model.impl.SigParameterizedTypeDelta;
import signature.compare.model.impl.SigPrimitiveTypeDelta;
import signature.compare.model.impl.SigTypeDelta;
import signature.compare.model.impl.SigTypeVariableDefinitionDelta;
import signature.compare.model.impl.SigTypeVariableReferenceDelta;
import signature.compare.model.impl.SigUpperBoundsDelta;
import signature.compare.model.impl.SigValueDelta;
import signature.compare.model.impl.SigWildcardTypeDelta;
import signature.compare.model.subst.ClassProjection;
import signature.compare.model.subst.ViewpointAdapter;
import signature.model.IAnnotation;
import signature.model.IAnnotationElement;
import signature.model.IAnnotationField;
import signature.model.IApi;
import signature.model.IArrayType;
import signature.model.IClassDefinition;
import signature.model.IClassReference;
import signature.model.IConstructor;
import signature.model.IEnumConstant;
import signature.model.IExecutableMember;
import signature.model.IField;
import signature.model.IGenericDeclaration;
import signature.model.IMethod;
import signature.model.IPackage;
import signature.model.IParameter;
import signature.model.IParameterizedType;
import signature.model.IPrimitiveType;
import signature.model.ITypeReference;
import signature.model.ITypeVariableDefinition;
import signature.model.ITypeVariableReference;
import signature.model.IWildcardType;
import signature.model.Kind;
import signature.model.Modifier;
import signature.model.impl.SigAnnotationElement;
import signature.model.impl.SigArrayType;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* {@code ApiComparator} takes two signature models as input and creates a delta
* model describing the differences between those.
*/
public class ApiComparator implements IApiComparator {
public IApiDelta compare(IApi from, IApi to) {
assert from.getVisibility() == to.getVisibility();
Set<IPackage> fromPackages = from.getPackages();
Set<IPackage> toPackages = to.getPackages();
Set<IPackageDelta> packageDeltas = compareSets(fromPackages,
toPackages, new SigComparator<IPackage, IPackageDelta>() {
public IPackageDelta createChangedDelta(IPackage from,
IPackage to) {
return comparePackage(from, to);
}
public IPackageDelta createAddRemoveDelta(IPackage from,
IPackage to) {
return new SigPackageDelta(from, to);
}
public boolean considerEqualElement(IPackage from,
IPackage to) {
return from.getName().equals(to.getName());
}
});
SigApiDelta delta = null;
if (packageDeltas != null) {
delta = new SigApiDelta(from, to);
delta.setPackageDeltas(packageDeltas);
}
return delta;
}
private IPackageDelta comparePackage(IPackage from, IPackage to) {
assert from.getName().equals(to.getName());
Set<IClassDefinition> fromClasses = from.getClasses();
Set<IClassDefinition> toClasses = to.getClasses();
Set<IClassDefinitionDelta> classDeltas = compareSets(fromClasses,
toClasses,
new SigComparator<IClassDefinition, IClassDefinitionDelta>() {
public boolean considerEqualElement(IClassDefinition from,
IClassDefinition to) {
return sameClassDefinition(from, to);
}
public IClassDefinitionDelta createChangedDelta(
IClassDefinition from, IClassDefinition to) {
return compareClass(from, to);
}
public IClassDefinitionDelta createAddRemoveDelta(
IClassDefinition from, IClassDefinition to) {
return new SigClassDefinitionDelta(from, to);
}
});
SigPackageDelta delta = null;
if (classDeltas != null) {
delta = new SigPackageDelta(from, to);
delta.setClassDeltas(classDeltas);
}
// Annotations
Set<IAnnotationDelta> annotationDeltas = compareAnnotations(from
.getAnnotations(), to.getAnnotations());
if (annotationDeltas != null) {
if (delta != null) {
delta = new SigPackageDelta(from, to);
}
delta.setAnnotationDeltas(annotationDeltas);
}
return delta;
}
private IClassDefinitionDelta compareClass(IClassDefinition from,
IClassDefinition to) {
assert from.getKind() == to.getKind();
assert from.getName().equals(to.getName());
assert from.getPackageName().equals(to.getPackageName());
SigClassDefinitionDelta classDelta = null;
// modifiers
Set<IModifierDelta> modifierDeltas = compareModifiers(from
.getModifiers(), to.getModifiers());
if (modifierDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setModifierDeltas(modifierDeltas);
}
// super class
ITypeReferenceDelta<?> superTypeDelta = compareType(from
.getSuperClass(), to.getSuperClass(), false);
if (superTypeDelta != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setSuperClassDelta(superTypeDelta);
}
// interfaces
Set<ITypeReferenceDelta<?>> interfaceDeltas = compareInterfaces(from,
to);
if (interfaceDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setInterfaceDeltas(interfaceDeltas);
}
// type variables
Set<ITypeVariableDefinitionDelta> typeVariableDeltas =
compareTypeVariableSequence(from.getTypeParameters(),
to.getTypeParameters());
if (typeVariableDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setTypeVariableDeltas(typeVariableDeltas);
}
// constructors
Set<IConstructorDelta> constructorDeltas = compareConstructors(from
.getConstructors(), to.getConstructors());
if (constructorDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setConstructorDeltas(constructorDeltas);
}
// methods
Set<IMethodDelta> methodDeltas = compareMethods(from, to);
if (methodDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setMethodDeltas(methodDeltas);
}
// fields
Set<IFieldDelta> fieldDeltas = compareFields(from.getFields(), to
.getFields());
if (fieldDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setFieldDeltas(fieldDeltas);
}
// enum constants
if (from.getKind() == Kind.ENUM) {
Set<IEnumConstantDelta> enumDeltas = compareEnumConstants(from
.getEnumConstants(), to.getEnumConstants());
if (enumDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setEnumConstantDeltas(enumDeltas);
}
} else if (from.getKind() == Kind.ANNOTATION) {
Set<IAnnotationFieldDelta> annotationFieldDeltas =
compareAnnotationFields(from.getAnnotationFields(),
to.getAnnotationFields());
if (annotationFieldDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setAnnotationFieldDeltas(annotationFieldDeltas);
}
}
Set<IAnnotationDelta> annotationDeltas = compareAnnotations(from
.getAnnotations(), to.getAnnotations());
if (annotationDeltas != null) {
if (classDelta == null) {
classDelta = new SigClassDefinitionDelta(from, to);
}
classDelta.setAnnotationDeltas(annotationDeltas);
}
return classDelta;
}
private Set<ITypeReferenceDelta<?>> compareInterfaces(
IClassDefinition from, IClassDefinition to) {
Set<ITypeReference> fromClosure = getInterfaceClosure(from);
Set<ITypeReference> toClosure = getInterfaceClosure(to);
Set<ITypeReference> fromInterfaces = from.getInterfaces();
Set<ITypeReference> toInterfaces = to.getInterfaces();
Set<ITypeReferenceDelta<?>> deltas =
new HashSet<ITypeReferenceDelta<?>>();
// check whether all from interfaces are directly or indirectly
// implemented by the to method
for (ITypeReference type : fromInterfaces) {
if (!containsType(type, toInterfaces)) {
if (!(containsType(type, toClosure) /*
* && !containsType(type,
* toInterfaces)
*/)) {
deltas.add(new SigTypeDelta<ITypeReference>(type, null));
}
}
}
// check whether all interfaces to are directly or indirectly
// implemented by the from method
for (ITypeReference type : toInterfaces) {
if (!containsType(type, fromInterfaces)) {
if (!(containsType(type, fromClosure) /*
* && !containsType(type,
* fromInterfaces)
*/)) {
deltas.add(new SigTypeDelta<ITypeReference>(null, type));
}
}
}
return deltas.isEmpty() ? null : deltas;
}
private boolean containsType(ITypeReference type,
Set<ITypeReference> setOfTypes) {
for (ITypeReference other : setOfTypes) {
if (compareType(type, other, false) == null) {
return true;
}
}
return false;
}
private Set<ITypeReference> getInterfaceClosure(IClassDefinition clazz) {
Set<ITypeReference> closure = new HashSet<ITypeReference>();
collectInterfaceClosure(ViewpointAdapter.getReferenceTo(clazz),
closure);
return closure;
}
private void collectInterfaceClosure(ITypeReference clazz,
Set<ITypeReference> closure) {
IClassDefinition classDefinition = getClassDefinition(clazz);
Set<ITypeReference> interfaces = classDefinition.getInterfaces();
if (interfaces == null) {
return;
}
for (ITypeReference interfaze : interfaces) {
closure.add(interfaze);
}
ITypeReference superclass = classDefinition.getSuperClass();
if (superclass != null) {
if (superclass instanceof IParameterizedType) {
collectInterfaceClosure(((IParameterizedType) superclass)
.getRawType(), closure);
} else {
collectInterfaceClosure(superclass, closure);
}
}
for (ITypeReference interfaze : interfaces) {
if (interfaze instanceof IParameterizedType) {
collectInterfaceClosure(((IParameterizedType) interfaze)
.getRawType(), closure);
} else {
collectInterfaceClosure(interfaze, closure);
}
}
}
private Set<IAnnotationDelta> compareAnnotations(Set<IAnnotation> from,
Set<IAnnotation> to) {
return compareSets(from, to,
new SigComparator<IAnnotation, IAnnotationDelta>() {
public IAnnotationDelta createAddRemoveDelta(
IAnnotation from, IAnnotation to) {
return new SigAnnotationDelta(from, to);
}
public boolean considerEqualElement(IAnnotation from,
IAnnotation to) {
return sameClassDefinition(from.getType()
.getClassDefinition(), to.getType()
.getClassDefinition());
}
public IAnnotationDelta createChangedDelta(
IAnnotation from, IAnnotation to) {
return compareAnnotation(from, to);
}
});
}
private Set<IAnnotationFieldDelta> compareAnnotationFields(
Set<IAnnotationField> from, Set<IAnnotationField> to) {
return compareSets(from, to,
new SigComparator<IAnnotationField, IAnnotationFieldDelta>() {
public boolean considerEqualElement(IAnnotationField from,
IAnnotationField to) {
return from.getName().equals(to.getName());
}
public IAnnotationFieldDelta createAddRemoveDelta(
IAnnotationField from, IAnnotationField to) {
return new SigAnnotationFieldDelta(from, to);
}
public IAnnotationFieldDelta createChangedDelta(
IAnnotationField from, IAnnotationField to) {
return compareAnnotationField(from, to);
}
});
}
private Set<IEnumConstantDelta> compareEnumConstants(
Set<IEnumConstant> from, Set<IEnumConstant> to) {
return compareSets(from, to,
new SigComparator<IEnumConstant, IEnumConstantDelta>() {
public boolean considerEqualElement(IEnumConstant from,
IEnumConstant to) {
return from.getName().equals(to.getName());
}
public IEnumConstantDelta createAddRemoveDelta(
IEnumConstant from, IEnumConstant to) {
return new SigEnumConstantDelta(from, to);
}
public IEnumConstantDelta createChangedDelta(
IEnumConstant from, IEnumConstant to) {
return compareEnumConstant(from, to);
}
});
}
private Set<IFieldDelta> compareFields(Set<IField> from, Set<IField> to) {
return compareSets(from, to, new SigComparator<IField, IFieldDelta>() {
public boolean considerEqualElement(IField from, IField to) {
return from.getName().equals(to.getName());
}
public IFieldDelta createAddRemoveDelta(IField from, IField to) {
return new SigFieldDelta(from, to);
}
public IFieldDelta createChangedDelta(IField from, IField to) {
return compareField(from, to);
}
});
}
private Set<IMethodDelta> compareMethods(IClassDefinition from,
IClassDefinition to) {
assert from != null;
assert to != null;
Set<IMethod> toMethods = new HashSet<IMethod>(to.getMethods());
Set<IMethod> toClosure = getMethodClosure(to);
Set<IMethod> fromMethods = new HashSet<IMethod>(from.getMethods());
Set<IMethod> fromClosure = getMethodClosure(from);
Set<IMethodDelta> deltas = new HashSet<IMethodDelta>();
for (IMethod method : fromMethods) {
IMethod compatibleMethod = findCompatibleMethod(method, toMethods);
if (compatibleMethod == null) {
compatibleMethod = findCompatibleMethod(method, toClosure);
if (compatibleMethod == null) {
deltas.add(new SigMethodDelta(method, null));
}
}
if (compatibleMethod != null) {
IMethodDelta delta = compareMethod(method, compatibleMethod);
if (delta != null) {
deltas.add(delta);
}
}
}
for (IMethod method : toMethods) {
IMethod compatibleMethod = findCompatibleMethod(method, fromMethods);
if (compatibleMethod == null) {
compatibleMethod = findCompatibleMethod(method, fromClosure);
if (compatibleMethod == null) {
deltas.add(new SigMethodDelta(null, method));
}
}
}
return deltas.isEmpty() ? null : deltas;
}
private IMethod findCompatibleMethod(IMethod method, Set<IMethod> set) {
for (IMethod methodFromSet : set) {
if (equalsSignature(method, methodFromSet)) {
return methodFromSet;
}
}
return null;
}
private Set<IMethod> getMethodClosure(IClassDefinition clazz) {
Set<IMethod> closure = new HashSet<IMethod>();
collectMethods(new ClassProjection(clazz,
new HashMap<ITypeVariableDefinition, ITypeReference>()),
closure);
return closure;
}
private void collectMethods(IClassDefinition clazz, Set<IMethod> closure) {
if (clazz == null) {
return;
}
if (clazz.getMethods() != null) {
closure.addAll(clazz.getMethods());
}
if (clazz.getSuperClass() != null) {
collectMethods(getClassDefinition(clazz.getSuperClass()), closure);
}
if (clazz.getInterfaces() != null) {
for (ITypeReference interfaze : clazz.getInterfaces()) {
collectMethods(getClassDefinition(interfaze), closure);
}
}
}
private Set<IConstructorDelta> compareConstructors(Set<IConstructor> from,
Set<IConstructor> to) {
return compareSets(from, to,
new SigComparator<IConstructor, IConstructorDelta>() {
public boolean considerEqualElement(IConstructor from,
IConstructor to) {
return equalsSignature(from, to);
}
public IConstructorDelta createAddRemoveDelta(
IConstructor from, IConstructor to) {
return new SigConstructorDelta(from, to);
}
public IConstructorDelta createChangedDelta(
IConstructor from, IConstructor to) {
return compareConstructor(from, to);
}
});
}
// compares names and parameter types
private boolean equalsSignature(IExecutableMember from,
IExecutableMember to) {
if (from.getName().equals(to.getName())) {
return compareTypeSequence(getParameterList(from.getParameters()),
getParameterList(to.getParameters()), true) == null;
}
return false;
}
private List<ITypeReference> getParameterList(List<IParameter> parameters) {
List<ITypeReference> parameterTypes = new LinkedList<ITypeReference>();
for (IParameter parameter : parameters) {
parameterTypes.add(parameter.getType());
}
return parameterTypes;
}
private IAnnotationDelta compareAnnotation(IAnnotation from,
IAnnotation to) {
assert sameClassDefinition(from.getType().getClassDefinition(), to
.getType().getClassDefinition());
Set<IAnnotationElement> fromAnnotationElement =
getNormalizedAnnotationElements(from);
Set<IAnnotationElement> toAnnotationElement =
getNormalizedAnnotationElements(to);
Set<IAnnotationElementDelta> annotationElementDeltas =
compareAnnotationElements(
fromAnnotationElement, toAnnotationElement);
SigAnnotationDelta delta = null;
if (annotationElementDeltas != null) {
delta = new SigAnnotationDelta(from, to);
delta.setAnnotationElementDeltas(annotationElementDeltas);
}
return delta;
}
/**
* Returns the annotation elements for the given annotation. The returned
* set contains all declared elements plus all elements with default values.
*
* @param annotation
* the annotation to return the elements for
* @return the default enriched annotation elements
*/
private Set<IAnnotationElement> getNormalizedAnnotationElements(
IAnnotation annotation) {
Set<IAnnotationElement> elements = new HashSet<IAnnotationElement>(
annotation.getElements());
Set<String> names = new HashSet<String>();
for (IAnnotationElement annotationElement : elements) {
names.add(annotationElement.getDeclaringField().getName());
}
for (IAnnotationField field : annotation.getType().getClassDefinition()
.getAnnotationFields()) {
if (!names.contains(field.getName())) {
SigAnnotationElement sigAnnotationElement =
new SigAnnotationElement();
sigAnnotationElement.setDeclaringField(field);
sigAnnotationElement.setValue(field.getDefaultValue());
elements.add(sigAnnotationElement);
}
}
return elements;
}
private Set<IAnnotationElementDelta> compareAnnotationElements(
Set<IAnnotationElement> from, Set<IAnnotationElement> to) {
return compareSets(from, to,
new SigComparator<IAnnotationElement, IAnnotationElementDelta>() {
public boolean considerEqualElement(
IAnnotationElement from, IAnnotationElement to) {
return from.getDeclaringField().getName().equals(
to.getDeclaringField().getName());
}
public IAnnotationElementDelta createAddRemoveDelta(
IAnnotationElement from, IAnnotationElement to) {
return new SigAnnotationElementDelta(from, to);
}
public IAnnotationElementDelta createChangedDelta(
IAnnotationElement from, IAnnotationElement to) {
return compareAnnotationElement(from, to);
}
});
}
private IAnnotationElementDelta compareAnnotationElement(
IAnnotationElement from, IAnnotationElement to) {
SigAnnotationElementDelta delta = null;
SigValueDelta valueDelta = compareValue(from.getValue(), to.getValue());
if (valueDelta != null) {
delta = new SigAnnotationElementDelta(from, to);
delta.setValueDelta(valueDelta);
}
return delta;
}
/**
* Removes the {@link Modifier#ABSTRACT} modifier.
*/
private Set<Modifier> prepareMethodModifiers(IMethod method) {
Set<Modifier> modifierCopy = new HashSet<Modifier>(method
.getModifiers());
modifierCopy.remove(Modifier.ABSTRACT);
return modifierCopy;
}
private IMethodDelta compareMethod(IMethod from, IMethod to) {
assert from != null && to != null;
SigMethodDelta methodDelta = null;
Set<IModifierDelta> modiferDeltas = compareModifiers(
prepareMethodModifiers(from), prepareMethodModifiers(to));
if (modiferDeltas != null) {
methodDelta = new SigMethodDelta(from, to);
methodDelta.setModifierDeltas(modiferDeltas);
}
Set<IParameterDelta> parameterDeltas = compareParameterSequence(from
.getParameters(), to.getParameters());
if (parameterDeltas != null) {
if (methodDelta == null) {
methodDelta = new SigMethodDelta(from, to);
}
methodDelta.setParameterDeltas(parameterDeltas);
}
Set<IAnnotationDelta> annotationDeltas = compareAnnotations(from
.getAnnotations(), to.getAnnotations());
if (annotationDeltas != null) {
if (methodDelta == null) {
methodDelta = new SigMethodDelta(from, to);
}
methodDelta.setAnnotationDeltas(annotationDeltas);
}
Set<ITypeVariableDefinitionDelta> typeParameterDeltas =
compareTypeVariableSequence(from.getTypeParameters(),
to.getTypeParameters());
if (typeParameterDeltas != null) {
if (methodDelta == null) {
methodDelta = new SigMethodDelta(from, to);
}
methodDelta.setTypeVariableDeltas(typeParameterDeltas);
}
Set<ITypeReferenceDelta<?>> exceptionDeltas = compareTypes(
normalizeExceptions(from.getExceptions()),
normalizeExceptions(to.getExceptions()));
if (exceptionDeltas != null) {
if (methodDelta == null) {
methodDelta = new SigMethodDelta(from, to);
}
methodDelta.setExceptionDeltas(exceptionDeltas);
}
ITypeReferenceDelta<?> returnTypeDelta = compareType(from
.getReturnType(), to.getReturnType(), false);
if (returnTypeDelta != null) {
if (methodDelta == null) {
methodDelta = new SigMethodDelta(from, to);
}
methodDelta.setReturnTypeDelta(returnTypeDelta);
}
return methodDelta;
}
// remove runtime exceptions,
// remove sub types of containing exception
private Set<ITypeReference> normalizeExceptions(
Set<ITypeReference> exceptions) {
Set<ITypeReference> exceptionCopy = new HashSet<ITypeReference>(
exceptions);
Iterator<ITypeReference> iterator = exceptionCopy.iterator();
while (iterator.hasNext()) {
ITypeReference exception = iterator.next();
if (isRuntimeExceptionOrErrorSubtype(exception)) {
iterator.remove();
}
}
exceptionCopy = removeSpecializations(exceptionCopy);
return exceptionCopy;
}
private Set<ITypeReference> removeSpecializations(
Set<ITypeReference> exceptions) {
Set<ITypeReference> exceptionCopy = new HashSet<ITypeReference>(
exceptions);
for (ITypeReference type : exceptions) {
Iterator<ITypeReference> it = exceptionCopy.iterator();
while (it.hasNext()) {
ITypeReference subType = it.next();
if (isSuperClass(getClassDefinition(type),
getClassDefinition(subType))) {
it.remove();
}
}
}
return exceptionCopy;
}
/**
* Returns true if superC is a super class of subC.
*/
private boolean isSuperClass(IClassDefinition superC,
IClassDefinition subC) {
if (superC == null || subC == null) {
return false;
}
if (subC.getSuperClass() == null) {
return false;
} else {
if (getClassDefinition(subC.getSuperClass()).equals(superC)) {
return true;
} else {
return isSuperClass(superC, getClassDefinition(subC
.getSuperClass()));
}
}
}
private boolean isSuperInterface(IClassDefinition superClass,
IClassDefinition subClass) {
if (superClass == null || subClass == null) {
return false;
}
if (subClass.getInterfaces() == null) {
return false;
} else {
if (getClassDefinitions(subClass.getInterfaces()).contains(
superClass)) {
return true;
} else {
for (ITypeReference subType : subClass.getInterfaces()) {
if (isSuperInterface(superClass,
getClassDefinition(subType))) {
return true;
}
}
return false;
}
}
}
private Set<IClassDefinition> getClassDefinitions(
Set<ITypeReference> references) {
Set<IClassDefinition> definitions = new HashSet<IClassDefinition>();
for (ITypeReference ref : references) {
definitions.add(getClassDefinition(ref));
}
return definitions;
}
/**
* Returns null if type is not one of:
* <ul>
* <li>IClassReference</li>
* <li>IParameterizedType</li>
* </ul>
*/
private IClassDefinition getClassDefinition(ITypeReference type) {
assert type != null;
IClassDefinition returnValue = null;
if (type instanceof IClassReference) {
returnValue = ((IClassReference) type).getClassDefinition();
} else if (type instanceof IParameterizedType) {
returnValue = ((IParameterizedType) type).getRawType()
.getClassDefinition();
}
return returnValue;
}
private boolean isRuntimeExceptionOrErrorSubtype(ITypeReference exception) {
IClassDefinition clazz = getClassDefinition(exception);
if (clazz != null) {
if (isRuntimeExceptionOrError(clazz)) {
return true;
} else if (clazz.getSuperClass() != null) {
return isRuntimeExceptionOrErrorSubtype(clazz.getSuperClass());
} else {
return false;
}
}
return false;
}
private boolean isRuntimeExceptionOrError(IClassDefinition exception) {
if (exception == null) {
return false;
}
String packageName = exception.getPackageName();
String className = exception.getName();
if (packageName != null && className != null
&& "java.lang".equals(packageName)) {
return "RuntimeException".equals(className)
|| "Error".equals(className);
}
return false;
}
private IConstructorDelta compareConstructor(IConstructor from,
IConstructor to) {
SigConstructorDelta constructorDelta = null;
Set<IModifierDelta> modiferDeltas = compareModifiers(from
.getModifiers(), to.getModifiers());
if (modiferDeltas != null) {
constructorDelta = new SigConstructorDelta(from, to);
constructorDelta.setModifierDeltas(modiferDeltas);
}
Set<IParameterDelta> parameterDeltas = compareParameterSequence(from
.getParameters(), to.getParameters());
if (parameterDeltas != null) {
if (constructorDelta == null) {
constructorDelta = new SigConstructorDelta(from, to);
}
constructorDelta.setParameterDeltas(parameterDeltas);
}
Set<IAnnotationDelta> annotationDeltas = compareAnnotations(from
.getAnnotations(), to.getAnnotations());
if (annotationDeltas != null) {
if (constructorDelta == null) {
constructorDelta = new SigConstructorDelta(from, to);
}
constructorDelta.setAnnotationDeltas(annotationDeltas);
}
Set<ITypeVariableDefinitionDelta> typeParameterDeltas =
compareTypeVariableSequence(from.getTypeParameters(),
to.getTypeParameters());
if (typeParameterDeltas != null) {
if (constructorDelta == null) {
constructorDelta = new SigConstructorDelta(from, to);
}
constructorDelta.setTypeVariableDeltas(typeParameterDeltas);
}
Set<ITypeReferenceDelta<?>> exceptionDeltas = compareTypes(
normalizeExceptions(from.getExceptions()),
normalizeExceptions(to.getExceptions()));
if (exceptionDeltas != null) {
if (constructorDelta == null) {
constructorDelta = new SigConstructorDelta(from, to);
}
constructorDelta.setExceptionDeltas(exceptionDeltas);
}
return constructorDelta;
}
private Set<IParameterDelta> compareParameterSequence(
List<IParameter> from, List<IParameter> to) {
assert from.size() == to.size();
Set<IParameterDelta> deltas = new HashSet<IParameterDelta>();
Iterator<IParameter> fromIterator = from.iterator();
Iterator<IParameter> toIterator = to.iterator();
while (fromIterator.hasNext() && toIterator.hasNext()) {
IParameterDelta delta = compareParameter(fromIterator.next(),
toIterator.next());
if (delta != null) {
deltas.add(delta);
}
}
return deltas.isEmpty() ? null : deltas;
}
private IParameterDelta compareParameter(IParameter from, IParameter to) {
SigParameterDelta delta = null;
ITypeReferenceDelta<?> typeDelta = compareType(from.getType(), to
.getType(), false);
if (typeDelta != null) {
if (delta == null) {
delta = new SigParameterDelta(from, to);
}
delta.setTypeDelta(typeDelta);
}
Set<IAnnotationDelta> annotationDeltas = compareAnnotations(from
.getAnnotations(), to.getAnnotations());
if (annotationDeltas != null) {
if (delta == null) {
delta = new SigParameterDelta(from, to);
}
delta.setAnnotationDeltas(annotationDeltas);
}
return delta;
}
private Set<ITypeVariableDefinitionDelta> compareTypeVariableSequence(
List<ITypeVariableDefinition> from,
List<ITypeVariableDefinition> to) {
Set<ITypeVariableDefinitionDelta> deltas =
new HashSet<ITypeVariableDefinitionDelta>();
if (from.size() != to.size()) {
for (ITypeVariableDefinition fromVariable : from) {
deltas.add(new SigTypeVariableDefinitionDelta(fromVariable,
null));
}
for (ITypeVariableDefinition toVariable : to) {
deltas
.add(new SigTypeVariableDefinitionDelta(null,
toVariable));
}
}
Iterator<ITypeVariableDefinition> fromIterator = from.iterator();
Iterator<ITypeVariableDefinition> toIterator = to.iterator();
while (fromIterator.hasNext() && toIterator.hasNext()) {
ITypeVariableDefinitionDelta delta = compareTypeVariableDefinition(
fromIterator.next(), toIterator.next());
if (delta != null) {
deltas.add(delta);
}
}
return deltas.isEmpty() ? null : deltas;
}
private ITypeVariableDefinitionDelta compareTypeVariableDefinition(
ITypeVariableDefinition from, ITypeVariableDefinition to) {
IGenericDeclarationDelta declarationDelta = compareGenericDeclaration(
from, to);
if (declarationDelta != null) {
SigTypeVariableDefinitionDelta delta =
new SigTypeVariableDefinitionDelta(from, to);
delta.setGenericDeclarationDelta(declarationDelta);
return delta;
}
IUpperBoundsDelta upperBoundDelta = compareUpperBounds(from
.getUpperBounds(), to.getUpperBounds());
if (upperBoundDelta != null) {
SigTypeVariableDefinitionDelta delta =
new SigTypeVariableDefinitionDelta(from, to);
delta.setUpperBoundsDelta(upperBoundDelta);
return delta;
}
return null;
}
private ITypeReferenceDelta<ITypeVariableReference> compareTypeVariableReference(
ITypeVariableReference from, ITypeVariableReference to) {
IGenericDeclarationDelta declarationDelta = compareGenericDeclaration(
from.getTypeVariableDefinition(), to
.getTypeVariableDefinition());
if (declarationDelta != null) {
SigTypeVariableReferenceDelta delta =
new SigTypeVariableReferenceDelta(from, to);
delta.setGenericDeclarationDelta(declarationDelta);
return delta;
}
return null;
}
private Set<IModifierDelta> compareModifiers(Set<Modifier> from,
Set<Modifier> to) {
return compareSets(from, to,
new SigComparator<Modifier, IModifierDelta>() {
public boolean considerEqualElement(Modifier from,
Modifier to) {
return from.equals(to);
}
public IModifierDelta createAddRemoveDelta(Modifier from,
Modifier to) {
return new SigModifierDelta(from, to);
}
public IModifierDelta createChangedDelta(Modifier from,
Modifier to) {
return null;
}
});
}
private IFieldDelta compareField(IField from, IField to) {
SigFieldDelta fieldDelta = null;
Set<IModifierDelta> modiferDeltas = compareModifiers(from
.getModifiers(), to.getModifiers());
if (modiferDeltas != null) {
fieldDelta = new SigFieldDelta(from, to);
fieldDelta.setModifierDeltas(modiferDeltas);
}
Set<IAnnotationDelta> annotationDeltas = compareAnnotations(from
.getAnnotations(), to.getAnnotations());
if (annotationDeltas != null) {
if (fieldDelta == null) {
fieldDelta = new SigFieldDelta(from, to);
}
fieldDelta.setAnnotationDeltas(annotationDeltas);
}
ITypeReferenceDelta<?> typeDelta = compareType(from.getType(), to
.getType(), false);
if (typeDelta != null) {
if (fieldDelta == null) {
fieldDelta = new SigFieldDelta(from, to);
}
fieldDelta.setTypeDelta(typeDelta);
}
return fieldDelta;
}
private IEnumConstantDelta compareEnumConstant(IEnumConstant from,
IEnumConstant to) {
SigEnumConstantDelta enumConstantDelta = null;
Set<IModifierDelta> modiferDeltas = compareModifiers(from
.getModifiers(), to.getModifiers());
if (modiferDeltas != null) {
enumConstantDelta = new SigEnumConstantDelta(from, to);
enumConstantDelta.setModifierDeltas(modiferDeltas);
}
Set<IAnnotationDelta> annotationDeltas = compareAnnotations(from
.getAnnotations(), to.getAnnotations());
if (annotationDeltas != null) {
if (enumConstantDelta == null) {
enumConstantDelta = new SigEnumConstantDelta(from, to);
}
enumConstantDelta.setAnnotationDeltas(annotationDeltas);
}
ITypeReferenceDelta<?> typeDelta = compareType(from.getType(), to
.getType(), false);
if (typeDelta != null) {
if (enumConstantDelta == null) {
enumConstantDelta = new SigEnumConstantDelta(from, to);
}
enumConstantDelta.setTypeDelta(typeDelta);
}
// FIXME ordinal not supported in dex
// ValueDelta ordinalDelta = compareValue(from.getOrdinal(),
// to.getOrdinal());
// if (ordinalDelta != null) {
// if (enumConstantDelta == null) {
// enumConstantDelta = new SigEnumConstantDelta(from, to);
// }
// enumConstantDelta.setOrdinalDelta(ordinalDelta);
// }
return enumConstantDelta;
}
private IAnnotationFieldDelta compareAnnotationField(IAnnotationField from,
IAnnotationField to) {
SigAnnotationFieldDelta annotationFieldDelta = null;
Set<IModifierDelta> modiferDeltas = compareModifiers(from
.getModifiers(), to.getModifiers());
if (modiferDeltas != null) {
annotationFieldDelta = new SigAnnotationFieldDelta(from, to);
annotationFieldDelta.setModifierDeltas(modiferDeltas);
}
Set<IAnnotationDelta> annotationDeltas = compareAnnotations(from
.getAnnotations(), to.getAnnotations());
if (annotationDeltas != null) {
if (annotationFieldDelta == null) {
annotationFieldDelta = new SigAnnotationFieldDelta(from, to);
}
annotationFieldDelta.setAnnotationDeltas(annotationDeltas);
}
ITypeReferenceDelta<?> typeDelta = compareType(from.getType(), to
.getType(), false);
if (typeDelta != null) {
if (annotationFieldDelta == null) {
annotationFieldDelta = new SigAnnotationFieldDelta(from, to);
}
annotationFieldDelta.setTypeDelta(typeDelta);
}
IValueDelta defaultValueDelta = compareValue(from.getDefaultValue(), to
.getDefaultValue());
if (defaultValueDelta != null) {
if (annotationFieldDelta == null) {
annotationFieldDelta = new SigAnnotationFieldDelta(from, to);
}
annotationFieldDelta.setDefaultValueDelta(defaultValueDelta);
}
return annotationFieldDelta;
}
private SigValueDelta compareValue(Object from, Object to) {
// same value
if (from == null && to == null) {
return null;
}
// one of both is null and other is not
if (from == null || to == null) {
return new SigValueDelta(from, to);
}
SigValueDelta delta = null;
// different types
if (from.getClass() == to.getClass()) {
if (from.getClass().isArray()) {
Object[] fromArray = (Object[]) from;
Object[] toArray = (Object[]) from;
if (!Arrays.equals(fromArray, toArray)) {
delta = new SigValueDelta(from, to);
}
} else if (from instanceof IEnumConstant) {
IEnumConstantDelta enumConstantDelta = compareEnumConstant(
(IEnumConstant) from, (IEnumConstant) to);
if (enumConstantDelta != null) {
delta = new SigValueDelta(from, to);
}
} else if (from instanceof IAnnotation) {
IAnnotationDelta annotationDelta = compareAnnotation(
(IAnnotation) from, (IAnnotation) to);
if (annotationDelta != null) {
delta = new SigValueDelta(from, to);
}
} else if (from instanceof IField) {
IFieldDelta fieldDelta = compareField((IField) from,
(IField) to);
if (fieldDelta != null) {
delta = new SigValueDelta(from, to);
}
} else if (from instanceof ITypeReference) {
ITypeReferenceDelta<? extends ITypeReference> typeDelta =
compareType((ITypeReference) from, (ITypeReference) to,
false);
if (typeDelta != null) {
delta = new SigValueDelta(from, to);
}
} else if (!from.equals(to)) {
delta = new SigValueDelta(from, to);
}
} else if (!(from == null && to == null)) {
delta = new SigValueDelta(from, to);
}
return delta;
}
private boolean considerEqualTypes(ITypeReference from, ITypeReference to) {
assert from != null && to != null;
if (implementInterface(from, to, IPrimitiveType.class)) {
return comparePrimitiveType((IPrimitiveType) from,
(IPrimitiveType) to) == null;
}
if (implementInterface(from, to, IClassReference.class)) {
return sameClassDefinition(((IClassReference) from)
.getClassDefinition(), ((IClassReference) to)
.getClassDefinition());
}
if (implementInterface(from, to, IArrayType.class)) {
return considerEqualTypes(((IArrayType) from).getComponentType(),
((IArrayType) to).getComponentType());
}
if (implementInterface(from, to, IParameterizedType.class)) {
return compareClassReference(((IParameterizedType) from)
.getRawType(), ((IParameterizedType) to)
.getRawType()) == null;
}
if (implementInterface(from, to, ITypeVariableReference.class)) {
return compareTypeVariableReference((ITypeVariableReference) from,
(ITypeVariableReference) to) == null;
}
return false;
}
private Set<ITypeReference> fromComparison = new HashSet<ITypeReference>();
private Set<ITypeReference> toComparison = new HashSet<ITypeReference>();
private boolean areInComparison(ITypeReference from, ITypeReference to) {
return fromComparison.contains(from) && toComparison.contains(to);
}
private void markInComparison(ITypeReference from, ITypeReference to) {
fromComparison.add(from);
toComparison.add(to);
}
private void markFinishedComparison(ITypeReference from,
ITypeReference to) {
fromComparison.remove(from);
toComparison.remove(to);
}
private ITypeReferenceDelta<? extends ITypeReference> compareType(
ITypeReference from, ITypeReference to, boolean acceptErasedTypes) {
if (from == null && to == null) {
return null;
}
if ((from == null && to != null) || (from != null && to == null)) {
return new SigTypeDelta<ITypeReference>(from, to);
}
if (areInComparison(from, to)) {
return null;
}
try {
markInComparison(from, to);
if (implementInterface(from, to, IPrimitiveType.class)) {
return comparePrimitiveType((IPrimitiveType) from,
(IPrimitiveType) to);
}
if (implementInterface(from, to, IClassReference.class)) {
return compareClassReference((IClassReference) from,
(IClassReference) to);
}
if (implementInterface(from, to, IArrayType.class)) {
return compareArrayType((IArrayType) from, (IArrayType) to);
}
if (implementInterface(from, to, IParameterizedType.class)) {
return compareParameterizedType((IParameterizedType) from,
(IParameterizedType) to, acceptErasedTypes);
}
if (implementInterface(from, to, ITypeVariableReference.class)) {
return compareTypeVariableReference(
(ITypeVariableReference) from,
(ITypeVariableReference) to);
}
if (implementInterface(from, to, IWildcardType.class)) {
return compareWildcardType((IWildcardType) from,
(IWildcardType) to);
}
if (acceptErasedTypes) {
if (isGeneric(from) && !isGeneric(to)) {
return compareType(getErasedType(from), to, false);
}
if (!isGeneric(from) && isGeneric(to)) {
return compareType(from, getErasedType(to), false);
}
}
return new SigTypeDelta<ITypeReference>(from, to);
} finally {
markFinishedComparison(from, to);
}
}
private boolean isGeneric(ITypeReference reference) {
if (reference instanceof IParameterizedType
|| reference instanceof ITypeVariableReference
|| reference instanceof IWildcardType) {
return true;
}
if (reference instanceof IArrayType) {
return isGeneric(((IArrayType) reference).getComponentType());
}
return false;
}
private ITypeReference getErasedType(ITypeReference reference) {
if (reference instanceof IParameterizedType) {
return ((IParameterizedType) reference).getRawType();
}
if (reference instanceof ITypeVariableReference) {
ITypeVariableDefinition typeVariableDefinition =
((ITypeVariableReference) reference)
.getTypeVariableDefinition();
return getErasedType(
typeVariableDefinition.getUpperBounds().get(0));
}
if (reference instanceof IWildcardType) {
return getErasedType(((IWildcardType) reference).getUpperBounds()
.get(0));
}
if (reference instanceof IArrayType) {
// FIXME implement with erasure projection?
return new SigArrayType(getErasedType(((IArrayType) reference)
.getComponentType()));
}
if (reference instanceof IPrimitiveType) {
return reference;
}
if (reference instanceof IClassReference) {
return reference;
}
throw new IllegalArgumentException("Unexpected type: " + reference);
}
private boolean implementInterface(ITypeReference from, ITypeReference to,
Class<?> check) {
return check.isAssignableFrom(from.getClass())
&& check.isAssignableFrom(to.getClass());
}
private IWildcardTypeDelta compareWildcardType(IWildcardType from,
IWildcardType to) {
SigWildcardTypeDelta delta = null;
ITypeReference fromLowerBound = from.getLowerBound();
ITypeReference toLowerBound = to.getLowerBound();
ITypeReferenceDelta<?> lowerBoundDelta = compareType(fromLowerBound,
toLowerBound, false);
if (lowerBoundDelta != null) {
delta = new SigWildcardTypeDelta(from, to);
delta.setLowerBoundDelta(lowerBoundDelta);
}
IUpperBoundsDelta upperBoundsDelta = compareUpperBounds(from
.getUpperBounds(), to.getUpperBounds());
if (upperBoundsDelta != null) {
if (delta == null) {
delta = new SigWildcardTypeDelta(from, to);
}
delta.setUpperBoundDelta(upperBoundsDelta);
}
return delta;
}
private IGenericDeclarationDelta compareGenericDeclaration(
ITypeVariableDefinition fromVariable,
ITypeVariableDefinition toVariable) {
IGenericDeclarationDelta delta = null;
IGenericDeclaration from = fromVariable.getGenericDeclaration();
IGenericDeclaration to = toVariable.getGenericDeclaration();
if (from != null && to != null) {
if (from.getClass() != to.getClass()) {
delta = new SigGenericDeclarationDelta(from, to);
} else if (from instanceof IClassDefinition) {
IClassDefinition fromDeclaringClass = (IClassDefinition) from;
IClassDefinition toDeclaringClass = (IClassDefinition) to;
if (!sameClassDefinition(fromDeclaringClass,
toDeclaringClass)) {
delta = new SigGenericDeclarationDelta(from, to);
}
} else if (from instanceof IConstructor) {
IConstructor fromConstructor = (IConstructor) from;
IConstructor toConstructor = (IConstructor) from;
String fromConstructorName = fromConstructor.getName();
String fromClassName = fromConstructor.getDeclaringClass()
.getQualifiedName();
String toConstructorName = toConstructor.getName();
String toClassName = toConstructor.getDeclaringClass()
.getQualifiedName();
if ((!fromConstructorName.equals(toConstructorName))
|| (!fromClassName.equals(toClassName))) {
delta = new SigGenericDeclarationDelta(from, to);
}
} else if (from instanceof IMethod) {
IMethod fromMethod = (IMethod) from;
IMethod toMethod = (IMethod) from;
String fromConstructorName = fromMethod.getName();
String fromClassName = fromMethod.getDeclaringClass()
.getQualifiedName();
String toConstructorName = toMethod.getName();
String toClassName = toMethod.getDeclaringClass()
.getQualifiedName();
if ((!fromConstructorName.equals(toConstructorName))
|| (!fromClassName.equals(toClassName))) {
delta = new SigGenericDeclarationDelta(from, to);
}
} else {
throw new IllegalStateException("Invlaid eclaration site: "
+ from);
}
// check position
int fromPosition = getPositionOf(fromVariable, from);
int toPosition = getPositionOf(toVariable, to);
if (fromPosition != toPosition) {
delta = new SigGenericDeclarationDelta(from, to);
}
} else {
// one of both is null
delta = new SigGenericDeclarationDelta(from, to);
}
return delta;
}
private int getPositionOf(ITypeVariableDefinition variable,
IGenericDeclaration declaration) {
return declaration.getTypeParameters().indexOf(variable);
}
private IUpperBoundsDelta compareUpperBounds(List<ITypeReference> from,
List<ITypeReference> to) {
if (from.isEmpty() && to.isEmpty()) {
return null;
}
SigUpperBoundsDelta delta = null;
ITypeReference fromFirstUpperBound = from.get(0);
ITypeReference toFirstUpperBound = to.get(0);
ITypeReferenceDelta<?> firstUpperBoundDelta = compareType(
fromFirstUpperBound, toFirstUpperBound, false);
if (firstUpperBoundDelta != null) {
delta = new SigUpperBoundsDelta(from, to);
delta.setFirstUpperBoundDelta(firstUpperBoundDelta);
} else {
// normalize
Set<ITypeReference> normalizedfrom = removeGeneralizations(
new HashSet<ITypeReference>(from));
Set<ITypeReference> normalizedto = removeGeneralizations(
new HashSet<ITypeReference>(to));
Set<ITypeReferenceDelta<?>> remainingUpperBoundsDelta =
compareTypes(normalizedfrom, normalizedto);
if (remainingUpperBoundsDelta != null) {
delta = new SigUpperBoundsDelta(from, to);
delta.setRemainingUpperBoundDeltas(remainingUpperBoundsDelta);
}
}
return delta;
}
private Set<ITypeReference> removeGeneralizations(
Set<ITypeReference> bounds) {
Set<ITypeReference> boundsCopy = new HashSet<ITypeReference>(bounds);
for (ITypeReference type : bounds) {
Iterator<ITypeReference> it = boundsCopy.iterator();
while (it.hasNext()) {
ITypeReference superType = it.next();
if (isSuperClass(getClassDefinition(superType),
getClassDefinition(type))
|| isSuperInterface(getClassDefinition(superType),
getClassDefinition(type))) {
it.remove();
}
}
}
return boundsCopy;
}
private IParameterizedTypeDelta compareParameterizedType(
IParameterizedType from, IParameterizedType to,
boolean ignoreTypeArguments) {
SigParameterizedTypeDelta delta = null;
// check raw type
ITypeReferenceDelta<?> rawTypeDelta = compareType(from.getRawType(), to
.getRawType(), false);
if (rawTypeDelta != null) {
delta = new SigParameterizedTypeDelta(from, to);
delta.setRawTypeDelta(rawTypeDelta);
} else {
// check owner type
ITypeReferenceDelta<?> ownerTypeDelta = compareType(from
.getOwnerType(), to.getOwnerType(), false);
if (ownerTypeDelta != null) {
delta = new SigParameterizedTypeDelta(from, to);
delta.setOwnerTypeDelta(ownerTypeDelta);
} else {
// check argument type
if (!ignoreTypeArguments) {
Set<ITypeReferenceDelta<?>> argumentTypeDeltas =
compareTypeSequence(from.getTypeArguments(),
to.getTypeArguments(), false);
if (argumentTypeDeltas != null) {
delta = new SigParameterizedTypeDelta(from, to);
delta.setArgumentTypeDeltas(argumentTypeDeltas);
}
}
}
}
return delta;
}
private Set<ITypeReferenceDelta<? extends ITypeReference>> compareTypeSequence(
List<ITypeReference> from, List<ITypeReference> to,
boolean ignoreTypeArguments) {
Set<ITypeReferenceDelta<?>> deltas =
new HashSet<ITypeReferenceDelta<?>>();
if (from.size() != to.size()) {
for (ITypeReference type : from) {
deltas.add(new SigTypeDelta<ITypeReference>(type, null));
}
for (ITypeReference type : to) {
deltas.add(new SigTypeDelta<ITypeReference>(null, type));
}
return deltas;
}
Iterator<? extends ITypeReference> fromIterator = from.iterator();
Iterator<? extends ITypeReference> toIterator = to.iterator();
while (fromIterator.hasNext() && toIterator.hasNext()) {
ITypeReferenceDelta<?> delta = compareType(fromIterator.next(),
toIterator.next(), ignoreTypeArguments);
if (delta != null) {
deltas.add(delta);
}
}
return deltas.isEmpty() ? null : deltas;
}
private Set<ITypeReferenceDelta<? extends ITypeReference>> compareTypes(
Set<ITypeReference> from, Set<ITypeReference> to) {
return compareSets(from, to,
new SigComparator<ITypeReference, ITypeReferenceDelta<? extends ITypeReference>>() {
public ITypeReferenceDelta<? extends ITypeReference> createAddRemoveDelta(
ITypeReference from, ITypeReference to) {
return new SigTypeDelta<ITypeReference>(from, to);
}
public boolean considerEqualElement(ITypeReference from,
ITypeReference to) {
return considerEqualTypes(from, to);
}
public ITypeReferenceDelta<? extends ITypeReference> createChangedDelta(
ITypeReference from, ITypeReference to) {
return compareType(from, to, false);
}
});
}
private static interface SigComparator<T, S extends IDelta<? extends T>> {
boolean considerEqualElement(T from, T to);
S createChangedDelta(T from, T to);
/**
* If null is returned, it will be ignored.
*/
S createAddRemoveDelta(T from, T to);
}
private <T, S extends IDelta<? extends T>> Set<S> compareSets(Set<T> from,
Set<T> to, SigComparator<T, S> comparator) {
Set<T> toCopy = new HashSet<T>(to);
Set<S> deltas = new HashSet<S>();
for (T fromType : from) {
Iterator<T> toIterator = toCopy.iterator();
boolean equals = false;
boolean hasNext = toIterator.hasNext();
while (hasNext && !equals) {
T toElement = toIterator.next();
equals = comparator.considerEqualElement(fromType, toElement);
if (equals) {
S compare = comparator.createChangedDelta(fromType,
toElement);
if (compare != null) {
deltas.add(compare);
}
}
hasNext = toIterator.hasNext();
}
if (equals) {
toIterator.remove();
} else {
S delta = comparator.createAddRemoveDelta(fromType, null);
if (delta != null) {
deltas.add(delta);
}
}
}
for (T type : toCopy) {
S delta = comparator.createAddRemoveDelta(null, type);
if (delta != null) {
deltas.add(delta);
}
}
return deltas.isEmpty() ? null : deltas;
}
private ITypeReferenceDelta<?> compareArrayType(IArrayType from,
IArrayType to) {
ITypeReferenceDelta<?> componentTypeDelta = compareType(from
.getComponentType(), to.getComponentType(), false);
if (componentTypeDelta != null) {
SigArrayTypeDelta delta = new SigArrayTypeDelta(from, to);
delta.setComponentTypeDelta(componentTypeDelta);
return delta;
}
return null;
}
private ITypeReferenceDelta<IClassReference> compareClassReference(
IClassReference fromRef, IClassReference toRef) {
IClassDefinition from = fromRef.getClassDefinition();
IClassDefinition to = toRef.getClassDefinition();
if (!sameClassDefinition(from, to)) {
return new SigClassReferenceDelta(fromRef, toRef);
}
return null;
}
private boolean sameClassDefinition(IClassDefinition from,
IClassDefinition to) {
boolean sameName = from.getName().equals(to.getName());
boolean samePackage = from.getPackageName().equals(to.getPackageName());
Kind fromKind = from.getKind();
Kind toKind = to.getKind();
boolean sameKind = (fromKind == null || toKind == null)
|| fromKind.equals(toKind);
return sameName && samePackage && sameKind;
}
private IPrimitiveTypeDelta comparePrimitiveType(IPrimitiveType from,
IPrimitiveType to) {
if (!from.equals(to)) {
return new SigPrimitiveTypeDelta(from, to);
}
return null;
}
}
|
9232d3b8dcebc8b4dd8db02c1bcaea51bb872fba | 3,418 | java | Java | src/test/java/org/okky/reply/domain/model/ReplyTest.java | coding8282/okky-reply | d6036809a702be197197d408d3307e1e4249591d | [
"MIT"
] | 1 | 2018-06-06T09:06:10.000Z | 2018-06-06T09:06:10.000Z | src/test/java/org/okky/reply/domain/model/ReplyTest.java | coding8282/okky-reply | d6036809a702be197197d408d3307e1e4249591d | [
"MIT"
] | null | null | null | src/test/java/org/okky/reply/domain/model/ReplyTest.java | coding8282/okky-reply | d6036809a702be197197d408d3307e1e4249591d | [
"MIT"
] | null | null | null | 28.247934 | 78 | 0.653306 | 996,369 | package org.okky.reply.domain.model;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.okky.reply.TestMother;
import org.okky.reply.domain.event.DomainEventPublisher;
import org.okky.share.event.ReplyPinned;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
@RunWith(PowerMockRunner.class)
@PrepareForTest(DomainEventPublisher.class)
public class ReplyTest extends TestMother {
@Before
public void setUp() {
PowerMockito.mockStatic(DomainEventPublisher.class);
}
@Test
public void new_최초에는_pin_상태가_아님() {
Reply reply = fixture();
assertFalse("최초 생성시에는 답글이 고정된 상태가 아니다.", reply.pinned());
}
@Test
public void pin_고정_후에는_상태가_true여야_하며_날짜도_null이_아니어야_함() {
PowerMockito.doNothing().when(DomainEventPublisher.class);
DomainEventPublisher.fire(any(ReplyPinned.class));
Reply reply = fixture();
reply.pin("m");
assertTrue("고정하였으므로 상태는 true여야 한다.", reply.pinned());
PowerMockito.verifyStatic(DomainEventPublisher.class);
DomainEventPublisher.fire(any(ReplyPinned.class));
}
@Test
public void pin_이미_고정_상태에서_여러번_고정하면_상태가_true여야_하며_날짜도_null이_아니어야_함() {
PowerMockito.doNothing().when(DomainEventPublisher.class);
DomainEventPublisher.fire(any(ReplyPinned.class));
Reply reply = fixture();
reply.pin("m");
reply.pin("m");
reply.pin("m");
reply.pin("m");
assertTrue("고정하였으므로 상태는 true여야 한다.", reply.pinned());
PowerMockito.verifyStatic(DomainEventPublisher.class, times(4));
DomainEventPublisher.fire(any(ReplyPinned.class));
}
@Test
public void unpin_고정_해제_후에는_상태가_false여야_하며_날짜도_null이어야_함() {
Reply reply = fixture();
reply.unpin();
assertFalse("고정한 상태가 아니므로 false여야 한다.", reply.pinned());
}
@Test
public void unpin_고정_상태가_아닌데_여러_번_고정_해제하면_상태가_false여야_하며_날짜도_null이어야_함() {
Reply reply = fixture();
reply.unpin();
reply.unpin();
reply.unpin();
reply.unpin();
assertFalse("고정한 상태가 아니므로 false여야 한다.", reply.pinned());
}
@Test
public void choice_토글_확인() {
Reply reply = fixture();
assertFalse(reply.accepted());
reply.toggleAccept();
assertTrue(reply.accepted());
reply.toggleAccept();
assertFalse(reply.accepted());
}
@Test
public void 수정_확인() {
Reply reply = fixture();
reply.modify("답변 드립니다2222");
assertThat(reply.getBody(), is("답변 드립니다2222"));
}
@Test
public void 채택_전에는_날짜가_null이고_후에는_날짜_존재_확인() {
Reply reply = fixture();
assertNull(reply.getAcceptedOn());
reply.toggleAccept();
assertNotNull(reply.getAcceptedOn());
}
// ----------------------------
private Reply fixture() {
String id = "a1";
String articleId = "a03";
String body = "답변 드립니다..";
String replierId = "m-334455";
String replierName = "coding8282";
return new Reply(articleId, body, replierId, replierName);
}
} |
9232d3f166baa151a4810729eeea29a84d152834 | 4,780 | java | Java | org.openntf.xpt.oneui/src/org/openntf/xpt/oneui/kernel/NamePickerProcessor.java | OpenNTF/XPagesToolk | 570af080d2704b53b483350a4022ac7240348e20 | [
"Apache-2.0"
] | 2 | 2015-10-30T12:38:37.000Z | 2017-12-21T06:54:45.000Z | org.openntf.xpt.oneui/src/org/openntf/xpt/oneui/kernel/NamePickerProcessor.java | OpenNTF/XPagesToolk | 570af080d2704b53b483350a4022ac7240348e20 | [
"Apache-2.0"
] | 5 | 2015-02-26T11:58:31.000Z | 2018-01-10T18:17:46.000Z | org.openntf.xpt.oneui/src/org/openntf/xpt/oneui/kernel/NamePickerProcessor.java | OpenNTF/XPagesToolk | 570af080d2704b53b483350a4022ac7240348e20 | [
"Apache-2.0"
] | 5 | 2015-08-15T15:11:15.000Z | 2020-03-11T13:54:19.000Z | 32.739726 | 145 | 0.72887 | 996,370 | /**
* Copyright 2013, WebGate Consulting AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.openntf.xpt.oneui.kernel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.DocumentCollection;
import lotus.domino.NotesException;
import lotus.domino.View;
import lotus.domino.ViewEntry;
import lotus.domino.ViewEntryCollection;
import org.openntf.xpt.core.XPTRuntimeException;
import org.openntf.xpt.core.utils.DatabaseProvider;
import org.openntf.xpt.core.utils.logging.LoggerFactory;
import org.openntf.xpt.oneui.component.UINamePicker;
import com.ibm.commons.util.StringUtil;
public enum NamePickerProcessor implements INamePickerValueService {
INSTANCE;
/* (non-Javadoc)
* @see org.openntf.xpt.oneui.kernel.INamePickerValueService#getTypeAheaderNE(org.openntf.xpt.oneui.component.UINamePicker, java.lang.String)
*/
@Override
public List<NameEntry> getTypeAheadValues(UINamePicker uiNp, String strSearch) throws NotesException {
Database db = DatabaseProvider.INSTANCE.getDatabase(uiNp.getDatabase(), false);
View vw = db.getView(uiNp.getView());
DocumentCollection docCollection;
String strFTSearch = uiNp.buildFTSearch(strSearch);
if (db.isFTIndexed() && !StringUtil.isEmpty(strFTSearch)) {
try {
db.updateFTIndex(true);
vw.FTSearch(strFTSearch);
ViewEntryCollection vecEntries = vw.getAllEntries();
ViewEntry entryNext = vecEntries.getFirstEntry();
docCollection = vw.getAllDocumentsByKey("EMPTY_COLLECTION"); // Initalize
// empty
// Collection
while (entryNext != null) {
ViewEntry entry = entryNext;
entryNext = vecEntries.getNextEntry(entry);
docCollection.addDocument(entry.getDocument());
entry.recycle();
}
vecEntries.recycle();
} catch (Exception e) {
LoggerFactory.logError(getClass(), "Error during ftSearch access", e);
docCollection = vw.getAllDocumentsByKey(strSearch, false);
}
} else {
docCollection = vw.getAllDocumentsByKey(strSearch, false);
}
List<NameEntry> lstNameEntries = new ArrayList<NameEntry>();
Document docNext = docCollection.getFirstDocument();
while (docNext != null) {
Document docProcess = docNext;
docNext = docCollection.getNextDocument();
NameEntry nam = uiNp.getDocumentEntryRepresentation(docProcess);
if (nam != null) {
lstNameEntries.add(nam);
nam.buildResultLineHL(strSearch);
}
docProcess.recycle();
}
Collections.sort(lstNameEntries, new Comparator<NameEntry>() {
@Override
public int compare(NameEntry o1, NameEntry o2) {
return o1.getLabel().compareTo(o2.getLabel());
}
});
return lstNameEntries;
}
/* (non-Javadoc)
* @see org.openntf.xpt.oneui.kernel.INamePickerValueService#getDislplayLabels(org.openntf.xpt.oneui.component.UINamePicker, java.lang.String[])
*/
@Override
public Map<String, String> getDislplayLabels(UINamePicker uiNp, String[] values) {
Map<String, String> hsRC = new HashMap<String, String>();
try {
Database db = DatabaseProvider.INSTANCE.getDatabase(uiNp.getDatabase(), false);
buildDisplayLabelsFromDatabase(uiNp, values, hsRC, db);
DatabaseProvider.INSTANCE.handleRecylce(db);
} catch (Exception ex) {
throw new XPTRuntimeException("getDisplayLables", ex);
}
return hsRC;
}
public void buildDisplayLabelsFromDatabase(UINamePicker uiNp, String[] values, Map<String, String> hsRC, Database db) throws NotesException {
View vw = null;
if (StringUtil.isEmpty(uiNp.getLookupView())) {
vw = db.getView(uiNp.getView());
} else {
vw = db.getView(uiNp.getLookupView());
}
for (String strValue : values) {
String strLabel = getLabel(vw, strValue, uiNp);
hsRC.put(strValue, strLabel);
}
if (vw != null) {
vw.recycle();
}
}
private String getLabel(View vw, String strValue, UINamePicker uiNp) throws NotesException {
String rc = strValue;
if (vw != null) {
Document docRC = vw.getDocumentByKey(strValue, true);
if (docRC != null) {
rc = uiNp.getDisplayLableValue(docRC);
docRC.recycle();
}
}
return rc;
}
}
|
9232d414a71ed782c9fc44c6bb189fc37ef88e3a | 8,621 | java | Java | src/main/java/uk/ac/sussex/gdsc/smlm/ij/IJImageSource.java | aherbert/gdsc-smlm | 193431b9ba2c6e6a2b901c7c3697039aaa00be8c | [
"BSL-1.0"
] | 8 | 2018-12-07T00:40:44.000Z | 2020-07-27T14:10:44.000Z | src/main/java/uk/ac/sussex/gdsc/smlm/ij/IJImageSource.java | aherbert/gdsc-smlm | 193431b9ba2c6e6a2b901c7c3697039aaa00be8c | [
"BSL-1.0"
] | 3 | 2020-11-17T18:01:09.000Z | 2021-05-18T19:10:34.000Z | src/main/java/uk/ac/sussex/gdsc/smlm/ij/IJImageSource.java | aherbert/gdsc-smlm | 193431b9ba2c6e6a2b901c7c3697039aaa00be8c | [
"BSL-1.0"
] | 2 | 2019-08-13T06:16:24.000Z | 2020-01-29T21:23:10.000Z | 27.63141 | 97 | 0.641109 | 996,371 | /*-
* #%L
* Genome Damage and Stability Centre SMLM ImageJ Plugins
*
* Software for single molecule localisation microscopy (SMLM)
* %%
* Copyright (C) 2011 - 2020 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.smlm.ij;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.io.FileInfo;
import ij.measure.Calibration;
import ij.process.ImageProcessor;
import java.awt.Rectangle;
import uk.ac.sussex.gdsc.smlm.results.ImageSource;
/**
* Represent an ImageJ image as a results source. Supports all greyscale images. Only processes
* channel 0 of 32-bit colour images.
*/
// This is allowed to support backwards serialisation compatibility
// CHECKSTYLE.OFF: AbbreviationAsWordInName
public class IJImageSource extends ImageSource {
// CHECKSTYLE.ON: AbbreviationAsWordInName
@XStreamOmitField
private int slice;
private int singleFrame;
private int extraFrames;
@XStreamOmitField
private Object[] imageArray;
@XStreamOmitField
private ImageStack imageStack;
private String path;
/**
* Create a new image source using the name of the image file.
*
* @param name the name
*/
public IJImageSource(String name) {
super(name);
}
/**
* Create a new image source using the path to the image file.
*
* @param name the name
* @param path the path
*/
public IJImageSource(String name, String path) {
super(name);
this.path = path;
}
/**
* Create a new image source from an ImagePlus.
*
* @param imp the imp
*/
public IJImageSource(ImagePlus imp) {
super(imp.getTitle());
initialise(imp);
}
private boolean initialise(ImagePlus imp) {
imageArray = null;
imageStack = null;
if (imp == null) {
return false;
}
final ImageStack s = imp.getImageStack();
if (s.isVirtual()) {
// We must use the image stack to get the image data for virtual images
imageStack = s;
} else {
// We can access the image array directly
imageArray = s.getImageArray();
}
width = imp.getWidth();
height = imp.getHeight();
// Store the number of valid frames
if (singleFrame > 0) {
frames = 1 + this.extraFrames;
} else {
frames = imp.getStackSize();
}
slice = 0;
final FileInfo info = imp.getOriginalFileInfo();
if (info != null) {
path = info.directory + info.fileName;
}
final int[] origin = getOrigin(imp);
setOrigin(origin[0], origin[1]);
return true;
}
/**
* Gets the origin from the Image calibration.
*
* @param imp the image
* @return the origin
* @throws IllegalArgumentException If the origin is not in integer pixel units
*/
public static int[] getOrigin(ImagePlus imp) {
final Calibration cal = imp.getLocalCalibration();
if (cal != null && (cal.xOrigin != 0 || cal.yOrigin != 0)) {
// Origin must be in integer pixels
final double ox = Math.round(cal.xOrigin);
final double oy = Math.round(cal.yOrigin);
if (ox != cal.xOrigin || oy != cal.yOrigin) {
throw new IllegalArgumentException("Origin must be in integer pixels");
}
// ImageJ has a negative origin to indicate 0,0 of the image
// is greater than the actual origin. The ImageSource convention is
// to have the origin represent the shift of the 0,0 pixel from the origin.
return new int[] {(int) -ox, (int) -oy};
}
return new int[2];
}
/**
* Gets the bounds from the Image calibration.
*
* @param imp the image
* @return the bounds
* @throws IllegalArgumentException If the origin is not in integer pixel units
*/
public static Rectangle getBounds(ImagePlus imp) {
final int[] origin = getOrigin(imp);
return new Rectangle(origin[0], origin[1], imp.getWidth(), imp.getHeight());
}
/**
* Create a new image source from an ImageProcessor.
*
* @param name the name
* @param ip the ip
*/
public IJImageSource(String name, ImageProcessor ip) {
super(name);
imageArray = new Object[] {ip.getPixels()};
width = ip.getWidth();
height = ip.getHeight();
frames = 1;
}
/**
* Create a new image source from an ImagePlus. Specify a single frame for processing.
*
* @param imp the imp
* @param frame the frame
*/
public IJImageSource(ImagePlus imp, int frame) {
this(imp, frame, 0);
}
/**
* Create a new image source from an ImagePlus. Specify a start frame and any additional frames
* (after the start) for processing.
*
* @param imp the imp
* @param startFrame The first frame to process
* @param extraFrames The number of additional frames to process
*/
public IJImageSource(ImagePlus imp, int startFrame, int extraFrames) {
super(imp.getTitle());
// Ensure only a single frame is processed
singleFrame = startFrame;
this.extraFrames = Math.max(0, extraFrames);
initialise(imp);
}
/**
* Sets the origin. This should be used if the source was a crop from a image camera sensor.
*
* @param x the x
* @param y the y
*/
public void setOrigin(int x, int y) {
xOrigin = x;
yOrigin = y;
}
/**
* Gets the path to the original image file.
*
* @return the path (or null)
*/
public String getPath() {
return path;
}
@Override
protected boolean openSource() {
if (nullImageArray() && imageStack == null) {
// Try and find the image using the name or path
ImagePlus imp = null;
if (getName() != null) {
imp = WindowManager.getImage(getName());
}
if ((imp == null) && (path != null && path.length() > 0)) {
// Try and open the original image from file
imp = IJ.openImage(path);
if (imp == null) {
// Some readers return null and display the image, e.g. BioFormats.
// Add code to handle this.
} else if (getName() != null) {
// Ensure the image has the correct name
imp.setTitle(getName());
}
}
return initialise(imp);
}
return true;
}
@Override
public void closeSource() {
imageArray = null;
imageStack = null;
}
/**
* Check if the image array or any part of it is null.
*
* @return True if the image array or any part of it is null.
*/
private boolean nullImageArray() {
if (imageArray == null) {
return true;
}
// Check the image array. This is set to null when an image is closed by ImageJ
// allowing us to detect when the image is still available
for (final Object o : imageArray) {
if (o == null) {
return true;
}
}
return false;
}
@Override
protected boolean initialiseSequentialRead() {
slice = 0;
return true;
}
@Override
protected Object nextRawFrame() {
++slice;
if (singleFrame > 0) {
// Return frames from the starting frame until the extra frames limit is reached
return (slice - 1 <= extraFrames) ? get(singleFrame + slice - 1) : null;
}
return get(slice);
}
@Override
protected Object getRawFrame(int frame) {
if (imageArray != null) {
if (frame > 0 && frame <= imageArray.length) {
return imageArray[frame - 1];
}
} else if (imageStack != null
// This is a virtual stack so access the image processor through the virtual stack object
&& frame > 0 && frame <= imageStack.getSize()) {
return imageStack.getPixels(frame);
}
return null;
}
@Override
public boolean isValid(int frame) {
if (singleFrame > 0) {
return (frame >= singleFrame && frame <= singleFrame + extraFrames);
}
return frame > 0 && frame <= frames;
}
@Override
public String toString() {
String string = super.toString();
if (path != null) {
string += String.format(" (%s)", path);
}
return string;
}
}
|
9232d4317467428179649b7c7f3116afc8ac08df | 3,071 | java | Java | FTFLAsyncGallery/src/com/ftfl/ftflasyncgallery/FTFLAsyncGalleryActivity.java | nasser-munshi/Android | ca3e2e1bb5323d36da012047d627f3e0c24d73ff | [
"Apache-2.0"
] | null | null | null | FTFLAsyncGallery/src/com/ftfl/ftflasyncgallery/FTFLAsyncGalleryActivity.java | nasser-munshi/Android | ca3e2e1bb5323d36da012047d627f3e0c24d73ff | [
"Apache-2.0"
] | null | null | null | FTFLAsyncGallery/src/com/ftfl/ftflasyncgallery/FTFLAsyncGalleryActivity.java | nasser-munshi/Android | ca3e2e1bb5323d36da012047d627f3e0c24d73ff | [
"Apache-2.0"
] | 2 | 2015-11-22T11:05:20.000Z | 2021-03-05T17:00:22.000Z | 26.474138 | 85 | 0.59199 | 996,372 | package com.ftfl.ftflasyncgallery;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridView;
public class FTFLAsyncGalleryActivity extends Activity {
String mImagesPath;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImagesPath = this.getFilesDir().getParent() + "/images/";
createImagesDir(mImagesPath);
copyImagesToStorage();
loadGridView();
}
/**
* Method handles the logic for setting the adapter for the gridview
*/
private void loadGridView(){
GridView lLazyGrid = (GridView) this.findViewById(R.id.gridview);
try {
LazyImageAdapter lLazyAdapter = new LazyImageAdapter(this.getApplicationContext(),
null,
mImagesPath);
lLazyGrid.setAdapter(lLazyAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Copy images from assets to storage
*/
private void copyImagesToStorage(){
AssetManager lAssetManager = getAssets();
String[] lFiles = null;
String lTag = "copyImageFail";
try {
// get all of the files in the assets directory
lFiles = lAssetManager.list("");
} catch (IOException e) {
Log.e(lTag, e.getMessage());
}
for(int i=0; i<lFiles.length; i++) {
// We have a file to copy
try {
// copy the file
copyFile(lFiles[i], mImagesPath + lFiles[i]);
} catch(Exception e) {
Log.e(lTag, e.getMessage());
}
}
}
/**
* Method copies the contents of one stream to another
* @param aIn stream to copy from
* @param aOut stream to copy to
* @throws IOException
*/
private void copyFile(String aIn, String aOut) throws IOException {
byte[] lBuffer = new byte[1024];
int lRead;
final int lOffset = 0;
// create an in and out stream
InputStream lIn = getAssets().open(aIn);
OutputStream lOut = new FileOutputStream(aOut);
// Copy contents while there is data
while((lRead = lIn.read(lBuffer)) != -1){
lOut.write(lBuffer, lOffset, lRead);
}
// clean up after our streams
lIn.close();
lIn = null;
lOut.flush();
lOut.close();
lOut = null;
}
/**
* Create the directory specified at aPath if it does not exist
* @param aPath directory to check for and create
*/
private void createImagesDir(String aPath){
File lDir = new File(aPath);
if(!lDir.exists()){
lDir.mkdir();
}
}
}
|
9232d46499030135380840cc31589f58b9fa1ac2 | 351 | java | Java | src/main/java/cn/yuyangyang/weixin/model/VoiceMessage.java | wuqimahei/weixin_cqmyg | 094a1f1d7ff120b751bb503a25401ee07c268aed | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/yuyangyang/weixin/model/VoiceMessage.java | wuqimahei/weixin_cqmyg | 094a1f1d7ff120b751bb503a25401ee07c268aed | [
"Apache-2.0"
] | 6 | 2020-11-16T20:45:26.000Z | 2022-02-01T01:03:17.000Z | src/main/java/cn/yuyangyang/weixin/model/VoiceMessage.java | wuqimahei/weixin_cqmyg | 094a1f1d7ff120b751bb503a25401ee07c268aed | [
"Apache-2.0"
] | null | null | null | 20.647059 | 66 | 0.709402 | 996,373 | package cn.yuyangyang.weixin.model;
import com.baomidou.mybatisplus.annotation.TableName;
public class VoiceMessage extends BaseMessage {
private Voice Voice;
public cn.yuyangyang.weixin.model.Voice getVoice() {
return Voice;
}
public void setVoice(cn.yuyangyang.weixin.model.Voice voice) {
Voice = voice;
}
}
|
9232d51b66ca57748ef8ca3a8aeaaa92d19c33fd | 4,191 | java | Java | wallpaper/src/main/java/com/pickni/wallpaper/utils/RomUtil.java | cj5785/wallpaper | 6880f030547ad8e8656030735c842b4d00b1dacb | [
"MIT"
] | null | null | null | wallpaper/src/main/java/com/pickni/wallpaper/utils/RomUtil.java | cj5785/wallpaper | 6880f030547ad8e8656030735c842b4d00b1dacb | [
"MIT"
] | null | null | null | wallpaper/src/main/java/com/pickni/wallpaper/utils/RomUtil.java | cj5785/wallpaper | 6880f030547ad8e8656030735c842b4d00b1dacb | [
"MIT"
] | null | null | null | 31.503759 | 118 | 0.590215 | 996,374 | package com.pickni.wallpaper.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import com.pickni.lib_log.HiLog;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
/**
* @author 工藤
* @email envkt@example.com
* cc.shinichi.library.tool.utility.device
* create at 2018/12/24 11:54
* description:
*/
public class RomUtil {
/**
* 判断是否为华为系统
*/
public static boolean isHuaweiRom() {
if (!TextUtils.isEmpty(getEmuiVersion()) && !getEmuiVersion().equals("")) {
HiLog.d("isHuaweiRom: true");
return true;
}
HiLog.d("isHuaweiRom: false");
return false;
}
/**
* 判断是否为小米系统
*/
public static boolean isMiuiRom() {
if (!TextUtils.isEmpty(getSystemProperty("ro.miui.ui.version.name"))) {
HiLog.d("isMiuiRom: true");
return true;
}
HiLog.d("isMiuiRom: false");
return false;
}
private static String getSystemProperty(String propName) {
String line;
BufferedReader input = null;
try {
Process p = Runtime.getRuntime().exec("getprop " + propName);
input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
line = input.readLine();
input.close();
} catch (IOException ex) {
HiLog.e("Unable to read sysprop " + propName, ex);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
HiLog.e("Exception while closing InputStream", e);
}
}
}
return line;
}
/**
* 判断是否为Flyme系统
*/
public static boolean isFlymeRom(Context context) {
HiLog.d("isFlymeRom: " + isInstalledByPkgName(context, "com.meizu.flyme.update"));
return isInstalledByPkgName(context, "com.meizu.flyme.update");
}
/**
* 判断是否是Smartisan系统
*/
public static boolean isSmartisanRom(Context context) {
HiLog.d("isSmartisanRom: " + isInstalledByPkgName(context, "com.smartisanos.security"));
return isInstalledByPkgName(context, "com.smartisanos.security");
}
/**
* 根据包名判断这个app是否已安装
*/
public static boolean isInstalledByPkgName(Context context, String pkgName) {
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
} catch (PackageManager.NameNotFoundException e) {
packageInfo = null;
}
if (packageInfo == null) {
return false;
} else {
return true;
}
}
/**
* @return 只要返回不是"",则是EMUI版本
*/
private static String getEmuiVersion() {
String emuiVerion = "";
Class<?>[] clsArray = new Class<?>[]{String.class};
Object[] objArray = new Object[]{"ro.build.version.emui"};
try {
@SuppressLint("PrivateApi") Class<?> SystemPropertiesClass = Class.forName("android.os.SystemProperties");
Method get = SystemPropertiesClass.getDeclaredMethod("get", clsArray);
String version = (String) get.invoke(SystemPropertiesClass, objArray);
HiLog.d("get EMUI version is:" + version);
if (!TextUtils.isEmpty(version)) {
return version;
}
} catch (ClassNotFoundException e) {
HiLog.e(" getEmuiVersion wrong, ClassNotFoundException");
} catch (LinkageError e) {
HiLog.e(" getEmuiVersion wrong, LinkageError");
} catch (NoSuchMethodException e) {
HiLog.e(" getEmuiVersion wrong, NoSuchMethodException");
} catch (NullPointerException e) {
HiLog.e(" getEmuiVersion wrong, NullPointerException");
} catch (Exception e) {
HiLog.e(" getEmuiVersion wrong");
}
return emuiVerion;
}
} |
9232d565999eb0fcaacf3848fe2f0ade663c77ee | 696 | java | Java | Backend/JAVA/Algorithms and Data Structures in Java - Part I/algorithms_datastructures_java/StackLinkedList/Stack.java | specter01wj/LAB-Udemy | 9a81bbabc9f55e68f6cce68c50a6c3cae8ee426f | [
"MIT"
] | null | null | null | Backend/JAVA/Algorithms and Data Structures in Java - Part I/algorithms_datastructures_java/StackLinkedList/Stack.java | specter01wj/LAB-Udemy | 9a81bbabc9f55e68f6cce68c50a6c3cae8ee426f | [
"MIT"
] | 89 | 2020-03-07T05:51:22.000Z | 2022-03-02T15:52:45.000Z | Backend/JAVA/Algorithms and Data Structures in Java - Part I/algorithms_datastructures_java/StackLinkedList/Stack.java | specter01wj/LAB-Udemy | 9a81bbabc9f55e68f6cce68c50a6c3cae8ee426f | [
"MIT"
] | null | null | null | 17.4 | 46 | 0.590517 | 996,375 | package StackLinkedList;
public class Stack<T extends Comparable<T>> {
private Node<T> root;
private int count;
// O(1) constant time
public void push(T newData){
this.count++;
if( this.root == null ){
this.root = new Node<>(newData);
}else{
Node<T> oldRoot = this.root;
this.root = new Node<>(newData);
this.root.setNextNode(oldRoot);
}
}
// O(1)
public int size(){
return this.count;
}
// O(1)
public T pop(){
T itemToPop = this.root.getData();
this.root = this.root.getNextNode();
this.count--;
return itemToPop;
}
// O(1) constant time
public boolean isEmpty(){
return this.root == null;
}
}
|
9232d5bf2c659951ca6baa22771bd9bd82fdedb8 | 2,233 | java | Java | src/com/emergentideas/webhandle/templates/TripartateParser.java | EmergentIdeas/webhandle | 657694b87fb4e6483c5c3791d0dfb09c1b717d39 | [
"Apache-2.0"
] | null | null | null | src/com/emergentideas/webhandle/templates/TripartateParser.java | EmergentIdeas/webhandle | 657694b87fb4e6483c5c3791d0dfb09c1b717d39 | [
"Apache-2.0"
] | null | null | null | src/com/emergentideas/webhandle/templates/TripartateParser.java | EmergentIdeas/webhandle | 657694b87fb4e6483c5c3791d0dfb09c1b717d39 | [
"Apache-2.0"
] | null | null | null | 27.231707 | 85 | 0.711151 | 996,376 | package com.emergentideas.webhandle.templates;
import java.util.ArrayList;
import java.util.List;
public class TripartateParser {
protected String initiatingSequence = "__";
protected String conditionSeparator = "??";
protected String handlingSeparator = "::";
protected String terminatingSequence = "__";
public List<Element> parse(String data) {
List<Element> result = new ArrayList<Element>();
StringBuilder sb = new StringBuilder(data);
while(sb.length() > 0) {
int nextInitiator = sb.indexOf(initiatingSequence);
if(nextInitiator < 0) {
result.add(new StringElementBasic(sb.toString()));
break;
}
else {
// Eat the available string
if(nextInitiator > 0) {
// checking to make sure it's not a zero length string
result.add(new StringElementBasic(sb.substring(0, nextInitiator)));
sb.delete(0, nextInitiator);
}
// delete the initiator
sb.delete(0, initiatingSequence.length());
int nextTerminator = sb.indexOf(terminatingSequence);
String tripartateExpression = sb.substring(0, nextTerminator);
sb.delete(0, nextTerminator);
result.add(parseTripartateExpression(tripartateExpression));
// delete the terminator
sb.delete(0, terminatingSequence.length());
}
}
return result;
}
protected TripartateElement parseTripartateExpression(String expression) {
TripartateElementBasic tp = new TripartateElementBasic();
int conditionalIndex = expression.indexOf(conditionSeparator);
if(conditionalIndex > 0) {
tp.setConditionalExpression(expression.substring(0, conditionalIndex));
}
if(conditionalIndex >=0) {
expression = expression.substring(conditionalIndex + conditionSeparator.length());
}
int handlingIndex = expression.indexOf(handlingSeparator);
if(handlingIndex > 0) {
tp.setDataSelectorExpression(expression.substring(0, handlingIndex));
}
else if(handlingIndex < 0) {
tp.setDataSelectorExpression(expression);
expression = "";
}
if(handlingIndex >= 0) {
expression = expression.substring(handlingIndex + handlingSeparator.length());
}
if(expression.length() > 0) {
tp.setHandlingExpression(expression);
}
return tp;
}
}
|
9232d72399b9f30b5b5dc88737a2c24ad5d1617a | 751 | java | Java | zeno-core/zeno-cdm/src/main/java/domain/zeno/core/cdm/data/serialization/xml/JaxbXmlDeserializer.java | sbarinov/zeno | 8963a9a123c0b1b0d253ae35566902f2e038c8f1 | [
"Apache-2.0"
] | null | null | null | zeno-core/zeno-cdm/src/main/java/domain/zeno/core/cdm/data/serialization/xml/JaxbXmlDeserializer.java | sbarinov/zeno | 8963a9a123c0b1b0d253ae35566902f2e038c8f1 | [
"Apache-2.0"
] | 5 | 2020-03-04T22:04:11.000Z | 2021-12-09T20:19:53.000Z | zeno-core/zeno-cdm/src/main/java/domain/zeno/core/cdm/data/serialization/xml/JaxbXmlDeserializer.java | sbarinov/zeno | 8963a9a123c0b1b0d253ae35566902f2e038c8f1 | [
"Apache-2.0"
] | null | null | null | 25.033333 | 87 | 0.728362 | 996,377 | package domain.zeno.core.cdm.data.serialization.xml;
/*
* COPYRIGHT_PLACEHOLDER
*/
import domain.zeno.core.cdm.data.serialization.IDeserializer;
import java.nio.charset.Charset;
public class JaxbXmlDeserializer<T> implements IDeserializer<T> {
private final IJaxbContextProvider contextProvider;
private final Charset charset;
public JaxbXmlDeserializer(IJaxbContextProvider contextProvider, Charset charset) {
this.contextProvider = contextProvider;
this.charset = charset;
}
public JaxbXmlDeserializer(IJaxbContextProvider contextProvider) {
this(contextProvider, Charset.defaultCharset());
}
@Override
public T deserialize(byte[] data) {
// todo
return null;
}
}
|
9232d740b4385f8ec5c4d75bfd6dc5da6eafccc6 | 2,932 | java | Java | src/main/java/io/wispforest/affinity/misc/recipe/PotionMixingRecipeSerializer.java | glisco03/affinity | c3e629fa61e805dc25c93ee4bb1107a753ee26b1 | [
"MIT"
] | 5 | 2021-12-29T12:46:29.000Z | 2022-01-05T16:46:42.000Z | src/main/java/io/wispforest/affinity/misc/recipe/PotionMixingRecipeSerializer.java | glisco03/affinity | c3e629fa61e805dc25c93ee4bb1107a753ee26b1 | [
"MIT"
] | null | null | null | src/main/java/io/wispforest/affinity/misc/recipe/PotionMixingRecipeSerializer.java | glisco03/affinity | c3e629fa61e805dc25c93ee4bb1107a753ee26b1 | [
"MIT"
] | null | null | null | 44.424242 | 221 | 0.740109 | 996,378 | package io.wispforest.affinity.misc.recipe;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import io.wispforest.affinity.misc.Ingrediente;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.recipe.RecipeSerializer;
import net.minecraft.util.Identifier;
import net.minecraft.util.JsonHelper;
import net.minecraft.util.registry.Registry;
import java.util.ArrayList;
public class PotionMixingRecipeSerializer implements RecipeSerializer<PotionMixingRecipe> {
public static final PotionMixingRecipeSerializer INSTANCE = new PotionMixingRecipeSerializer();
private static final Ingrediente.Serializer<Boolean> INGREDIENTE_SERIALIZER = Ingrediente.makeSerializer(
PacketByteBuf::writeBoolean,
PacketByteBuf::readBoolean,
object -> JsonHelper.getBoolean(object, "copy_nbt", false)
);
private PotionMixingRecipeSerializer() {}
@Override
public PotionMixingRecipe read(Identifier id, JsonObject json) {
final var effectInputsJson = JsonHelper.getArray(json, "effect_inputs");
final var itemInputsJson = JsonHelper.getArray(json, "item_inputs");
final var outputPotion = Registry.POTION.getOrEmpty(Identifier.tryParse(JsonHelper.getString(json, "output"))).orElseThrow(() -> new JsonSyntaxException("Invalid potion: " + JsonHelper.getString(json, "output")));
final var inputEffects = new ArrayList<StatusEffect>();
for (var element : effectInputsJson) {
inputEffects.add(Registry.STATUS_EFFECT.getOrEmpty(Identifier.tryParse(element.getAsString())).orElseThrow(() -> new JsonSyntaxException("Invalid status effect: " + element.getAsString())));
}
final var itemInputs = new ArrayList<Ingrediente<Boolean>>();
for (var element : itemInputsJson) {
itemInputs.add(INGREDIENTE_SERIALIZER.fromJson(element));
}
return new PotionMixingRecipe(id, itemInputs, inputEffects, outputPotion);
}
@Override
public PotionMixingRecipe read(Identifier id, PacketByteBuf buf) {
final var potion = Registry.POTION.get(buf.readVarInt());
final var effectInputs = buf.readCollection(value -> new ArrayList<>(), buf1 -> Registry.STATUS_EFFECT.get(buf1.readVarInt()));
final var itemInputs = buf.readCollection(value -> new ArrayList<>(), INGREDIENTE_SERIALIZER::fromPacket);
return new PotionMixingRecipe(id, itemInputs, effectInputs, potion);
}
@Override
public void write(PacketByteBuf buf, PotionMixingRecipe recipe) {
buf.writeVarInt(Registry.POTION.getRawId(recipe.getPotionOutput()));
buf.writeCollection(recipe.getEffectInputs(), (buf1, effect) -> buf1.writeVarInt(Registry.STATUS_EFFECT.getRawId(effect)));
buf.writeCollection(recipe.getItemInputs(), INGREDIENTE_SERIALIZER::writeToPacket);
}
}
|
9232d76d8a02e300e1b5f46c5ad505307e2d8785 | 8,903 | java | Java | uima-build-helper-maven-plugin/src/main/java/org/apache/uima/buildhelper/CopyFromApacheDist.java | apache/uima-build | b3121f5f109f6a99aa472406fcc548e27ee61919 | [
"Apache-2.0"
] | 3 | 2017-04-06T02:46:31.000Z | 2021-11-10T17:54:28.000Z | uima-build-helper-maven-plugin/src/main/java/org/apache/uima/buildhelper/CopyFromApacheDist.java | apache/uima-build | b3121f5f109f6a99aa472406fcc548e27ee61919 | [
"Apache-2.0"
] | null | null | null | uima-build-helper-maven-plugin/src/main/java/org/apache/uima/buildhelper/CopyFromApacheDist.java | apache/uima-build | b3121f5f109f6a99aa472406fcc548e27ee61919 | [
"Apache-2.0"
] | 6 | 2016-01-08T21:11:20.000Z | 2021-11-10T17:54:14.000Z | 33.723485 | 123 | 0.617769 | 996,379 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.uima.buildhelper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
* Check if the requested artifact is already in the .m2 repository
* if so, just return
* else, download the requested artifact from archive.apache.org/dist/uima/
*
*/
@Mojo( name = "copy-from-apache-dist", defaultPhase = LifecyclePhase.VALIDATE)
public class CopyFromApacheDist extends AbstractMojo {
private static final int MAXRETRIES = 6;
private static final int MINTOTALSIZE = 100;
/**
* Group Id
*/
@Parameter ( defaultValue = "${project.groupId}" )
private String groupId;
/**
* Artifact Id
*/
@Parameter ( defaultValue = "uimaj" )
private String artifactId;
/**
* Version, e.g. 2.4.0
*/
@Parameter (required = true)
private String version = null;
/**
* Type
*/
@Parameter ( defaultValue = "zip" )
private String type;
/**
* Classifier
*/
@Parameter ( defaultValue = "bin" )
private String classifier;
/**
* Repository
*
*
*/
@Parameter ( defaultValue = "${settings.localRepository}" )
private String repository;
public void execute() throws MojoExecutionException {
// repoloc / org/apache/uima / artifactId / version / artifactId - version - classifier . type
String targetInLocalFileSystem = String.format("%s/%s/%s/%s/%s-%s%s.%s",
repository,
groupId.replace('.', '/'),
artifactId,
version,
artifactId,
version,
(classifier.length() > 0) ? ("-" + classifier) : "",
type);
File targetFile = new File(targetInLocalFileSystem);
if (targetFile.exists()) {
System.out.format("copy-from-apache-dist returning, file %s exists%n", targetInLocalFileSystem);
return;
}
// http://archive.apache.org/dist/uima/ artifactId - version / artifactId - version - classifier . type
String remoteLocation = String.format("http://%s.apache.org/dist/uima/%s-%s/%s-%s%s.%s",
"archive",
// "www",
artifactId,
version,
artifactId,
version,
(classifier.length() > 0) ? ("-" + classifier) : "",
type);
// read remote file
URL remoteURL = null;
try {
remoteURL = new URL(remoteLocation);
} catch (MalformedURLException e) {
throw new MojoExecutionException("Bad URL internally: " + remoteLocation, e);
}
FileOutputStream os = null;
targetFile.getParentFile().mkdirs();
if (targetFile.exists()) {
System.out.format(" *** Surprise, file %s exists on 2nd check%n", targetInLocalFileSystem);
return;
}
try {
os = new FileOutputStream(targetFile);
} catch (FileNotFoundException e) {
throw new MojoExecutionException("While creating local file in location " + targetFile.getAbsolutePath(), e);
}
int totalSize = 0;
int readSoFar = 0;
retryLoop:
for (int retry = 0; retry < MAXRETRIES; retry ++) {
HttpURLConnection remoteConnection = null;
InputStream is = null;
try {
remoteConnection = (HttpURLConnection) remoteURL.openConnection();
if (readSoFar > 0) {
String rangespec = String.format("bytes=%d-", readSoFar);
System.out.format("Requesting range: %s%n", rangespec);
remoteConnection.setRequestProperty("Range", rangespec);
}
if (totalSize == 0) {
totalSize = remoteConnection.getContentLength();
if (totalSize < MINTOTALSIZE) {
throw new MojoExecutionException(String.format("File size %d too small for %s%n", totalSize, remoteLocation));
}
}
is = remoteConnection.getInputStream();
// if (readSoFar > 0) {
// System.out.format("Skipping over %,d bytes read so far; this may take some time%n", readSoFar);
// long skipped = is.skip(readSoFar);
// if (skipped != readSoFar) {
// System.out.format("Skipping only skipped %,d out of %,d; retrying", skipped, readSoFar);
// continue retryLoop;
// }
// }
} catch (IOException e) {
throw new MojoExecutionException("While reading remote location " + remoteLocation, e);
}
System.out.format("copy-from-apache-dist file %s to %s%n", remoteLocation, targetInLocalFileSystem);
System.out.format("%,12d of %,12d\r", readSoFar, totalSize);
byte[] buf = new byte[1024*1024]; // buffer size
long timeToLog = System.currentTimeMillis();
while(true) {
int bytesRead;
try {
bytesRead = is.read(buf);
} catch (IOException e) {
throw new MojoExecutionException("While reading remote file in location " + remoteLocation, e);
}
if (bytesRead < 0 ) {
if (readSoFar == totalSize) {
System.out.format("%,12d of %,12d%nFinished%n", readSoFar, totalSize);
break;
}
System.out.format("%n *** Premature EOF, %,12d read out of %,12d Retry %d%n", readSoFar, totalSize, retry);
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (retry == (MAXRETRIES - 1)) {
throw new MojoExecutionException("CopyFromApacheDist retry limit exceeded ");
}
continue retryLoop;
}
retry = 0; // reset retry count because we read some good bytes
try {
os.write(buf, 0, bytesRead);
} catch (IOException e) {
throw new MojoExecutionException("While writing target file in location " + targetFile.getAbsolutePath(), e);
}
readSoFar = readSoFar + bytesRead;
if (System.currentTimeMillis() - timeToLog > 1000) {
timeToLog = System.currentTimeMillis();
System.out.format("%,12d of %,12d\r", readSoFar, totalSize);
}
}
try {
os.close();
} catch (IOException e) {
throw new MojoExecutionException("While closing target file in location " + targetFile.getAbsolutePath(), e);
}
try {
is.close();
} catch (IOException e) {
throw new MojoExecutionException("While closing remote file in location " + remoteLocation, e);
}
break; // out of retry loop
}
}
// public static void main(String[] args) throws IOException {
// String remoteLocation = "http://archive.apache.org/dist/uima/uimaj-2.4.0/uimaj-2.4.0-bin.zip.asc";
// // read remote file
// URL remoteURL = null;
// try {
// remoteURL = new URL(remoteLocation);
// } catch (MalformedURLException e) {
// // throw new MojoExecutionException("Bad URL internally: " + remoteLocation, e);
// }
//
// InputStream is = null;
// try {
// is = remoteURL.openStream();
// } catch (IOException e) {
// e.printStackTrace();
// // throw new MojoExecutionException("While reading remote location " + remoteLocation, e);
// }
// FileOutputStream os = null;
// try {
// os = new FileOutputStream("c:/temp/t");
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// byte[] buf = new byte[1024*1024]; // 1 meg buffer size
// while(true) {
// int bytesRead = is.read(buf);
// if (bytesRead < 0) {
// break;
// }
// os.write(buf, 0, bytesRead);
// }
// os.close();
// is.close();
//
// }
}
|
9232d8c7dd5263eb6cf9d2fac2295afb8794bfcb | 1,264 | java | Java | winery-core/src/main/java/com/changfa/frame/core/exception/AppException.java | luffykid/smart_wine_java | e53bea4aef2b7967e9c11ea64428ac729994caa9 | [
"Apache-2.0"
] | null | null | null | winery-core/src/main/java/com/changfa/frame/core/exception/AppException.java | luffykid/smart_wine_java | e53bea4aef2b7967e9c11ea64428ac729994caa9 | [
"Apache-2.0"
] | 10 | 2020-06-30T23:25:15.000Z | 2022-02-01T01:00:03.000Z | winery-core/src/main/java/com/changfa/frame/core/exception/AppException.java | luffykid/smart_wine_java | e53bea4aef2b7967e9c11ea64428ac729994caa9 | [
"Apache-2.0"
] | 1 | 2021-07-18T16:43:17.000Z | 2021-07-18T16:43:17.000Z | 21.423729 | 79 | 0.634494 | 996,380 | package com.changfa.frame.core.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class AppException extends AppCheckedException {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(SysException.class);
public String getErrId() {
return this.errId;
}
public void setErrId(String errId) {
this.errId = errId;
}
public String getErrMsg() {
return this.errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public AppException() {
}
/**
* 错误号
*/
String errId;
/**
* 错误信息,当前错误的信息。
*/
String errMsg;
public AppException(String errId, String errOwnMsg) {
this.errId = errId;
this.errMsg = errOwnMsg;
this.writeAppException();
}
private void writeAppException() {
logger.error("应用错误号:" + this.errId);
logger.error("应用错误信息:" + this.errMsg);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream p = new PrintStream(os);
this.printStackTrace(p);
logger.error(os.toString());
}
}
|
9232d96c352bd76b2350ca15a209a34a9ca83e09 | 8,757 | java | Java | src/test_en/Form.java | ShangHong-CAI/test-en | 640053e892e588b636ffc729ba9b34551cdd2164 | [
"MIT"
] | null | null | null | src/test_en/Form.java | ShangHong-CAI/test-en | 640053e892e588b636ffc729ba9b34551cdd2164 | [
"MIT"
] | null | null | null | src/test_en/Form.java | ShangHong-CAI/test-en | 640053e892e588b636ffc729ba9b34551cdd2164 | [
"MIT"
] | null | null | null | 33.296578 | 87 | 0.543337 | 996,381 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test_en;
import javax.swing.JButton;
import java.awt.Label;
import javax.swing.JTextArea;
import java.awt.Panel;
import java.awt.Frame;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static test_en.Test_en.POS_arabic;
import static test_en.Test_en.POS_english;
import static test_en.Test_en.POS_french;
import static test_en.Test_en.POS_german;
import static test_en.Test_en.POS_japan;
import static test_en.Test_en.POS_korea;
import static test_en.Test_en.POS_russian;
import static test_en.Test_en.POS_spanish;
/**
*
* @author tfcs
*/
public class Form implements ActionListener
{
Frame frame;
//Button button1;
JButton button1; //
JButton button2;
JButton button3;
JButton button4;
JButton button5;
JButton button6;
JButton button7;
JButton button8;
Label label1;
JTextArea textBox_output; JTextArea textBox_input;
@Override
public void actionPerformed(ActionEvent e) //動作執行器
{
String cmd = e.getActionCommand();
String Input_text ="";
String Output_text="";
switch(cmd)
{
case "b1":
Input_text = textBox_input.getText();
Output_text = "";
{
try {
String [] output_text_array = POS_arabic(Input_text);
for (String output_text_array1 : output_text_array) {
Output_text += output_text_array1 + "\r\n";
}
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
textBox_output.setText(Output_text);
}
break;
case "b2":
Input_text = textBox_input.getText();
Output_text = "";
{
try {
String [] output_text_array = POS_spanish(Input_text);
for (String output_text_array1 : output_text_array) {
Output_text += output_text_array1 + "\r\n";
}
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
textBox_output.setText(Output_text);
break;
case "b3":
Input_text = textBox_input.getText();
Output_text = "";
{
try {
String [] output_text_array = POS_english(Input_text);
for (String output_text_array1 : output_text_array) {
Output_text += output_text_array1 + "\r\n";
}
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
textBox_output.setText(Output_text);
break;
case "b4":
Input_text = textBox_input.getText();
Output_text = "";
{
try {
String [] output_text_array = POS_german(Input_text);
for (String output_text_array1 : output_text_array) {
Output_text += output_text_array1 + "\r\n";
}
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
textBox_output.setText(Output_text);
break;
case "b5":
Input_text = textBox_input.getText();
Output_text = "";
{
try {
String [] output_text_array = POS_french(Input_text);
for (String output_text_array1 : output_text_array) {
Output_text += output_text_array1 + "\r\n";
}
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
textBox_output.setText(Output_text);
break;
case "b6":
Input_text = textBox_input.getText();
Output_text = "";
{
String [] output_text_array = POS_japan(Input_text);
for (String output_text_array1 : output_text_array)
{
Output_text += output_text_array1 + "\r\n";
}
}
textBox_output.setText(Output_text);
break;
case "b7":
Input_text = textBox_input.getText();
Output_text = "";
{
String [] output_text_array = POS_korea(Input_text);
for (String output_text_array1 : output_text_array)
{
Output_text += output_text_array1 + "\r\n";
}
}
textBox_output.setText(Output_text);
break;
case "b8":
Input_text = textBox_input.getText();
Output_text = "";
{
String [] output_text_array = POS_russian(Input_text);
for (String output_text_array1 : output_text_array)
{
Output_text += output_text_array1 + "\r\n";
}
}
textBox_output.setText(Output_text);
break;
}
}
public void InitializeComponent()
{
//
Panel panel = new Panel();
panel.setBackground(Color.BLACK);
//文字方塊
textBox_input = new JTextArea();
//textBox_input.setFont(new Font(Font.DIALOG, Font.BOLD, 20));
textBox_input.setBounds(15,40,800,80);
textBox_input.setText("請輸入文字...");
textBox_output = new JTextArea();
//textBox_output.setFont(new Font(Font.DIALOG, Font.BOLD, 20));
textBox_output.setBounds(15, 185, 800, 350);
//按鈕
button1 = new JButton("阿拉伯");
button1.setBounds(15,150,95,30);
button1.setActionCommand("b1");//傳送到執行器
button1.addActionListener(this);
button2 = new JButton("西班牙");
button2.setBounds(115,150,95,30);
button2.setActionCommand("b2");
button2.addActionListener(this);
button3 = new JButton("英文");
button3.setBounds(215,150,95,30);
button3.setActionCommand("b3");
button3.addActionListener(this);
button4 = new JButton("德文");
button4.setBounds(315,150,95,30);
button4.setActionCommand("b4");
button4.addActionListener(this);
button5 = new JButton("法文");
button5.setBounds(415,150,95,30);
button5.setActionCommand("b5");
button5.addActionListener(this);
button6 = new JButton("日文");
button6.setBounds(515,150,95,30);
button6.setActionCommand("b6");
button6.addActionListener(this);
button7 = new JButton("韓文");
button7.setBounds(615,150,95,30);
button7.setActionCommand("b7");
button7.addActionListener(this);
button8 = new JButton("俄文");
button8.setBounds(715,150,95,30);
button8.setActionCommand("b8");
button8.addActionListener(this);
//整個視窗畫面
frame = new Frame("多國語言分詞系統");
frame.addWindowListener(new AdapterDemo());//新增事件處理功能
//frame.setLayout(new FlowLayout());
frame.setSize(850, 600);//視窗大小
frame.setLocation(50, 50);//視窗顯示位置
frame.add(button1);//增加按鈕1
frame.add(button2);//增加按鈕2
frame.add(button3);//增加按鈕3
frame.add(button4);//增加按鈕4
frame.add(button5);//增加按鈕5
frame.add(button6);//增加按鈕6
frame.add(button7);//增加按鈕6
frame.add(button8);//增加按鈕6
frame.add(textBox_output);//增加文字版
frame.add(textBox_input); //增加文字版
//frame.add(label1);
frame.add(panel);
//frame.pack();
frame.setVisible(true);
}
}
class AdapterDemo extends WindowAdapter
{
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} |
9232da040b083d80d30c67510424776862ae1e1f | 1,997 | java | Java | src/main/java/com/github/charlemaznable/bunny/client/guice/AbstractBunnyModular.java | CharLemAznable/bunny-client | d52a0d0ed015c82ed61cd4fc31715182b6385eca | [
"MIT"
] | null | null | null | src/main/java/com/github/charlemaznable/bunny/client/guice/AbstractBunnyModular.java | CharLemAznable/bunny-client | d52a0d0ed015c82ed61cd4fc31715182b6385eca | [
"MIT"
] | null | null | null | src/main/java/com/github/charlemaznable/bunny/client/guice/AbstractBunnyModular.java | CharLemAznable/bunny-client | d52a0d0ed015c82ed61cd4fc31715182b6385eca | [
"MIT"
] | null | null | null | 34.431034 | 88 | 0.719079 | 996,382 | package com.github.charlemaznable.bunny.client.guice;
import com.github.charlemaznable.bunny.client.config.BunnyClientConfig;
import com.github.charlemaznable.core.codec.nonsense.NonsenseOptions;
import com.github.charlemaznable.core.codec.signature.SignatureOptions;
import com.github.charlemaznable.core.guice.Modulee;
import com.github.charlemaznable.core.miner.MinerModular;
import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.util.Providers;
import lombok.RequiredArgsConstructor;
@SuppressWarnings("unchecked")
@RequiredArgsConstructor
public abstract class AbstractBunnyModular<T extends AbstractBunnyModular> {
private final Module configModule;
private NonsenseOptions nonsenseOptions;
private SignatureOptions signatureOptions;
public AbstractBunnyModular() {
this((BunnyClientConfig) null);
}
public AbstractBunnyModular(Class<? extends BunnyClientConfig> configClass) {
this(new MinerModular().bindClasses(configClass).createModule());
}
public AbstractBunnyModular(BunnyClientConfig configImpl) {
this(new AbstractModule() {
@Override
protected void configure() {
bind(BunnyClientConfig.class).toProvider(Providers.of(configImpl));
}
});
}
public T nonsenseOptions(NonsenseOptions nonsenseOptions) {
this.nonsenseOptions = nonsenseOptions;
return (T) this;
}
public T signatureOptions(SignatureOptions signatureOptions) {
this.signatureOptions = signatureOptions;
return (T) this;
}
public Module createModule() {
return Modulee.override(new AbstractModule() {
@Override
protected void configure() {
bind(NonsenseOptions.class).toProvider(Providers.of(nonsenseOptions));
bind(SignatureOptions.class).toProvider(Providers.of(signatureOptions));
}
}, configModule);
}
}
|
9232da3e8bcf1bdc5da4ec230fe861a970c8d27a | 713 | java | Java | server/src/it/castelli/connection/messages/UpdatePlayersListServerMessage.java | LucaVaccari/MonopolyFX | a0e742745d64b68c6e765093df682cff1868850d | [
"MIT"
] | 1 | 2021-04-20T11:11:07.000Z | 2021-04-20T11:11:07.000Z | server/src/it/castelli/connection/messages/UpdatePlayersListServerMessage.java | LucaVaccari/MonopolyFX | a0e742745d64b68c6e765093df682cff1868850d | [
"MIT"
] | null | null | null | server/src/it/castelli/connection/messages/UpdatePlayersListServerMessage.java | LucaVaccari/MonopolyFX | a0e742745d64b68c6e765093df682cff1868850d | [
"MIT"
] | 1 | 2021-03-14T16:51:20.000Z | 2021-03-14T16:51:20.000Z | 20.970588 | 76 | 0.765778 | 996,383 | package it.castelli.connection.messages;
import it.castelli.connection.Connection;
import it.castelli.gameLogic.Player;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Message to update the players list in the game (send only)
*/
public class UpdatePlayersListServerMessage implements Message
{
/**
* The updated player list
*/
private final CopyOnWriteArrayList<Player> players;
/**
* Constructor for UpdatePlayersListServerMessage
*
* @param players The updated player list
*/
public UpdatePlayersListServerMessage(CopyOnWriteArrayList<Player> players)
{
this.players = players;
}
@Override
public void onReceive(Connection connection, Player player)
{
//do nothing
}
}
|
9232da6d5f4cad26a8fa5768b392d622503a2a06 | 4,170 | java | Java | plugin/src/main/java/me/joeleoli/praxi/player/RematchData.java | disclearing/praxi- | 8deb23f3ae83c80f706d2932c730e176398bfed5 | [
"Apache-2.0"
] | 1 | 2021-02-17T23:21:20.000Z | 2021-02-17T23:21:20.000Z | plugin/src/main/java/me/joeleoli/praxi/player/RematchData.java | disclearing/praxi- | 8deb23f3ae83c80f706d2932c730e176398bfed5 | [
"Apache-2.0"
] | null | null | null | plugin/src/main/java/me/joeleoli/praxi/player/RematchData.java | disclearing/praxi- | 8deb23f3ae83c80f706d2932c730e176398bfed5 | [
"Apache-2.0"
] | 4 | 2019-09-09T15:30:56.000Z | 2022-01-24T06:04:03.000Z | 32.578125 | 114 | 0.71295 | 996,384 | package me.joeleoli.praxi.player;
import java.util.UUID;
import lombok.Getter;
import me.joeleoli.nucleus.NucleusAPI;
import me.joeleoli.nucleus.chat.ChatComponentBuilder;
import me.joeleoli.nucleus.util.Style;
import me.joeleoli.praxi.Praxi;
import me.joeleoli.praxi.arena.Arena;
import me.joeleoli.praxi.ladder.Ladder;
import me.joeleoli.praxi.match.Match;
import me.joeleoli.praxi.match.MatchPlayer;
import me.joeleoli.praxi.match.impl.SoloMatch;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import org.bukkit.entity.Player;
@Getter
public class RematchData {
private static final HoverEvent HOVER_EVENT = new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
new ChatComponentBuilder(Style.YELLOW + "Click to accept this rematch invite.").create()
);
private static final ClickEvent CLICK_EVENT = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/rematch");
private UUID key;
private UUID sender;
private UUID target;
private Ladder ladder;
private Arena arena;
private boolean sent;
private boolean receive;
private long timestamp = System.currentTimeMillis();
public RematchData(UUID key, UUID sender, UUID target, Ladder ladder, Arena arena) {
this.key = key;
this.sender = sender;
this.target = target;
this.ladder = ladder;
this.arena = arena;
}
public void request() {
final Player sender = Praxi.getInstance().getServer().getPlayer(this.sender);
final Player target = Praxi.getInstance().getServer().getPlayer(this.target);
if (sender == null || target == null) {
return;
}
final PraxiPlayer senderPraxiPlayer = PraxiPlayer.getByUuid(sender.getUniqueId());
final PraxiPlayer targetPraxiPlayer = PraxiPlayer.getByUuid(target.getUniqueId());
if (senderPraxiPlayer.getRematchData() == null || targetPraxiPlayer.getRematchData() == null ||
!senderPraxiPlayer.getRematchData().getKey().equals(targetPraxiPlayer.getRematchData().getKey())) {
return;
}
if (senderPraxiPlayer.isBusy()) {
sender.sendMessage(Style.RED + "You cannot duel right now.");
return;
}
sender.sendMessage(Style.translate(
"&eYou sent a rematch request to &d" + target.getName() + " &eon arena &d" + this.arena.getName() +
"&e."));
target.sendMessage(Style.translate(
"&d" + sender.getName() + " &ehas sent you a rematch request on arena &d" + this.arena.getName() +
"&e."));
target.sendMessage(new ChatComponentBuilder("").parse("&6Click here or type &b/rematch &6to accept the invite.")
.attachToEachPart(HOVER_EVENT).attachToEachPart(CLICK_EVENT)
.create());
this.sent = true;
targetPraxiPlayer.getRematchData().receive = true;
senderPraxiPlayer.refreshHotbar();
targetPraxiPlayer.refreshHotbar();
}
public void accept() {
final Player sender = Praxi.getInstance().getServer().getPlayer(this.sender);
final Player target = Praxi.getInstance().getServer().getPlayer(this.target);
if (sender == null || target == null || !sender.isOnline() || !target.isOnline()) {
return;
}
final PraxiPlayer senderPraxiPlayer = PraxiPlayer.getByUuid(sender.getUniqueId());
final PraxiPlayer targetPraxiPlayer = PraxiPlayer.getByUuid(target.getUniqueId());
if (senderPraxiPlayer.getRematchData() == null || targetPraxiPlayer.getRematchData() == null ||
!senderPraxiPlayer.getRematchData().getKey().equals(targetPraxiPlayer.getRematchData().getKey())) {
return;
}
if (senderPraxiPlayer.isBusy()) {
sender.sendMessage(Style.RED + "You cannot duel right now.");
return;
}
if (targetPraxiPlayer.isBusy()) {
sender.sendMessage(NucleusAPI.getColoredName(target) + Style.RED + " is currently busy.");
return;
}
Arena arena = this.arena;
if (arena.isActive()) {
arena = Arena.getRandom(this.ladder);
}
if (arena == null) {
sender.sendMessage(Style.RED + "Tried to start a match but there are no available arenas.");
return;
}
arena.setActive(true);
Match match = new SoloMatch(new MatchPlayer(sender), new MatchPlayer(target), this.ladder, arena, false, true);
match.handleStart();
}
}
|
9232db310f1a517782863bddce06f464ea408137 | 4,498 | java | Java | src/main/java/bluegreen/manager/tasks/ElbInstanceGoneProgressChecker.java | thexdesk/bluegreen-manager | 7198bc5a9aa17e825812bf4eb7faabdf958d03b5 | [
"MIT"
] | 6 | 2017-11-08T14:34:41.000Z | 2021-04-06T16:16:51.000Z | src/main/java/bluegreen/manager/tasks/ElbInstanceGoneProgressChecker.java | thexdesk/bluegreen-manager | 7198bc5a9aa17e825812bf4eb7faabdf958d03b5 | [
"MIT"
] | null | null | null | src/main/java/bluegreen/manager/tasks/ElbInstanceGoneProgressChecker.java | thexdesk/bluegreen-manager | 7198bc5a9aa17e825812bf4eb7faabdf958d03b5 | [
"MIT"
] | 4 | 2018-08-06T20:53:46.000Z | 2019-08-24T04:07:48.000Z | 30.808219 | 141 | 0.700978 | 996,385 | package bluegreen.manager.tasks;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.services.elasticloadbalancing.model.Instance;
import com.amazonaws.services.elasticloadbalancing.model.LoadBalancerDescription;
import bluegreen.manager.client.aws.ElbClient;
import bluegreen.manager.utils.ProgressChecker;
/**
* Knows how to check progress of an EC2 instance deregistering from an ELB, by looking at the ELB's described list of
* instances and declaring "done" when the instance is gone from the list.
* <p/>
* Assumes there will always be another instance left in the ELB after this one is removed, so it would be an error if
* we found an empty list of instances.
* <p/>
* Result is "true" when the deregistered instance is gone from the ELB.
*/
public class ElbInstanceGoneProgressChecker implements ProgressChecker<Boolean>
{
private static final Logger LOGGER = LoggerFactory.getLogger(ElbInstanceGoneProgressChecker.class);
private String elbName;
private String ec2InstanceId;
private String logContext;
private ElbClient elbClient;
private boolean done;
private Boolean result;
public ElbInstanceGoneProgressChecker(String elbName,
String ec2InstanceId,
String logContext,
ElbClient elbClient)
{
this.elbName = elbName;
this.ec2InstanceId = ec2InstanceId;
this.logContext = logContext;
this.elbClient = elbClient;
}
@Override
public String getDescription()
{
return "ELB Instance Gone for elb '" + elbName + "', ec2 instance '" + ec2InstanceId + "'";
}
/**
* Initial check calls elbClient to describe the ELB, same as the followup checks, because the initial
* deregistration call does not return an ELB description.
*/
@Override
public void initialCheck()
{
LoadBalancerDescription loadBalancerDescription = elbClient.describeLoadBalancer(elbName);
checkInstanceRemoval(loadBalancerDescription);
LOGGER.debug(logContext + "Initial ELB instance list: " + summarizeInstances(loadBalancerDescription.getInstances()));
}
@Override
public void followupCheck(int waitNum)
{
LoadBalancerDescription loadBalancerDescription = elbClient.describeLoadBalancer(elbName);
checkInstanceRemoval(loadBalancerDescription);
LOGGER.debug(logContext + "ELB instance list after wait#" + waitNum + ": " + summarizeInstances(loadBalancerDescription.getInstances()));
}
/**
* Sanity checks the LB description, and checks for done-ness.
*/
private void checkInstanceRemoval(LoadBalancerDescription loadBalancerDescription)
{
if (!StringUtils.equals(elbName, loadBalancerDescription.getLoadBalancerName()))
{
throw new IllegalStateException(logContext + "We requested description of ELB '" + elbName
+ "' but response is for '" + loadBalancerDescription.getLoadBalancerName() + "'");
}
if (CollectionUtils.isEmpty(loadBalancerDescription.getInstances()))
{
throw new IllegalStateException("ELB '" + elbName + "' has zero instances");
}
if (instanceIsGoneFromList(loadBalancerDescription.getInstances()))
{
LOGGER.info("ELB '" + elbName + "' list of instances shows '" + ec2InstanceId + "' is gone");
done = true;
result = true;
}
}
/**
* True if ec2InstanceId is not in the input list.
*/
private boolean instanceIsGoneFromList(List<Instance> instances)
{
if (instances == null)
{
throw new IllegalArgumentException();
}
for (Instance instance : instances)
{
if (StringUtils.equals(instance.getInstanceId(), ec2InstanceId))
{
return false;
}
}
return true;
}
/**
* Returns a one-line, comma-separated string of the input instance list. Health status info is not available.
* <p/>
* Example: "i-123456, i-234567"
*/
private String summarizeInstances(List<Instance> instances)
{
return StringUtils.join(instances, ", ");
}
@Override
public boolean isDone()
{
return done;
}
@Override
public Boolean getResult()
{
return result;
}
/**
* Simply logs the timeout and returns null.
*/
@Override
public Boolean timeout()
{
LOGGER.error("Timeout before ELB Instance Gone");
return null;
}
}
|
9232db659c28cef1382813cd11a6ab1105a1a84e | 606 | java | Java | core/src/main/java/org/museautomation/core/events/matching/EventTagMatcher.java | ChrisLMerrill/muse | e60cac308813c96d23d4f62d35eaca09f64d959e | [
"Apache-2.0"
] | 12 | 2015-09-13T02:42:37.000Z | 2021-06-25T18:24:51.000Z | core/src/main/java/org/museautomation/core/events/matching/EventTagMatcher.java | ChrisLMerrill/muse | e60cac308813c96d23d4f62d35eaca09f64d959e | [
"Apache-2.0"
] | 2 | 2016-02-17T14:11:20.000Z | 2016-02-17T17:08:56.000Z | core/src/main/java/org/museautomation/core/events/matching/EventTagMatcher.java | ChrisLMerrill/muse | e60cac308813c96d23d4f62d35eaca09f64d959e | [
"Apache-2.0"
] | null | null | null | 20.2 | 70 | 0.612211 | 996,386 | package org.museautomation.core.events.matching;
import org.museautomation.core.*;
import java.util.*;
/**
* @author Christopher L Merrill (see LICENSE.txt for license details)
*/
public class EventTagMatcher implements EventMatcher
{
public EventTagMatcher(String... tags)
{
_tags.addAll(Arrays.asList(tags));
}
@Override
public boolean matches(MuseEvent event)
{
for (String tag : _tags)
if (event.hasTag(tag))
return true;
return false;
}
private Set<String> _tags = new HashSet<>();
}
|
9232dd59d85fae77f78ef3746103ceaaa31d9ad8 | 6,605 | java | Java | src/main/java/arekkuusu/enderskills/api/helper/ExpressionHelper.java | Nekulian/EnderSkills | aa31940b2f3fd952393a1b4b7f74b3556f4efca1 | [
"MIT"
] | 3 | 2021-12-23T14:52:59.000Z | 2022-03-11T03:02:27.000Z | src/main/java/arekkuusu/enderskills/api/helper/ExpressionHelper.java | Nekulian/EnderSkills | aa31940b2f3fd952393a1b4b7f74b3556f4efca1 | [
"MIT"
] | 14 | 2020-06-14T05:36:22.000Z | 2020-12-19T04:30:56.000Z | src/main/java/arekkuusu/enderskills/api/helper/ExpressionHelper.java | Nekulian/EnderSkills | aa31940b2f3fd952393a1b4b7f74b3556f4efca1 | [
"MIT"
] | 1 | 2020-08-31T18:44:00.000Z | 2020-08-31T18:44:00.000Z | 44.033333 | 183 | 0.624073 | 996,387 | package arekkuusu.enderskills.api.helper;
import arekkuusu.enderskills.api.EnderSkillsAPI;
import arekkuusu.enderskills.api.registry.Skill;
import com.expression.parser.Parser;
import com.expression.parser.util.ParserResult;
import com.expression.parser.util.Point;
import it.unimi.dsi.fastutil.ints.Int2DoubleArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Tuple;
import javax.annotation.Nullable;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExpressionHelper {
public static final Function<Tuple<ResourceLocation, String>, Int2DoubleArrayMap> EXPRESSION_CACHE_SUPPLIER = (s) -> new Int2DoubleArrayMap();
public static final Function<ResourceLocation, Object2ObjectArrayMap<String, FunctionInfo>> EXPRESSION_FUNCTION_CACHE_SUPPLIER = (s) -> new Object2ObjectArrayMap<>();
public static final Function<String, FunctionInfo> EXPRESSION_PARSER_SUPPLIER = ExpressionHelper::parse;
public static final String EXPRESSION_REGEX = "^\\(([\\+\\-\\d]+)\\)\\{(.+)\\}$";
public static double getExpression(Skill skill, String function, int min, int max) {
return getExpression(skill.getRegistryName(), function, min, max);
}
public static double getExpression(Skill skill, String[] functionArray, int min, int max) {
return getExpression(skill.getRegistryName(), functionArray, min, max);
}
public static double getExpression(ResourceLocation location, String function, int min, int max) {
Int2DoubleArrayMap cache = EnderSkillsAPI.EXPRESSION_CACHE.asMap().computeIfAbsent(new Tuple<>(location, function), ExpressionHelper.EXPRESSION_CACHE_SUPPLIER);
if(min > max) min = max;
if (!cache.containsKey(min)) {
Point x = new Point("x", String.valueOf(min));
Point y = new Point("y", String.valueOf(max));
ParserResult result = Parser.eval(function, x, y);
cache.put(min, result.getValue().doubleValue());
}
return cache.get(min);
}
public static double getExpression(ResourceLocation location, String[] functionArray, int min, int max) {
Object2ObjectMap<String, FunctionInfo> cache = EnderSkillsAPI.EXPRESSION_FUNCTION_CACHE.asMap().computeIfAbsent(location, ExpressionHelper.EXPRESSION_FUNCTION_CACHE_SUPPLIER);
FunctionInfo match = null;
FunctionInfo temp = null;
if(min > max) min = max;
for (String s : functionArray) {
FunctionInfo info = cache.computeIfAbsent(s, ExpressionHelper.EXPRESSION_PARSER_SUPPLIER);
if (info.matches(min) && isNotOverride(temp, info, min)) {
match = info;
}
temp = info;
}
return match != null ? ExpressionHelper.getExpression(location, match.function, min, max) : 0;
}
public static boolean isNotOverride(@Nullable FunctionInfo prev, FunctionInfo next, int min) {
return prev == null || next.condition != FunctionInfo.Condition.MinusInfinite
|| (prev.condition == FunctionInfo.Condition.PlusInfinite && min > prev.min)
|| (prev.condition == FunctionInfo.Condition.Between && min > prev.max)
|| (prev.condition == FunctionInfo.Condition.MinusInfinite && min > prev.min);
}
public static FunctionInfo parse(String string) {
Pattern pattern = Pattern.compile(ExpressionHelper.EXPRESSION_REGEX);
Matcher matcher = pattern.matcher(string.trim());
if (matcher.matches()) {
String condition = matcher.group(1).trim().replace(" ", "");
String function = matcher.group(2).trim();
if (condition.endsWith("+")) {
int min = Integer.parseInt(condition.substring(0, condition.length() - 1));
return new FunctionInfo(FunctionInfo.Condition.PlusInfinite, function, min);
} else if (condition.startsWith("-")) {
int min = Integer.parseInt(condition.substring(1));
return new FunctionInfo(FunctionInfo.Condition.MinusInfinite, function, min);
} else if (condition.contains("-")){
int index = condition.indexOf('-');
int min = Integer.parseInt(condition.substring(0, index));
int max = Integer.parseInt(condition.substring(index + 1));
return new FunctionInfo(FunctionInfo.Condition.Between, function, min, max);
} else {
int min = Integer.parseInt(condition);
return new FunctionInfo(FunctionInfo.Condition.Equal, function, min);
}
} else {
throw new IllegalStateException("[ExpressionHelper] - Expression " + string + " is not valid, might be missing a { or }");
}
}
public static class FunctionInfo {
public Condition condition;
public String function;
public int min;
public int max;
public FunctionInfo(Condition condition, String function, int min, int max) {
this.condition = condition;
this.function = function;
this.min = min;
this.max = max;
}
public FunctionInfo(Condition condition, String function, int min) {
this.condition = condition;
this.function = function;
this.min = min;
this.max = -1;
}
public boolean matches(int level) {
return condition.test(level, this.min, this.max);
}
public enum Condition {
PlusInfinite {
@Override
boolean test(int level, int levelMin, int levelMax) {
return level >= levelMin;
}
},
MinusInfinite {
@Override
boolean test(int level, int levelMin, int levelMax) {
return level <= levelMin;
}
},
Between {
@Override
boolean test(int level, int levelMin, int levelMax) {
return level >= levelMin && level <= levelMax;
}
},
Equal {
@Override
boolean test(int level, int levelMin, int levelMax) {
return level == levelMin;
}
};
abstract boolean test(int level, int levelMin, int levelMax);
}
}
}
|
9232de7070e7c5cc31c41a0ed8a2559be7a5c157 | 10,411 | java | Java | src/main/java/com/boohee/one/ui/fragment/StatusBlockFragment.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | 7 | 2017-05-30T12:01:38.000Z | 2021-04-22T12:22:39.000Z | src/main/java/com/boohee/one/ui/fragment/StatusBlockFragment.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/boohee/one/ui/fragment/StatusBlockFragment.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | 6 | 2017-07-28T03:47:08.000Z | 2019-06-28T17:57:50.000Z | 40.988189 | 100 | 0.610604 | 996,388 | package com.boohee.one.ui.fragment;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.internal.view.SupportMenu;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.boohee.api.StatusApi;
import com.boohee.database.OnePreference;
import com.boohee.model.status.Block;
import com.boohee.myview.GuidePopWindow;
import com.boohee.myview.GuidePopWindow.OnGuideClickListener;
import com.boohee.one.R;
import com.boohee.one.http.JsonCallback;
import com.boohee.one.ui.ChannelPostsActivity;
import com.boohee.one.ui.DiamondSignActivity;
import com.boohee.one.ui.HomeTimelineActivity;
import com.boohee.one.ui.MyFavoriteActivity;
import com.boohee.utility.BooheeScheme;
import com.boohee.utility.Event;
import com.boohee.utility.ImageLoaderOptions;
import com.boohee.utils.FastJsonUtils;
import com.boohee.utils.Helper;
import com.boohee.utils.ViewUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.umeng.analytics.MobclickAgent;
import java.util.List;
import org.json.JSONObject;
public class StatusBlockFragment extends BaseFragment {
@InjectView(2131428356)
TextView chatBadge;
@InjectView(2131428355)
LinearLayout chatLayout;
@InjectView(2131428350)
TextView checkInBtn;
@InjectView(2131428349)
TextView checkInMsgText;
@InjectView(2131428164)
LinearLayout collectLayout;
@InjectView(2131427647)
LinearLayout contentLayout;
@InjectView(2131428352)
TextView friendsBadge;
Handler handler = new Handler();
@InjectView(2131428354)
TextView hotBadge;
public boolean isLoadFirst = true;
private List<Block> mBlocks;
private int mCheckInCount;
@InjectView(2131427340)
PullToRefreshScrollView scrollView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.gp, container, false);
ButterKnife.inject((Object) this, view);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.scrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
public void onRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {
StatusBlockFragment.this.initUI();
}
});
}
public void loadFirst() {
new Handler().postDelayed(new Runnable() {
public void run() {
if (StatusBlockFragment.this.isLoadFirst && StatusBlockFragment.this.scrollView
!= null) {
StatusBlockFragment.this.scrollView.setRefreshing(true);
StatusBlockFragment.this.createGuidePopWindow();
}
}
}, 500);
}
private void createGuidePopWindow() {
if (getActivity() != null && !OnePreference.getInstance(getActivity()).isGuidePartner()) {
GuidePopWindow guidePopWindow = new GuidePopWindow();
guidePopWindow.init(getActivity(), R.drawable.n5);
guidePopWindow.setOnGuideClickListener(new OnGuideClickListener() {
public void onGuideClick() {
OnePreference.getInstance(StatusBlockFragment.this.getActivity())
.setGuidePartner(true);
}
});
guidePopWindow.show();
}
}
private void initUI() {
StatusApi.getHomeBlocks(getActivity(), new JsonCallback(getActivity()) {
public void ok(JSONObject object) {
super.ok(object);
if (object != null) {
StatusBlockFragment.this.mBlocks = FastJsonUtils.parseList(object.optString
("blocks"), Block.class);
StatusBlockFragment.this.initBadge(object);
StatusBlockFragment.this.initBlocks();
}
}
public void onFinish() {
super.onFinish();
StatusBlockFragment.this.isLoadFirst = false;
StatusBlockFragment.this.scrollView.onRefreshComplete();
}
});
}
private void initCheckInData(JSONObject object) {
JSONObject checkInObj = object.optJSONObject("check_in");
if (checkInObj != null) {
this.mCheckInCount = checkInObj.optInt("continue");
setCheckInUI(this.mCheckInCount, checkInObj.optBoolean("checked"));
}
}
private void setCheckInUI(int count, boolean isChecked) {
boolean z;
String message = String.format(getString(R.string.d7), new Object[]{Integer.valueOf
(count)});
SpannableString ss = new SpannableString(message);
ss.setSpan(new ForegroundColorSpan(SupportMenu.CATEGORY_MASK), 5, message.length() - 1, 33);
this.checkInMsgText.setText(ss);
this.checkInBtn.setText(isChecked ? R.string.d4 : R.string.d6);
TextView textView = this.checkInBtn;
if (isChecked) {
z = false;
} else {
z = true;
}
textView.setEnabled(z);
}
private void initBadge(JSONObject object) {
JSONObject badgeObject = object.optJSONObject("badge");
if (badgeObject != null) {
initCheckInData(badgeObject);
this.friendsBadge.setText(badgeObject.optInt("friends") > 0 ? String.valueOf
(badgeObject.optInt("friends")) : "");
this.hotBadge.setText(badgeObject.optInt("hot_posts") > 0 ? String.valueOf
(badgeObject.optInt("hot_posts")) : "");
}
}
private void initBlocks() {
if (this.mBlocks != null && this.mBlocks.size() > 0) {
this.contentLayout.removeAllViews();
for (final Block block : this.mBlocks) {
View contentView = View.inflate(getActivity(), R.layout.j7, null);
this.contentLayout.addView(contentView);
LinearLayout showMoreLayout = (LinearLayout) contentView.findViewById(R.id
.ll_show_more);
ImageView bannerImage = (ImageView) contentView.findViewById(R.id.iv_banner);
((TextView) contentView.findViewById(R.id.tv_name)).setText(block.getName());
ViewUtils.setViewScaleHeight(getActivity(), bannerImage, 640, 320);
this.imageLoader.displayImage(block.getImg(), bannerImage, ImageLoaderOptions
.randomColor());
bannerImage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MobclickAgent.onEvent(StatusBlockFragment.this.getActivity(), Event
.status_clickBlock);
BooheeScheme.handleUrl(StatusBlockFragment.this.getActivity(), block
.link_to, block.name);
}
});
if (!TextUtils.isEmpty(block.show_more)) {
showMoreLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MobclickAgent.onEvent(StatusBlockFragment.this.getActivity(), Event
.status_clickMoreContent);
BooheeScheme.handleUrl(StatusBlockFragment.this.getActivity(), block
.show_more, block.name);
}
});
}
}
}
}
@OnClick({2131427590, 2131428350, 2131428351, 2131428353, 2131428355, 2131428164})
public void onClick(View view) {
switch (view.getId()) {
case R.id.ll_check_in:
MobclickAgent.onEvent(getActivity(), Event.status_viewCheckinPage);
DiamondSignActivity.comeOnBaby(getActivity());
return;
case R.id.ll_collect:
MobclickAgent.onEvent(getActivity(), Event.status_favoritePage);
MyFavoriteActivity.comeOnBaby(getActivity());
return;
case R.id.btn_check_in:
MobclickAgent.onEvent(getActivity(), Event.status_clickCheckin);
StatusApi.checkIn(getActivity(), new JsonCallback(getActivity()) {
public void ok(JSONObject object) {
super.ok(object);
CharSequence message = object.optString("message");
if (!TextUtils.isEmpty(message)) {
Helper.showToast(message);
}
StatusBlockFragment.this.mCheckInCount = StatusBlockFragment.this
.mCheckInCount + 1;
StatusBlockFragment.this.setCheckInUI(StatusBlockFragment.this
.mCheckInCount, true);
OnePreference.setPrefSignRecord();
}
});
return;
case R.id.ll_friends:
MobclickAgent.onEvent(getActivity(), Event.status_friendTimeline);
HomeTimelineActivity.comeOnBaby(getActivity());
this.friendsBadge.setText("");
return;
case R.id.ll_hot:
MobclickAgent.onEvent(getActivity(), Event.status_hotTimeline);
ChannelPostsActivity.comeOnBaby(getActivity(), "hot_posts");
this.hotBadge.setText("");
return;
default:
return;
}
}
public void onDestroy() {
super.onDestroy();
if (!isDetached() && getActivity() != null) {
}
}
}
|
9232e03a1a93011d8456225f89516be5fc952a7e | 1,586 | java | Java | app/src/main/java/io/github/nickdex/pasteit/framework/domain/repository/UserRepository.java | nickdex/PasteIt-Android-Clean-Architecture | c73a21c81f9eb8d85eba0f8f6befddf6b0a01197 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/io/github/nickdex/pasteit/framework/domain/repository/UserRepository.java | nickdex/PasteIt-Android-Clean-Architecture | c73a21c81f9eb8d85eba0f8f6befddf6b0a01197 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/io/github/nickdex/pasteit/framework/domain/repository/UserRepository.java | nickdex/PasteIt-Android-Clean-Architecture | c73a21c81f9eb8d85eba0f8f6befddf6b0a01197 | [
"Apache-2.0"
] | null | null | null | 33.744681 | 79 | 0.715006 | 996,389 | /*
* Copyright © 2016 Nikhil Warke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.nickdex.pasteit.framework.domain.repository;
import io.github.nickdex.pasteit.framework.domain.Messenger;
import io.github.nickdex.pasteit.framework.domain.model.User;
import rx.Observable;
/**
* Interface that represents a Repository of Users.
*/
public interface UserRepository extends Repository {
/**
* A method to create the user, if it doesn't already exists in repository.
*
* @param user The user that has to be created.
* @param messenger Shows messages to the user.
* @return The unique userId of the user created or found in repository.
*/
Observable<String> createUserIfNotExists(User user, Messenger messenger);
/**
* Fetches a User by its userId.
*
* @param userId The unique id of the User to be returned.
* @param messenger Doesn't show any messages yet.
* @return The User that was found.
*/
Observable<User> getUser(final String userId, Messenger messenger);
}
|
9232e0677c968991ebbaa9c2e7c728c9cf946a09 | 1,659 | java | Java | Intern/chapter_003/src/main/java/ru/job4j/collections_framework_1/list_1_3/package-info.java | AlSidorenko/Java_from_A_to_Z | fa056ade64531bdf001e219815b9ba031793ac30 | [
"Apache-2.0"
] | null | null | null | Intern/chapter_003/src/main/java/ru/job4j/collections_framework_1/list_1_3/package-info.java | AlSidorenko/Java_from_A_to_Z | fa056ade64531bdf001e219815b9ba031793ac30 | [
"Apache-2.0"
] | null | null | null | Intern/chapter_003/src/main/java/ru/job4j/collections_framework_1/list_1_3/package-info.java | AlSidorenko/Java_from_A_to_Z | fa056ade64531bdf001e219815b9ba031793ac30 | [
"Apache-2.0"
] | null | null | null | 26.09375 | 286 | 0.648503 | 996,390 | /**
* Created on 26.03.2018.
*
* @author Aleks Sidorenko (kenaa@example.com).
* @version $Id$.
* @since 0.1.
*/
package ru.job4j.collections_framework_1.list_1_3;
/*
Конвертация ArrayList в двухмерный массив [#10035]
Каретко Виктор, 06.04.18 10:09
Вам необходимо создать класс
ConvertList2Array
Внутри методов использовать foreach.
public int[][] toArray (List<Integer> list, int rows) {} - метод toArray должен равномерно разбить лист на количество строк двумерного массива. В методе toArray должна быть проверка - если количество элементов не кратно количеству строк - оставшиеся значения в массиве заполнять нулями.
Например в результате конвертации листа со значениями (1,2,3,4,5,6,7)
с разбиением на 3 строки должен получиться двумерный массив {{1, 2, 3} {4, 5, 6} {7, 0 ,0}}
Шаблон класса.
package ru.job4j.list;
import java.util.List;
public class ConvertList2Array {
public int[][] toArray(List<Integer> list, int rows) {
int cells = ... ;
int[][] array = new int[rows][cells];
return array;
}
}
Шаблон теста.
package ru.job4j.list;
import org.junit.Test;
import java.util.Arrays;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class ConvertList2ArrayTest {
@Test
public void when7ElementsThen9() {
ConvertList2Array list = new ConvertList2Array();
int[][] result = list.toArray(
Arrays.asList(1, 2, 3, 4, 5, 6, 7),
3
);
int[][] expect = {
{1, 2, 3},
{4, 5, 6},
{7, 0 ,0}
};
assertThat(result, is(expect));
}
}
*/ |
9232e0869157ddd4dbecd57aab34012e8abc722d | 21,053 | java | Java | src/main/java/org/jetbrains/research/intellijdeodorant/core/ast/decomposition/cfg/PDGNode.java | Teej42/IntelliJDeodorant | dd29fd996c5a01f5a078b4815b054a980d9614ed | [
"MIT"
] | 55 | 2019-11-12T05:06:46.000Z | 2022-02-22T22:50:34.000Z | src/main/java/org/jetbrains/research/intellijdeodorant/core/ast/decomposition/cfg/PDGNode.java | Teej42/IntelliJDeodorant | dd29fd996c5a01f5a078b4815b054a980d9614ed | [
"MIT"
] | 220 | 2019-10-07T14:18:07.000Z | 2022-03-30T12:26:51.000Z | src/main/java/org/jetbrains/research/intellijdeodorant/core/ast/decomposition/cfg/PDGNode.java | Teej42/IntelliJDeodorant | dd29fd996c5a01f5a078b4815b054a980d9614ed | [
"MIT"
] | 15 | 2019-11-14T07:13:30.000Z | 2022-02-06T18:57:45.000Z | 50.608173 | 130 | 0.630504 | 996,391 | package org.jetbrains.research.intellijdeodorant.core.ast.decomposition.cfg;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl;
import org.jetbrains.research.intellijdeodorant.core.ast.*;
import org.jetbrains.research.intellijdeodorant.core.ast.decomposition.AbstractStatement;
import org.jetbrains.research.intellijdeodorant.core.ast.util.ExpressionExtractor;
import java.util.*;
import static org.jetbrains.research.intellijdeodorant.utils.PsiUtils.isPrimitive;
public class PDGNode extends GraphNode implements Comparable<PDGNode> {
private CFGNode cfgNode;
final Set<AbstractVariable> declaredVariables;
protected final Set<AbstractVariable> definedVariables;
protected final Set<AbstractVariable> usedVariables;
final Set<CreationObject> createdTypes;
final Set<String> thrownExceptionTypes;
private Set<VariableDeclarationObject> variableDeclarationsInMethod;
private Set<FieldObject> fieldsAccessedInMethod;
private Set<AbstractVariable> originalDefinedVariables;
private Set<AbstractVariable> originalUsedVariables;
PDGNode() {
super();
this.declaredVariables = new LinkedHashSet<>();
this.definedVariables = new LinkedHashSet<>();
this.usedVariables = new LinkedHashSet<>();
this.createdTypes = new LinkedHashSet<>();
this.thrownExceptionTypes = new LinkedHashSet<>();
}
PDGNode(CFGNode cfgNode, Set<VariableDeclarationObject> variableDeclarationsInMethod,
Set<FieldObject> fieldsAccessedInMethod) {
super();
this.cfgNode = cfgNode;
this.variableDeclarationsInMethod = variableDeclarationsInMethod;
this.fieldsAccessedInMethod = fieldsAccessedInMethod;
this.id = cfgNode.id;
cfgNode.setPDGNode(this);
this.declaredVariables = new LinkedHashSet<>();
this.definedVariables = new LinkedHashSet<>();
this.usedVariables = new LinkedHashSet<>();
this.createdTypes = new LinkedHashSet<>();
this.thrownExceptionTypes = new LinkedHashSet<>();
}
public CFGNode getCFGNode() {
return cfgNode;
}
public PDGNode getControlDependenceParent() {
for (GraphEdge edge : incomingEdges) {
PDGDependence dependence = (PDGDependence) edge;
if (dependence instanceof PDGControlDependence) {
return (PDGNode) dependence.src;
}
}
return null;
}
boolean hasIncomingControlDependenceFromMethodEntryNode() {
for (GraphEdge edge : incomingEdges) {
PDGDependence dependence = (PDGDependence) edge;
if (dependence instanceof PDGControlDependence) {
PDGNode srcNode = (PDGNode) dependence.src;
if (srcNode instanceof PDGMethodEntryNode)
return true;
}
}
return false;
}
boolean declaresLocalVariable(AbstractVariable variable) {
return declaredVariables.contains(variable);
}
boolean definesLocalVariable(AbstractVariable variable) {
return definedVariables.contains(variable);
}
boolean usesLocalVariable(AbstractVariable variable) {
return usedVariables.contains(variable);
}
boolean instantiatesLocalVariable(AbstractVariable variable) {
if (variable instanceof PlainVariable && this.definesLocalVariable(variable)) {
PlainVariable plainVariable = (PlainVariable) variable;
String variableType = plainVariable.getType();
for (CreationObject creation : createdTypes) {
if (creation instanceof ClassInstanceCreationObject) {
PsiNewExpression classInstanceCreationExpression =
((ClassInstanceCreationObject) creation).getClassInstanceCreation();
PsiReference psiReference = classInstanceCreationExpression.getReference();
if (psiReference != null) {
PsiClass referencedClass = (PsiClass) psiReference.getElement();
PsiClass superClass = referencedClass.getSuperClass();
Set<String> implementedInterfaces = new LinkedHashSet<>();
if (superClass != null && superClass.getInterfaces().length > 0) {
for (PsiClass implementedInterface : superClass.getInterfaces()) {
implementedInterfaces.add(implementedInterface.getName());
}
}
if (variableType.equals(referencedClass.getQualifiedName())
|| variableType.equals(Objects.requireNonNull(superClass).getQualifiedName())
|| implementedInterfaces.contains(variableType))
return true;
}
}
}
}
return false;
}
boolean containsClassInstanceCreation() {
return !createdTypes.isEmpty();
}
boolean throwsException() {
return !thrownExceptionTypes.isEmpty();
}
public BasicBlock getBasicBlock() {
return cfgNode.getBasicBlock();
}
public AbstractStatement getStatement() {
return cfgNode.getStatement();
}
public PsiStatement getASTStatement() {
return cfgNode.getASTStatement();
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o instanceof PDGNode) {
PDGNode pdgNode = (PDGNode) o;
return this.cfgNode.equals(pdgNode.cfgNode);
}
return false;
}
public int hashCode() {
return cfgNode.hashCode();
}
public String toString() {
return cfgNode.toString();
}
public int compareTo(PDGNode node) {
return Integer.compare(this.getId(), node.getId());
}
void updateReachingAliasSet(ReachingAliasSet reachingAliasSet) {
Set<VariableDeclarationObject> variableDeclarations = new LinkedHashSet<>();
variableDeclarations.addAll(variableDeclarationsInMethod);
variableDeclarations.addAll(fieldsAccessedInMethod);
PsiElement statement = getASTStatement();
if (statement instanceof PsiDeclarationStatement) {
PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) statement;
PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
if (declaredElements.length > 0 && declaredElements[0] instanceof PsiVariable) {
PsiVariable declaredVariable = (PsiVariable) declaredElements[0];
if (!isPrimitive(declaredVariable.getType())) {
PsiExpression initializer = declaredVariable.getInitializer();
PsiElement initializerSimpleName = null;
if (initializer != null) {
if (initializer instanceof PsiReferenceExpression) {
initializerSimpleName = ((PsiReferenceExpression) initializer).resolve();
}
if (initializerSimpleName != null) {
PsiVariable initializerVariableDeclaration = null;
for (VariableDeclarationObject declarationObject : variableDeclarations) {
PsiVariable declaration = declarationObject.getVariableDeclaration();
if (declaration.equals((initializerSimpleName))) {
initializerVariableDeclaration = declaration;
break;
}
}
if (initializerVariableDeclaration != null) {
reachingAliasSet.insertAlias(declaredVariable, initializerVariableDeclaration);
}
}
}
}
}
} else if (statement instanceof PsiExpressionStatement) {
PsiExpressionStatement expressionStatement = (PsiExpressionStatement) statement;
PsiExpression expression = expressionStatement.getExpression();
if (expression instanceof PsiAssignmentExpression) {
PsiAssignmentExpression assignment = (PsiAssignmentExpression) expression;
processAssignment(reachingAliasSet, variableDeclarations, assignment);
}
}
}
private void processAssignment(ReachingAliasSet reachingAliasSet,
Set<VariableDeclarationObject> variableDeclarations, PsiAssignmentExpression assignment) {
PsiExpression leftHandSideExpression = assignment.getLExpression();
PsiExpression rightHandSideExpression = assignment.getRExpression();
PsiElement leftHandSideElement = null;
if (leftHandSideExpression instanceof PsiReferenceExpression) {
leftHandSideElement = ((PsiReferenceExpression) leftHandSideExpression).resolve();
}
PsiVariable leftHandSideSimpleName = null;
if (leftHandSideElement instanceof PsiVariable) {
leftHandSideSimpleName = (PsiVariable) leftHandSideElement;
}
if (leftHandSideSimpleName != null && !isPrimitive(leftHandSideSimpleName.getType())) {
PsiVariable leftHandSideVariableDeclaration = null;
for (VariableDeclarationObject declarationObject : variableDeclarations) {
PsiVariable declaration = declarationObject.getVariableDeclaration();
if (declaration.equals(leftHandSideSimpleName)) {
leftHandSideVariableDeclaration = declaration;
break;
}
}
PsiElement rightHandSideSimpleName = null;
if (rightHandSideExpression instanceof PsiReferenceExpression) {
rightHandSideSimpleName = ((PsiReferenceExpression) rightHandSideExpression).resolve();
} else if (rightHandSideExpression instanceof PsiAssignmentExpression) {
PsiAssignmentExpression rightHandSideAssignment = (PsiAssignmentExpression) rightHandSideExpression;
processAssignment(reachingAliasSet, variableDeclarations, rightHandSideAssignment);
PsiExpression leftHandSideExpressionOfRightHandSideAssignment = rightHandSideAssignment.getLExpression();
PsiElement leftHandSideSimpleNameOfRightHandSideAssignment = null;
if (leftHandSideExpressionOfRightHandSideAssignment instanceof PsiReferenceExpression) {
leftHandSideSimpleNameOfRightHandSideAssignment = leftHandSideExpressionOfRightHandSideAssignment;
} else if (leftHandSideExpressionOfRightHandSideAssignment instanceof PsiVariable) {
leftHandSideSimpleNameOfRightHandSideAssignment = leftHandSideExpressionOfRightHandSideAssignment;
}
if (leftHandSideSimpleNameOfRightHandSideAssignment != null) {
rightHandSideSimpleName = leftHandSideSimpleNameOfRightHandSideAssignment;
}
}
if (rightHandSideSimpleName != null) {
PsiVariable rightHandSideVariableDeclaration = null;
for (VariableDeclarationObject declarationObject : variableDeclarations) {
PsiVariable declaration = declarationObject.getVariableDeclaration();
if (declaration.equals(rightHandSideSimpleName)) {
rightHandSideVariableDeclaration = declaration;
break;
}
}
if (leftHandSideVariableDeclaration != null && rightHandSideVariableDeclaration != null) {
reachingAliasSet.insertAlias(leftHandSideVariableDeclaration, rightHandSideVariableDeclaration);
}
} else {
if (leftHandSideVariableDeclaration != null) {
reachingAliasSet.removeAlias(leftHandSideVariableDeclaration);
}
}
}
}
void applyReachingAliasSet(ReachingAliasSet reachingAliasSet) {
if (originalDefinedVariables == null)
originalDefinedVariables = new LinkedHashSet<>(definedVariables);
Set<AbstractVariable> defVariablesToBeAdded = new LinkedHashSet<>();
for (AbstractVariable abstractVariable : originalDefinedVariables) {
if (abstractVariable instanceof CompositeVariable) {
CompositeVariable compositeVariable = (CompositeVariable) abstractVariable;
if (reachingAliasSet.containsAlias(compositeVariable)) {
Set<PsiVariable> aliases = reachingAliasSet.getAliases(compositeVariable);
for (PsiVariable alias : aliases) {
CompositeVariable aliasCompositeVariable =
new CompositeVariable(alias, compositeVariable.getRightPart());
defVariablesToBeAdded.add(aliasCompositeVariable);
}
}
}
}
definedVariables.addAll(defVariablesToBeAdded);
if (originalUsedVariables == null)
originalUsedVariables = new LinkedHashSet<>(usedVariables);
Set<AbstractVariable> useVariablesToBeAdded = new LinkedHashSet<>();
for (AbstractVariable abstractVariable : originalUsedVariables) {
if (abstractVariable instanceof CompositeVariable) {
CompositeVariable compositeVariable = (CompositeVariable) abstractVariable;
if (reachingAliasSet.containsAlias(compositeVariable)) {
Set<PsiVariable> aliases = reachingAliasSet.getAliases(compositeVariable);
for (PsiVariable alias : aliases) {
CompositeVariable aliasCompositeVariable = new CompositeVariable(alias, compositeVariable.getRightPart());
useVariablesToBeAdded.add(aliasCompositeVariable);
}
}
}
}
usedVariables.addAll(useVariablesToBeAdded);
}
Map<PsiVariable, PsiNewExpression> getClassInstantiations() {
Map<PsiVariable, PsiNewExpression> classInstantiationMap = new LinkedHashMap<>();
Set<VariableDeclarationObject> variableDeclarations = new LinkedHashSet<>();
variableDeclarations.addAll(variableDeclarationsInMethod);
variableDeclarations.addAll(fieldsAccessedInMethod);
PsiElement statement = getASTStatement();
if (statement instanceof PsiDeclarationStatement) {
PsiDeclarationStatement vDStatement = (PsiDeclarationStatement) statement;
PsiElement[] declaredElements = vDStatement.getDeclaredElements();
for (PsiElement psiElement : declaredElements) {
if (psiElement instanceof PsiVariable) {
PsiVariable psiVariable = (PsiVariable) psiElement;
PsiExpression psiExpression = psiVariable.getInitializer();
if (psiExpression instanceof PsiNewExpression) {
PsiNewExpression classInstanceCreation = (PsiNewExpression) psiExpression;
classInstantiationMap.put(psiVariable, classInstanceCreation);
}
}
}
} else if (statement instanceof PsiExpressionStatement) {
PsiExpressionStatement expressionStatement = (PsiExpressionStatement) statement;
PsiExpression expression = expressionStatement.getExpression();
ExpressionExtractor expressionExtractor = new ExpressionExtractor();
List<PsiExpression> assignments = expressionExtractor.getAssignments(expression);
for (PsiExpression assignmentExpression : assignments) {
PsiAssignmentExpression assignment = (PsiAssignmentExpression) assignmentExpression;
PsiExpression leftHandSideExpression = assignment.getLExpression();
PsiExpression rightHandSideExpression = assignment.getRExpression();
if (rightHandSideExpression instanceof PsiNewExpression) {
PsiNewExpression classInstanceCreation = (PsiNewExpression) rightHandSideExpression;
PsiElement leftHandSideSimpleName = null;
if (((PsiReferenceExpressionImpl) leftHandSideExpression).resolve() instanceof PsiVariable) {
leftHandSideSimpleName = ((PsiReferenceExpressionImpl) leftHandSideExpression).resolve();
}
if (leftHandSideSimpleName != null) {
PsiVariable leftHandSideVariableDeclaration = null;
for (VariableDeclarationObject declarationObject : variableDeclarations) {
PsiVariable declaration = declarationObject.getVariableDeclaration();
if (declaration.equals(leftHandSideSimpleName)) {
leftHandSideVariableDeclaration = declaration;
break;
}
}
if (leftHandSideVariableDeclaration != null) {
classInstantiationMap.put(leftHandSideVariableDeclaration, classInstanceCreation);
}
}
}
}
}
return classInstantiationMap;
}
boolean changesStateOfReference(PsiVariable variableDeclaration) {
for (AbstractVariable abstractVariable : definedVariables) {
if (abstractVariable instanceof CompositeVariable) {
CompositeVariable compositeVariable = (CompositeVariable) abstractVariable;
if (variableDeclaration.equals(compositeVariable.getOrigin()))
return true;
}
}
return false;
}
boolean accessesReference(PsiVariable variableDeclaration) {
for (AbstractVariable abstractVariable : usedVariables) {
if (abstractVariable instanceof PlainVariable) {
PlainVariable plainVariable = (PlainVariable) abstractVariable;
if (variableDeclaration.equals(plainVariable.getOrigin()))
return true;
}
}
return false;
}
boolean assignsReference(PsiVariable variableDeclaration) {
PsiElement statement = getASTStatement();
if (statement instanceof PsiDeclarationStatement) {
PsiDeclarationStatement vDStatement = (PsiDeclarationStatement) statement;
PsiElement[] psiElements = vDStatement.getDeclaredElements();
for (PsiElement psiElement : psiElements) {
if (psiElement instanceof PsiVariable) {
PsiVariable psiVariable = (PsiVariable) psiElement;
PsiExpression initializer = psiVariable.getInitializer();
PsiElement initializerSimpleName = null;
if (initializer instanceof PsiReferenceExpression) {
PsiElement element = ((PsiReferenceExpression) initializer).resolve();
if (element instanceof PsiVariable) {
initializerSimpleName = element;
}
}
if (initializerSimpleName != null) {
if (variableDeclaration.equals(initializerSimpleName)) {
return true;
}
}
}
}
} else if (statement instanceof PsiExpressionStatement) {
PsiExpressionStatement expressionStatement = (PsiExpressionStatement) statement;
PsiExpression expression = expressionStatement.getExpression();
ExpressionExtractor expressionExtractor = new ExpressionExtractor();
List<PsiExpression> assignments = expressionExtractor.getAssignments(expression);
for (PsiExpression assignmentExpression : assignments) {
PsiAssignmentExpression assignment = (PsiAssignmentExpression) assignmentExpression;
PsiExpression rightHandSideExpression = assignment.getRExpression();
PsiElement rightHandSideSimpleName = null;
if (rightHandSideExpression instanceof PsiReferenceExpression) {
rightHandSideSimpleName = ((PsiReferenceExpression) rightHandSideExpression).resolve();
}
if (rightHandSideSimpleName != null) {
if (variableDeclaration.equals(rightHandSideSimpleName)) {
return true;
}
}
}
}
return false;
}
}
|
9232e1722ce7d62206e447ffda002b4e18cda9cd | 489 | java | Java | src/Cell.java | samonuall/Conways_Game_of_Life | 5793b7a25e6b6742ce511ff74bf0b49820f452c5 | [
"MIT"
] | null | null | null | src/Cell.java | samonuall/Conways_Game_of_Life | 5793b7a25e6b6742ce511ff74bf0b49820f452c5 | [
"MIT"
] | null | null | null | src/Cell.java | samonuall/Conways_Game_of_Life | 5793b7a25e6b6742ce511ff74bf0b49820f452c5 | [
"MIT"
] | null | null | null | 13.971429 | 49 | 0.619632 | 996,392 | public class Cell {
private int row, col;
private boolean isAlive;
public Cell(int row, int col, boolean isAlive) {
this.row = row;
this.col = col;
this.isAlive = isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public boolean getAlive() {
return isAlive;
}
public String toString() {
if(isAlive) {
return "*";
}else {
return ".";
}
}
}
|
9232e2e324557e1da9956e2db8f379f430de07ba | 544 | java | Java | client/synapseJavaClient/src/main/java/org/sagebionetworks/client/exceptions/SynapseUnauthorizedException.java | txk1452/Synapse-Repository-Services | e530afb283e6afa0ba6df090138a0f76101370ed | [
"Apache-2.0"
] | null | null | null | client/synapseJavaClient/src/main/java/org/sagebionetworks/client/exceptions/SynapseUnauthorizedException.java | txk1452/Synapse-Repository-Services | e530afb283e6afa0ba6df090138a0f76101370ed | [
"Apache-2.0"
] | null | null | null | client/synapseJavaClient/src/main/java/org/sagebionetworks/client/exceptions/SynapseUnauthorizedException.java | txk1452/Synapse-Repository-Services | e530afb283e6afa0ba6df090138a0f76101370ed | [
"Apache-2.0"
] | null | null | null | 20.148148 | 74 | 0.770221 | 996,393 | package org.sagebionetworks.client.exceptions;
/**
* Exception throw for HTTP status code of 401.
*/
public class SynapseUnauthorizedException extends SynapseServerException {
private static final long serialVersionUID = 1L;
public SynapseUnauthorizedException() {
super();
}
public SynapseUnauthorizedException(String message, Throwable cause) {
super(message, cause);
}
public SynapseUnauthorizedException(String message) {
super(message);
}
public SynapseUnauthorizedException(Throwable cause) {
super(cause);
}
}
|
9232e3595bb643d9c03cb55edd1fe82e09d0392e | 591 | java | Java | app/src/main/java/io/github/mayunfei/simple/apt/GlideRequests.java | MaYunFei/GlideTest | 555dd7ed1f16144cb7ab98ba5ba1160ca4b45d7f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/io/github/mayunfei/simple/apt/GlideRequests.java | MaYunFei/GlideTest | 555dd7ed1f16144cb7ab98ba5ba1160ca4b45d7f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/io/github/mayunfei/simple/apt/GlideRequests.java | MaYunFei/GlideTest | 555dd7ed1f16144cb7ab98ba5ba1160ca4b45d7f | [
"Apache-2.0"
] | null | null | null | 32.833333 | 107 | 0.798646 | 996,394 | package io.github.mayunfei.simple.apt;
import io.github.mayunfei.simple.Glide;
import io.github.mayunfei.simple.RequestManager;
import io.github.mayunfei.simple.manager.Lifecycle;
import io.github.mayunfei.simple.manager.RequestManagerTreeNode;
/**
* 如果在同一个 activity 或者是 同一个 fragment 会得到同一个 GlideRequests,也就是 RequestManager
* Created by mayunfei on 17-9-4.
*/
public class GlideRequests extends RequestManager {
public GlideRequests(Glide glide, Lifecycle lifecycle, RequestManagerTreeNode requestManagerTreeNode) {
super(glide, lifecycle, requestManagerTreeNode);
}
}
|
9232e37dd3e13ece03fa5411b4370100ae2c06c1 | 3,942 | java | Java | commons-dict-wordnet-indexbyname/src/main/java/org/swtk/commons/dict/wordnet/indexbyname/controller/v/o/WordnetNounIndexNameControllerVO.java | torrances/swtk-commons | 78ee97835e4437d91fd4ba0cf6ccab40be5c8889 | [
"Apache-2.0"
] | null | null | null | commons-dict-wordnet-indexbyname/src/main/java/org/swtk/commons/dict/wordnet/indexbyname/controller/v/o/WordnetNounIndexNameControllerVO.java | torrances/swtk-commons | 78ee97835e4437d91fd4ba0cf6ccab40be5c8889 | [
"Apache-2.0"
] | null | null | null | commons-dict-wordnet-indexbyname/src/main/java/org/swtk/commons/dict/wordnet/indexbyname/controller/v/o/WordnetNounIndexNameControllerVO.java | torrances/swtk-commons | 78ee97835e4437d91fd4ba0cf6ccab40be5c8889 | [
"Apache-2.0"
] | null | null | null | 91.674419 | 446 | 0.810249 | 996,395 | package org.swtk.commons.dict.wordnet.indexbyname.controller.v.o; import java.util.Collection; import java.util.Set; import java.util.TreeSet; import org.swtk.common.dict.dto.wordnet.IndexNoun; import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.c.WordnetNounIndexNameInstanceVOC;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.d.WordnetNounIndexNameInstanceVOD;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.g.WordnetNounIndexNameInstanceVOG;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.i.WordnetNounIndexNameInstanceVOI;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.l.WordnetNounIndexNameInstanceVOL;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.m.WordnetNounIndexNameInstanceVOM;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.n.WordnetNounIndexNameInstanceVON;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.o.WordnetNounIndexNameInstanceVOO;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.r.WordnetNounIndexNameInstanceVOR;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.t.WordnetNounIndexNameInstanceVOT;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.u.WordnetNounIndexNameInstanceVOU;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.w.WordnetNounIndexNameInstanceVOW;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.y.WordnetNounIndexNameInstanceVOY;
import org.swtk.commons.dict.wordnet.indexbyname.instance.v.o.z.WordnetNounIndexNameInstanceVOZ;
import com.trimc.blogger.commons.exception.BusinessException; public final class WordnetNounIndexNameControllerVO { public static Collection<IndexNoun> get(final String TERM) throws BusinessException { if (TERM.length() < 3) throw new BusinessException("TERM not found (term = %s)", TERM); String key = TERM.replaceAll(" ", "").substring(0, 3).toLowerCase(); if ("voc".equals(key)) return WordnetNounIndexNameInstanceVOC.get(TERM);
if ("vod".equals(key)) return WordnetNounIndexNameInstanceVOD.get(TERM);
if ("vog".equals(key)) return WordnetNounIndexNameInstanceVOG.get(TERM);
if ("voi".equals(key)) return WordnetNounIndexNameInstanceVOI.get(TERM);
if ("vol".equals(key)) return WordnetNounIndexNameInstanceVOL.get(TERM);
if ("vom".equals(key)) return WordnetNounIndexNameInstanceVOM.get(TERM);
if ("von".equals(key)) return WordnetNounIndexNameInstanceVON.get(TERM);
if ("voo".equals(key)) return WordnetNounIndexNameInstanceVOO.get(TERM);
if ("vor".equals(key)) return WordnetNounIndexNameInstanceVOR.get(TERM);
if ("vot".equals(key)) return WordnetNounIndexNameInstanceVOT.get(TERM);
if ("vou".equals(key)) return WordnetNounIndexNameInstanceVOU.get(TERM);
if ("vow".equals(key)) return WordnetNounIndexNameInstanceVOW.get(TERM);
if ("voy".equals(key)) return WordnetNounIndexNameInstanceVOY.get(TERM);
if ("voz".equals(key)) return WordnetNounIndexNameInstanceVOZ.get(TERM);
throw new BusinessException("TERM not found (term = %s)", TERM); } public static Collection<String> terms() throws BusinessException { Set<String> set = new TreeSet<String>(); set.addAll(WordnetNounIndexNameInstanceVOC.terms());
set.addAll(WordnetNounIndexNameInstanceVOD.terms());
set.addAll(WordnetNounIndexNameInstanceVOG.terms());
set.addAll(WordnetNounIndexNameInstanceVOI.terms());
set.addAll(WordnetNounIndexNameInstanceVOL.terms());
set.addAll(WordnetNounIndexNameInstanceVOM.terms());
set.addAll(WordnetNounIndexNameInstanceVON.terms());
set.addAll(WordnetNounIndexNameInstanceVOO.terms());
set.addAll(WordnetNounIndexNameInstanceVOR.terms());
set.addAll(WordnetNounIndexNameInstanceVOT.terms());
set.addAll(WordnetNounIndexNameInstanceVOU.terms());
set.addAll(WordnetNounIndexNameInstanceVOW.terms());
set.addAll(WordnetNounIndexNameInstanceVOY.terms());
set.addAll(WordnetNounIndexNameInstanceVOZ.terms());
return set; } } |
9232e4b8114e85e559475716cd5e387004e9c502 | 859 | java | Java | inventory-domain/src/main/java/io/joamit/inventory/domain/part/PartManufacturer.java | joamit/inventory | 2ad14a6feb92981b5180c9a9d6b91e59caf7ea4a | [
"MIT"
] | 12 | 2017-11-29T22:11:58.000Z | 2022-01-26T14:39:02.000Z | inventory-domain/src/main/java/io/joamit/inventory/domain/part/PartManufacturer.java | joamit/inventory | 2ad14a6feb92981b5180c9a9d6b91e59caf7ea4a | [
"MIT"
] | 1 | 2019-06-12T09:35:54.000Z | 2019-06-12T09:35:54.000Z | inventory-domain/src/main/java/io/joamit/inventory/domain/part/PartManufacturer.java | joamit/inventory | 2ad14a6feb92981b5180c9a9d6b91e59caf7ea4a | [
"MIT"
] | 1 | 2018-01-10T08:41:15.000Z | 2018-01-10T08:41:15.000Z | 20.95122 | 60 | 0.689173 | 996,396 | package io.joamit.inventory.domain.part;
import io.joamit.inventory.domain.BaseDocument;
import io.joamit.inventory.domain.misc.Manufacturer;
import org.springframework.data.mongodb.core.mapping.DBRef;
public class PartManufacturer extends BaseDocument {
@DBRef
private Part part;
@DBRef
private Manufacturer manufacturer;
private String partNumber;
public Part getPart() {
return part;
}
public void setPart(Part part) {
this.part = part;
}
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
}
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
}
|
9232e5ac4a6089b1a6195859c624d5b7872cfdb5 | 11,681 | java | Java | opensrp-gizi/src/main/java/util/growthchart/GrowthChartGenerator.java | sid-indonesia/opensrp-client-sid | 556159126bf61dbbc704b019601a1f6274d6cf86 | [
"Apache-2.0"
] | 1 | 2018-05-25T14:56:44.000Z | 2018-05-25T14:56:44.000Z | opensrp-gizi/src/main/java/util/growthchart/GrowthChartGenerator.java | sid-indonesia/opensrp-client-sid | 556159126bf61dbbc704b019601a1f6274d6cf86 | [
"Apache-2.0"
] | 22 | 2017-10-13T01:01:24.000Z | 2019-02-12T17:00:01.000Z | opensrp-gizi/src/main/java/util/growthchart/GrowthChartGenerator.java | sid-indonesia/opensrp-client-sid | 556159126bf61dbbc704b019601a1f6274d6cf86 | [
"Apache-2.0"
] | 5 | 2018-04-09T05:11:59.000Z | 2021-01-04T03:13:58.000Z | 38.807309 | 135 | 0.603544 | 996,397 | package util.growthchart;
import android.graphics.Color;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.util.ArrayList;
public class GrowthChartGenerator {
private GraphView graph;
private LineGraphSeries<DataPoint> series1 = new LineGraphSeries<>();
private LineGraphSeries<DataPoint> series2 = new LineGraphSeries<>();
private LineGraphSeries<DataPoint> series3 = new LineGraphSeries<>();
private LineGraphSeries<DataPoint> series4 = new LineGraphSeries<>();
private LineGraphSeries<DataPoint> series5 = new LineGraphSeries<>();
private LineGraphSeries<DataPoint> series6 = new LineGraphSeries<>();
private LineGraphSeries<DataPoint> series7 = new LineGraphSeries<>();
// LineGraphSeries<DataPoint> seriesMain = new LineGraphSeries<DataPoint>();
private double [][]graphLine;
private String xValue;
private String yValue;
private String dateOfBirth;
private String gender;
private LineGraphSeries [][]a;
/**
* age shift used to shift X-Axis value so the axis value will start from (0 + ageShift) value,
* currently used when generating height for age chart.
*/
private int ageShift = 0;
private int index = 0;
private boolean[]chartDisplay = {true,true,true};
private final int red = Color.rgb(255,0,0);
private final int yellow = Color.rgb(255,255,0);
private final int green = Color.rgb(0,255,0);
private final int blue = Color.rgb(0,32,255);
private final int purple = Color.rgb(239,0,255);
private final int orange = Color.rgb(255,111,0);
private final int []zScoreChartColor = {blue,purple,orange};
public GrowthChartGenerator(GraphView graph,String gender,String dateOfBirth, String xValue,String yValue){
this.graph = graph;
this.xValue = xValue;
this.yValue = yValue;
this.dateOfBirth=dateOfBirth;
this.gender = gender;
//System.out.println("XValue: "+xValue);
//System.out.println("YValue: "+yValue);
//System.out.println("DOB : "+dateOfBirth);
//System.out.println("gender: "+gender);
a = new LineGraphSeries[3][];
graphLine = this.gender.toLowerCase().contains("em") ? GraphConstant.girlWeightChart : GraphConstant.boyWeightChart;
buildGraphTemplate();
}
public GrowthChartGenerator(GraphView graph,int graphStyle, String gender,String dateOfBirth, String xValue,String yValue){
this.graph = graph;
this.dateOfBirth=dateOfBirth;
this.gender = gender;
a = new LineGraphSeries[3][];
switch (graphStyle){
case GraphConstant.WFA_CHART : initWeightForAgeChart(xValue, yValue);
break;
case GraphConstant.HFA_CHART : initHeightForAgeChart(xValue, yValue);
break;
case GraphConstant.LFA_CHART : initLengthForAgeChart(xValue, yValue);
break;
case GraphConstant.Z_SCORE_CHART : initzScoreChart(xValue, yValue);
break;
default:
}
}
private void initStage(){
graph.setBackgroundColor(Color.rgb(215, 215, 215));
graph.getViewport().setScrollable(true);
graph.getViewport().setScalable(true);
}
private void initLengthForAgeChart(String xValue, String yValue){
this.xValue = xValue;
this.yValue = yValue;
graphLine = gender.toLowerCase().contains("em") ? GraphConstant.girlLengthChart : GraphConstant.boyLengthChart;
buildGraphTemplate();
}
private void initHeightForAgeChart(String xValue, String yValue){
this.ageShift = 24;
this.xValue = xValue;
this.yValue = yValue;
graphLine = gender.toLowerCase().contains("em") ? GraphConstant.girlHeightChart : GraphConstant.boyHeightChart;
buildGraphTemplate();
}
private void initWeightForAgeChart(String xValue, String yValue){
this.xValue = xValue;
this.yValue = yValue;
graphLine = gender.toLowerCase().contains("em") ? GraphConstant.girlWeightChart : GraphConstant.boyWeightChart;
buildGraphTemplate();
}
private void initzScoreChart(String xValue, String yValue){
this.xValue = xValue;
this.yValue = yValue;
graphLine = GraphConstant.zScoreBackground();
buildGraphTemplate();
}
private void buildGraphTemplate() {
initStage();
initSeries(series1, Color.argb(255,215,215,215), red, 5);
initSeries(series2, Color.argb(192, 255, 255, 0), yellow, 5);
initSeries(series3, Color.argb(128, 128, 255, 128), green, 5);
initSeries(series4, Color.argb(30, 0, 135, 0), green, 5);
initSeries(series5, Color.argb(30, 0, 40, 0), green, 5);
initSeries(series6, Color.argb(128, 0, 255, 0), green, 5);
initSeries(series7, Color.argb(128, 255, 255, 0), yellow, 5);
// initSeries(seriesMain, Color.argb(0, 0, 0, 0), Color.BLUE, 3, "weight", true);
for(int i=0;i<graphLine.length;i++){
series1.appendData(new DataPoint(i+ageShift,graphLine[i][0]),false,62);
series2.appendData(new DataPoint(i+ageShift,graphLine[i][1]),false,62);
series3.appendData(new DataPoint(i+ageShift,graphLine[i][2]),false,62);
series4.appendData(new DataPoint(i+ageShift,graphLine[i][3]),false,62);
series5.appendData(new DataPoint(i+ageShift,graphLine[i][4]),false,62);
series6.appendData(new DataPoint(i+ageShift,graphLine[i][5]),false,62);
series7.appendData(new DataPoint(i+ageShift,graphLine[i][6]),false,62);
}
graph.addSeries(series7);
graph.addSeries(series6);
graph.addSeries(series5);
graph.addSeries(series4);
graph.addSeries(series3);
graph.addSeries(series2);
graph.addSeries(series1);
if(xValue.contains("@"))
createLineChart(graph,dateOfBirth,xValue.split("@"),yValue.split("@"));
else
createLineChart(graph,dateOfBirth,xValue,yValue);
// //System.out.println("length of a = "+a[0].length + ","+a[1].length + ","+a[2].length);
}
//
// private void initSeries(LineGraphSeries<DataPoint> series, int backGround, int color, int thick,String title, boolean putStroke){
// series.setTitle(title);
// this.initSeries(series, backGround, color, thick);
// if(putStroke){
// series.setDrawDataPoints(true);
// series.setDataPointsRadius(5);
// }
// }
private void initSeries(LineGraphSeries<DataPoint> series, int backGround, int color, int thick){
series.setDrawBackground(true);
series.setBackgroundColor(backGround);
series.setColor(color);
series.setThickness(thick);
}
private LineGraphSeries<DataPoint>createDataSeries(String []age,String []weight){
LineGraphSeries<DataPoint>series=new LineGraphSeries<>();
series.setDrawDataPoints(true);
int dataPointRadius = 7;
series.setDataPointsRadius(dataPointRadius);
series.setColor(zScoreChartColor[index]);
if(age[0]!=null)
series.appendData(new DataPoint(Double.parseDouble(age[0]), Double.parseDouble(weight[0])), false, 70);
for(int i=0;i<age.length;i++){
series.appendData(new DataPoint(Double.parseDouble(age[i]), Double.parseDouble(weight[i])), false, 70);
}
return series;
}
private void createLineChart(GraphView graph, String dateOfBirth, String date,String weight){
int counter = 0;
if("".equals(date)||" ".equals(date))
return;
int[]dateInt = calculateAgesFrom(dateOfBirth, date.split(","));
String []weightDouble = weight.split(",");
int length = countAgeSeries(dateInt);
String []axis = new String[length];
String[] series = new String[length];
if(!"0".equals(weightDouble[0])){
series[0]=weightDouble[0];
axis[0]=Integer.toString(dateInt[0]);
}
for(int i=1;i<dateInt.length;i++){
if(dateInt[i]-dateInt[i-1]>1)
counter++;
if(series[counter]==null){
series[counter]=weightDouble[i];
axis[counter]=Integer.toString(dateInt[i]);
}
else{
series[counter] = series[counter]+","+weightDouble[i];
axis[counter]=axis[counter]+","+Integer.toString(dateInt[i]);
}
}
//System.out.println("index of line 172 = "+index);
ArrayList<LineGraphSeries> list = new ArrayList<>();
LineGraphSeries<DataPoint> temp;
for(int i=0;i<series.length;i++){
if(series[i]==null)
continue;
try {
temp = createDataSeries(axis[i].split(","), series[i].split(","));
graph.addSeries(temp);
list.add(temp);
} catch(Exception e){
e.printStackTrace();
}
}
a[index]=new LineGraphSeries[list.size()];
for(int i=0;i<list.size();i++){
a[index][i]=list.get(i);
}
}
private void createLineChart(GraphView graph, String dateOfBirth, String[]date, String[]value){
//System.out.println("date length = "+date.length);
for(int i=0;i<date.length;i++){
this.index=i;
// System.out.println("Z Score line chart : "+i);
// System.out.println("date "+i+" : "+date[i]);
// System.out.println("value "+i+" : "+value[i]);
if(i>=date.length || i>=value.length) // prevent null data on chart
break;
createLineChart(graph, dateOfBirth, date[i], value[i]);
}
}
private int[]calculateAgesFrom(String dateOfBirth,String []data){
int[]result=new int[data.length];
if(data[0].length()>5) {
for (int i = 0; i < data.length; i++) {
result[i] = getMonthAge(dateOfBirth, data[i]);
}
}else{
for (int i=0;i<data.length;i++){
result[i]=Integer.parseInt(data[i]);
}
}
return result;
}
private int getMonthAge(String start,String end){
if(start.length()<7 || end.length()<7)
return 0;
return ((Integer.parseInt(end.substring(0,4)) - Integer.parseInt(start.substring(0,4)))*12 +
(Integer.parseInt(end.substring(5,7)) - Integer.parseInt(start.substring(5,7))));
}
private int countAgeSeries(int[]data){
int counter=data[0]==0? 0:1;
for(int i=1;i<data.length-1;i++){
if(data[i]-data[i-1]==0 && data[i+1]-data[i]==2)
data[i]++;
else if(data[i]-data[i-1]==2 && data[i+1]-data[i]==0)
data[i]--;
}
for(int i=0;i<data.length-1;i++){
if(data[i+1]-data[i]>1)
counter++;
}
return counter+1;
}
public void putSeriesOfIndex(int idx){
index = idx;
if(!chartDisplay[index] && a[index]!=null){
for(int i=0;i<a[index].length;i++){
graph.addSeries(a[index][i]);
}
chartDisplay[index]=true;
}
}
public void removeSeriesOfIndex(int idx){
index=idx;
if(chartDisplay[index] && a[index]!=null){
for(int i=0;i<a[index].length;i++) {
graph.removeSeries(a[index][i]);
}
chartDisplay[index]=false;
}
}
}
|
9232e5b23aaf9bff22eadee5299a4145df821259 | 9,286 | java | Java | core/src/main/java/ru/wildbot/core/vk/callback/server/VkCallbackHandler.java | wildbot-project/WildBot | c78690ec8e6208c6bf6dc532e208ae967ff175dc | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2017-09-18T13:25:38.000Z | 2020-06-06T15:06:04.000Z | core/src/main/java/ru/wildbot/core/vk/callback/server/VkCallbackHandler.java | wildbot-project/WildBot | c78690ec8e6208c6bf6dc532e208ae967ff175dc | [
"ECL-2.0",
"Apache-2.0"
] | 60 | 2017-10-02T18:02:09.000Z | 2020-10-12T17:35:32.000Z | core/src/main/java/ru/wildbot/core/vk/callback/server/VkCallbackHandler.java | wildbot-project/WildBot | c78690ec8e6208c6bf6dc532e208ae967ff175dc | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2017-09-16T09:51:37.000Z | 2019-02-21T19:37:33.000Z | 39.181435 | 103 | 0.758884 | 996,398 | /*
* Copyright 2017 Peter P. (JARvis PROgrammer)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.wildbot.core.vk.callback.server;
import com.vk.api.sdk.callback.CallbackApi;
import com.vk.api.sdk.callback.objects.board.CallbackBoardPostDelete;
import com.vk.api.sdk.callback.objects.group.*;
import com.vk.api.sdk.callback.objects.market.CallbackMarketComment;
import com.vk.api.sdk.callback.objects.market.CallbackMarketCommentDelete;
import com.vk.api.sdk.callback.objects.messages.CallbackMessageAllow;
import com.vk.api.sdk.callback.objects.messages.CallbackMessageDeny;
import com.vk.api.sdk.callback.objects.photo.CallbackPhotoComment;
import com.vk.api.sdk.callback.objects.photo.CallbackPhotoCommentDelete;
import com.vk.api.sdk.callback.objects.poll.CallbackPollVoteNew;
import com.vk.api.sdk.callback.objects.user.CallbackUserBlock;
import com.vk.api.sdk.callback.objects.user.CallbackUserUnblock;
import com.vk.api.sdk.callback.objects.video.CallbackVideoComment;
import com.vk.api.sdk.callback.objects.video.CallbackVideoCommentDelete;
import com.vk.api.sdk.callback.objects.wall.CallbackWallComment;
import com.vk.api.sdk.callback.objects.wall.CallbackWallCommentDelete;
import com.vk.api.sdk.objects.audio.Audio;
import com.vk.api.sdk.objects.board.TopicComment;
import com.vk.api.sdk.objects.messages.Message;
import com.vk.api.sdk.objects.photos.Photo;
import com.vk.api.sdk.objects.video.Video;
import com.vk.api.sdk.objects.wall.WallPost;
import ru.wildbot.core.WildBotCore;
import ru.wildbot.core.api.event.EventManager;
import ru.wildbot.core.vk.callback.event.*;
public class VkCallbackHandler extends CallbackApi {
private EventManager eventManager;
public VkCallbackHandler() {
this.eventManager = WildBotCore.getInstance().getEventManager();
}
@Override
public void messageNew(final Integer groupId, final Message message) {
eventManager.callEvents(new VkMessageNewEvent(groupId, message));
}
@Override
public void messageReply(final Integer groupId, final Message message) {
eventManager.callEvents(new VkMessageReplyEvent(groupId, message));
}
@Override
public void messageAllow(final Integer groupId, final CallbackMessageAllow message) {
eventManager.callEvents(new VkMessageAllowEvent(groupId, message));
}
@Override
public void messageDeny(final Integer groupId, final CallbackMessageDeny message) {
eventManager.callEvents(new VkMessageDenyEvent(groupId, message));
}
@Override
public void photoNew(final Integer groupId, final Photo message) {
eventManager.callEvents(new VkPhotoNewEvent(groupId, message));
}
@Override
public void photoCommentNew(final Integer groupId, final CallbackPhotoComment message) {
eventManager.callEvents(new VkPhotoCommandNewEvent(groupId, message));
}
@Override
public void photoCommentEdit(final Integer groupId, final CallbackPhotoComment message) {
eventManager.callEvents(new VkPhotoCommentEditEvent(groupId, message));
}
@Override
public void photoCommentRestore(final Integer groupId, final CallbackPhotoComment message) {
eventManager.callEvents(new VkPhotoCommentRestoreEvent(groupId, message));
}
@Override
public void photoCommentDelete(final Integer groupId, final CallbackPhotoCommentDelete message) {
eventManager.callEvents(new VkPhotoCommentDeleteEvent(groupId, message));
}
@Override
public void audioNew(final Integer groupId, final Audio message) {
eventManager.callEvents(new VkAudioNewEvent(groupId, message));
}
@Override
public void videoNew(final Integer groupId, final Video message) {
eventManager.callEvents(new VkVideoNewEvent(groupId, message));
}
@Override
public void videoCommentNew(final Integer groupId, final CallbackVideoComment message) {
eventManager.callEvents(new VkVideoCommentNewEvent(groupId, message));
}
@Override
public void videoCommentEdit(final Integer groupId, final CallbackVideoComment message) {
eventManager.callEvents(new VkVideoCommentEditEvent(groupId, message));
}
@Override
public void videoCommentRestore(final Integer groupId, final CallbackVideoComment message) {
eventManager.callEvents(new VkVideoCommentRestoreEvent(groupId, message));
}
@Override
public void videoCommentDelete(final Integer groupId, final CallbackVideoCommentDelete message) {
eventManager.callEvents(new VkVideoCommentDeleteEvent(groupId, message));
}
@Override
public void wallPostNew(final Integer groupId, final WallPost message) {
eventManager.callEvents(new VkWallPostNewEvent(groupId, message));
}
@Override
public void wallRepost(final Integer groupId, final WallPost message) {
eventManager.callEvents(new VkWallRepostEvent(groupId, message));
}
@Override
public void wallReplyNew(final Integer groupId, final CallbackWallComment object) {
eventManager.callEvents(new VkWallReplyNewEvent(groupId, object));
}
@Override
public void wallReplyEdit(final Integer groupId, final CallbackWallComment message) {
eventManager.callEvents(new VkWallReplyEditEvent(groupId, message));
}
@Override
public void wallReplyRestore(final Integer groupId, final CallbackWallComment message) {
eventManager.callEvents(new VkWallReplyRestoreEvent(groupId, message));
}
@Override
public void wallReplyDelete(final Integer groupId, final CallbackWallCommentDelete message) {
eventManager.callEvents(new VkWallReplyDeleteEvent(groupId, message));
}
@Override
public void boardPostNew(final Integer groupId, final TopicComment message) {
eventManager.callEvents(new VkBoardPostNewEvent(groupId, message));
}
@Override
public void boardPostEdit(final Integer groupId, final TopicComment message) {
eventManager.callEvents(new VkBoardPostEditEvent(groupId, message));
}
@Override
public void boardPostRestore(final Integer groupId, final TopicComment message) {
eventManager.callEvents(new VkBoardPostRestoreEvent(groupId, message));
}
@Override
public void boardPostDelete(final Integer groupId, final CallbackBoardPostDelete message) {
eventManager.callEvents(new VkBoardPostDeleteEvent(groupId, message));
}
@Override
public void marketCommentNew(final Integer groupId, final CallbackMarketComment message) {
eventManager.callEvents(new VkMarketCommentNewEvent(groupId, message));
}
@Override
public void marketCommentEdit(final Integer groupId, final CallbackMarketComment message) {
eventManager.callEvents(new VkMarketCommentEditEvent(groupId, message));
}
@Override
public void marketCommentRestore(final Integer groupId, final CallbackMarketComment message) {
eventManager.callEvents(new VkMarketCommentRestoreEvent(groupId, message));
}
@Override
public void marketCommentDelete(final Integer groupId, final CallbackMarketCommentDelete message) {
eventManager.callEvents(new VkMarketCommentDeleteEvent(groupId, message));
}
@Override
public void groupLeave(final Integer groupId, final CallbackGroupLeave message) {
eventManager.callEvents(new VkGroupLeaveEvent(groupId, message));
}
@Override
public void groupJoin(final Integer groupId, final CallbackGroupJoin message) {
eventManager.callEvents(new VkGroupJoinEvent(groupId, message));
}
@Override
public void groupChangeSettings(final Integer groupId, final CallbackGroupChangeSettings message) {
eventManager.callEvents(new VkGroupChangeSettingsEvent(groupId, message));
}
@Override
public void groupChangePhoto(final Integer groupId, final CallbackGroupChangePhoto message) {
eventManager.callEvents(new VkGroupChangePhotoEvent(groupId, message));
}
@Override
public void groupOfficersEdit(final Integer groupId, final CallbackGroupOfficersEdit message) {
eventManager.callEvents(new VkGroupOfficersEditEvent(groupId, message));
}
@Override
public void pollVoteNew(final Integer groupId, final CallbackPollVoteNew message) {
eventManager.callEvents(new VkPollVoteNewEvent(groupId, message));
}
@Override
public void userBlock(final Integer groupId, final CallbackUserBlock message) {
eventManager.callEvents(new VkUserBlockEvent(groupId, message));
}
@Override
public void userUnblock(final Integer groupId, final CallbackUserUnblock message) {
eventManager.callEvents(new VkUserUnblockEvent(groupId, message));
}
}
|
9232e69608a22449b64f94c567eb26e62409e709 | 3,683 | java | Java | acm-module-sys/src/main/java/com/wisdom/acm/sys/service/ProjectTeamService.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | acm-module-sys/src/main/java/com/wisdom/acm/sys/service/ProjectTeamService.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | acm-module-sys/src/main/java/com/wisdom/acm/sys/service/ProjectTeamService.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | 24.553333 | 132 | 0.66902 | 996,399 | package com.wisdom.acm.sys.service;
import com.github.pagehelper.PageInfo;
import com.wisdom.acm.sys.form.JlSectionAddForm;
import com.wisdom.acm.sys.form.ProjectTeamAddForm;
import com.wisdom.acm.sys.form.ProjectTeamUpdateForm;
import com.wisdom.acm.sys.po.OrgSectionRelation;
import com.wisdom.acm.sys.vo.ProjectTeamUserVo;
import com.wisdom.acm.sys.vo.ProjectTeamVo;
import com.wisdom.acm.sys.vo.SysRoleVo;
import java.util.List;
import java.util.Map;
public interface ProjectTeamService {
/**
* 项目团队(不含标段)
* @param projectId
* @return
*/
List<ProjectTeamVo> queryProjectTeam(int projectId);
/**
* 删除业务数据时删除项目团队
* @param bizType 业务数据类型
* @param bizId 业务ID
* @return
*/
List<Integer> deleteByBiz(String bizType, Integer bizId);
int add(ProjectTeamAddForm form);
int update(ProjectTeamUpdateForm form);
void delete(List<Integer> ids);
ProjectTeamVo get(Integer id);
List<ProjectTeamVo> queryProjectTeamList(String bizType, Integer bizId);
List<ProjectTeamVo> queryProjectTeamTree(String bizType, Integer bizId);
/**
* 查询团队下的用户信息
* @param teamId
* @return
*/
List<ProjectTeamUserVo> queryUserListByTeamId(Integer teamId);
/**
* 为项目团队分配用户
* @param teamId
* @param users
*/
void assignUser(Integer teamId, List<Map<String,Object>> users);
/**
* 修改团队下的用户的角色
* @param teamId
* @param userId
* @param roleIds
*/
void updateUserRole(Integer teamId, Integer userId, List<Integer> roleIds);
/**
* 导入团队
* @param dataSource
* @param bizType
* @param bizId
* @param parentId
* @param data
*/
void importProjectTeam(String dataSource,String bizType, Integer bizId,Integer parentId,Map<String,Object> data );
/**
* 复制项目团队
* @param sourceBizType
* @param sourceBizId
* @param targetBizType
* @param targetBizId
* @param teamCanEmpty false:抛出异常
*/
void copyProjectTeam(String sourceBizType, Integer sourceBizId, String targetBizType, Integer targetBizId,boolean teamCanEmpty);
/**
* 删除项目团队下用户
* @param ids
*/
void deleteUsers(List<Integer> ids);
String queryLoggers(Integer teamId, List<Map<String, Object>> data);
String queryTeamUserlogger(List<Integer> ids);
/**
* 项目团队排序
* @return
*/
List<ProjectTeamVo> updateProjectTeamSortByIdAndUpOrDown(Integer id,String upOrDown);
/**
* 团队成员排序
* @param id
* @param teamId
* @param upOrDown
* @return
*/
List<ProjectTeamUserVo> updateProjectTeamUserSortByIdAndUpdateOrDown(Integer teamId,Integer id,String upOrDown);
/**
* 查询项目下 用户角色
* @param projectId
* @param userId
* @return
*/
List<SysRoleVo> queryRoleListByProjectIdAndUserId(Integer projectId, Integer userId);
/**
* 查询施工标下的监理标
* @param sectionId
* @param pageSize
* @param currentPageNum
* @return
*/
PageInfo<ProjectTeamVo> selectJlSectionList(Integer sectionId, Integer pageSize, Integer currentPageNum);
/**
* 查询需要分配的监理标
* @param sectionId
* @return
*/
List<ProjectTeamVo> selectXyJlSectionList(Integer sectionId);
/**
* 批量增加监理标
* @param jlSectionAddForms
*/
void addJlSection(List<JlSectionAddForm> jlSectionAddForms);
/**
* 批量删除监理标
* @param jlSectionAddForms
*/
void deleteJlSection(List<JlSectionAddForm> jlSectionAddForms);
void updateOrgSectionRelation(int sectionId, OrgSectionRelation relation);
OrgSectionRelation getOrgSectionRelation(int sectionId);
}
|
9232e7f4a4c8ed62bbfb5af842399eb02ffbec59 | 197 | java | Java | whois-query/src/main/java/net/ripe/db/whois/query/dao/Inet6numDao.java | WEBZCC/whois | 5babbb0ef5456cfac96270789c320d226d26e9ee | [
"BSD-3-Clause"
] | 362 | 2015-01-21T16:20:23.000Z | 2022-03-29T08:25:37.000Z | whois-query/src/main/java/net/ripe/db/whois/query/dao/Inet6numDao.java | WEBZCC/whois | 5babbb0ef5456cfac96270789c320d226d26e9ee | [
"BSD-3-Clause"
] | 370 | 2015-01-05T17:00:34.000Z | 2022-03-31T13:34:07.000Z | whois-query/src/main/java/net/ripe/db/whois/query/dao/Inet6numDao.java | WEBZCC/whois | 5babbb0ef5456cfac96270789c320d226d26e9ee | [
"BSD-3-Clause"
] | 96 | 2015-05-01T15:57:45.000Z | 2022-02-15T08:21:22.000Z | 19.7 | 50 | 0.77665 | 996,400 | package net.ripe.db.whois.query.dao;
import net.ripe.db.whois.common.iptree.Ipv6Entry;
import java.util.List;
public interface Inet6numDao {
List<Ipv6Entry> findByNetname(String netname);
}
|
9232e942c8e137c0242f0cf750379d180ef9959f | 1,113 | java | Java | src/main/java/com/fijo/cores/admin/authority/mapper/SysPermissionMapper.java | bozongz/fijo-cores | da0c3d94daa88444db42bed5d2625d5527d94b18 | [
"Apache-2.0"
] | 1 | 2019-01-18T18:38:04.000Z | 2019-01-18T18:38:04.000Z | src/main/java/com/fijo/cores/admin/authority/mapper/SysPermissionMapper.java | bozongz/fijo-cores | da0c3d94daa88444db42bed5d2625d5527d94b18 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/fijo/cores/admin/authority/mapper/SysPermissionMapper.java | bozongz/fijo-cores | da0c3d94daa88444db42bed5d2625d5527d94b18 | [
"Apache-2.0"
] | null | null | null | 30.081081 | 126 | 0.779874 | 996,401 | package com.fijo.cores.admin.authority.mapper;
import java.util.List;
import com.fijo.cores.mapper.ISystemMapper;
import org.apache.ibatis.annotations.Param;
import com.fijo.cores.admin.authority.model.SysPermission;
import com.fijo.cores.mapper.ISystemMapper;
public interface SysPermissionMapper extends ISystemMapper<SysPermission,Integer> {
SysPermission getRoot();
List<SysPermission> getExcludeRoot();
List<SysPermission> getByRole(Integer roleId);
/** 系统扩展 基于用户-资源直接授权时使用 Start **/
List<SysPermission> getSysUserPermission(Integer userId);
int deleteSysUserPermissionByUserId(@Param(value = "userId")Integer userId);
int createSysUserPermission(@Param(value = "userId")Integer userId, @Param(value = "permissionId")Integer permissionId);
/** 系统扩展 基于用户-资源直接授权时使用 End **/
List<SysPermission> getByParent(Integer id);
List<SysPermission> getByMoudle(@Param(value = "loginName")String loginName);
List<SysPermission> getByParentMenu(@Param(value = "parentId")Integer parentId, @Param(value = "loginName")String loginName);
List<SysPermission> getMenu(Integer userId);
}
|
9232e9b2f00c27ff572cdaeb30a7eb279ed23052 | 15,809 | java | Java | base/common/src/main/java/org/artifactory/util/HttpClientConfigurator.java | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | 3 | 2016-01-21T11:49:08.000Z | 2018-12-11T21:02:11.000Z | base/common/src/main/java/org/artifactory/util/HttpClientConfigurator.java | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | null | null | null | base/common/src/main/java/org/artifactory/util/HttpClientConfigurator.java | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | 5 | 2015-12-08T10:22:21.000Z | 2021-06-15T16:14:00.000Z | 39.131188 | 119 | 0.652919 | 996,402 | /*
* Artifactory is a binaries repository manager.
* Copyright (C) 2014 JFrog Ltd.
*
* Artifactory 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.
*
* Artifactory 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 Artifactory. If not, see <http://www.gnu.org/licenses/>.
*/
package org.artifactory.util;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.artifactory.common.ConstantValues;
import org.artifactory.descriptor.repo.ProxyDescriptor;
import org.artifactory.security.crypto.CryptoHelper;
import org.artifactory.util.bearer.BearerSchemeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Builder for HTTP client.
*
* @author Yossi Shaul
*/
public class HttpClientConfigurator {
private static final Logger log = LoggerFactory.getLogger(HttpClientConfigurator.class);
private HttpClientBuilder builder = HttpClients.custom();
private RequestConfig.Builder config = RequestConfig.custom();
private String host;
private BasicCredentialsProvider credsProvider;
boolean explicitCookieSupport;
public HttpClientConfigurator() {
builder.setUserAgent(HttpUtils.getArtifactoryUserAgent());
credsProvider = new BasicCredentialsProvider();
handleGzipResponse(ConstantValues.httpAcceptEncodingGzip.getBoolean());
config.setMaxRedirects(20);
config.setCircularRedirectsAllowed(true);
}
public CloseableHttpClient getClient() {
if (!explicitCookieSupport && !ConstantValues.enableCookieManagement.getBoolean()) {
builder.disableCookieManagement();
}
if (hasCredentials()) {
builder.setDefaultCredentialsProvider(credsProvider);
}
return builder.setDefaultRequestConfig(config.build()).build();
}
public HttpClientConfigurator keepAliveStrategy() {
ConnectionKeepAliveStrategy keepAliveStrategy = getConnectionKeepAliveStrategy();
builder.setKeepAliveStrategy(keepAliveStrategy);
return this;
}
/**
* provide a custom keep-alive strategy
*
* @return keep-alive strategy to be used for connection pool
*/
private ConnectionKeepAliveStrategy getConnectionKeepAliveStrategy() {
return new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
// Honor 'keep-alive' header
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
HttpHost target = (HttpHost) context.getAttribute(
HttpClientContext.HTTP_TARGET_HOST);
if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
return 5 * 1000;
} else {
return 30 * 1000;
}
}
};
}
/**
* set customized Pooling Http Client Connection Manager
*
* @param connectionManager - custom PoolingHttpClientConnectionManager
* @return Http Client Configurator
*/
public HttpClientConfigurator connectionMgr(PoolingHttpClientConnectionManager connectionManager) {
builder.setConnectionManager(connectionManager);
return this;
}
/**
* Disable the automatic gzip compression on read.
* Once disabled cannot be activated.
*/
public HttpClientConfigurator handleGzipResponse(boolean handleGzipResponse) {
if (!handleGzipResponse) {
builder.disableContentCompression();
}
return this;
}
/**
* May throw a runtime exception when the given URL is invalid.
*/
public HttpClientConfigurator hostFromUrl(String urlStr) {
if (StringUtils.isNotBlank(urlStr)) {
try {
URL url = new URL(urlStr);
host(url.getHost());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Cannot parse the url " + urlStr, e);
}
}
return this;
}
/**
* Ignores blank values
*/
public HttpClientConfigurator host(String host) {
if (StringUtils.isNotBlank(host)) {
this.host = host;
builder.setRoutePlanner(new DefaultHostRoutePlanner(host));
}
return this;
}
public HttpClientConfigurator defaultMaxConnectionsPerHost(int maxConnectionsPerHost) {
builder.setMaxConnPerRoute(maxConnectionsPerHost);
return this;
}
public HttpClientConfigurator maxTotalConnections(int maxTotalConnections) {
builder.setMaxConnTotal(maxTotalConnections);
return this;
}
public HttpClientConfigurator connectionTimeout(int connectionTimeout) {
config.setConnectTimeout(connectionTimeout);
return this;
}
public HttpClientConfigurator soTimeout(int soTimeout) {
config.setSocketTimeout(soTimeout);
return this;
}
/**
* see {@link org.apache.http.client.config.RequestConfig#isStaleConnectionCheckEnabled()}
*/
public HttpClientConfigurator staleCheckingEnabled(boolean staleCheckingEnabled) {
config.setStaleConnectionCheckEnabled(staleCheckingEnabled);
return this;
}
/**
* Disable request retries on service unavailability.
*/
public HttpClientConfigurator noRetry() {
return retry(0, false);
}
/**
* Number of retry attempts. Default is 3 retries.
*
* @param retryCount Number of retry attempts. 0 means no retries.
*/
public HttpClientConfigurator retry(int retryCount, boolean requestSentRetryEnabled) {
if (retryCount == 0) {
builder.disableAutomaticRetries();
} else {
builder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, requestSentRetryEnabled));
}
return this;
}
/**
* Ignores blank or invalid input
*/
public HttpClientConfigurator localAddress(String localAddress) {
if (StringUtils.isNotBlank(localAddress)) {
try {
InetAddress address = InetAddress.getByName(localAddress);
config.setLocalAddress(address);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid local address: " + localAddress, e);
}
}
return this;
}
/**
* Ignores null credentials
*/
public HttpClientConfigurator authentication(UsernamePasswordCredentials creds) {
if (creds != null) {
authentication(creds.getUserName(), creds.getPassword());
}
return this;
}
/**
* Configures preemptive authentication on this client. Ignores blank username input.
*/
public HttpClientConfigurator authentication(String username, String password) {
return authentication(username, password, false);
}
/**
* Configures preemptive authentication on this client. Ignores blank username input.
*/
public HttpClientConfigurator authentication(String username, String password, boolean allowAnyHost) {
if (StringUtils.isNotBlank(username)) {
if (StringUtils.isBlank(host)) {
throw new IllegalStateException("Cannot configure authentication when host is not set.");
}
AuthScope authscope = allowAnyHost ?
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM) :
new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
credsProvider.setCredentials(
authscope, new UsernamePasswordCredentials(username, password));
builder.addInterceptorFirst(new PreemptiveAuthInterceptor());
}
return this;
}
/**
* Enable cookie management for this client.
*/
public HttpClientConfigurator enableCookieManagement(boolean enableCookieManagement) {
if (enableCookieManagement) {
config.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);
} else {
config.setCookieSpec(null);
}
explicitCookieSupport = enableCookieManagement;
return this;
}
public HttpClientConfigurator enableTokenAuthentication(boolean enableTokenAuthentication,
String username, String password) {
if (enableTokenAuthentication) {
if (StringUtils.isBlank(host)) {
throw new IllegalStateException("Cannot configure authentication when host is not set.");
}
config.setTargetPreferredAuthSchemes(Collections.singletonList("Bearer"));
// We need dummy credentials otherwise we won't respond to a challenge properly
AuthScope authScope = new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// Dummy:dummy is the specification for forcing token authentication
UsernamePasswordCredentials dummyCredentials = new UsernamePasswordCredentials("dummy", "dummy");
credsProvider.setCredentials(authScope, dummyCredentials);
// The real credentials are passed to the Bearer that will get the token with them
UsernamePasswordCredentials realCredentials = null;
if (StringUtils.isNotBlank(username)) {
realCredentials = new UsernamePasswordCredentials(username, password);
}
Registry<AuthSchemeProvider> bearerRegistry = RegistryBuilder.<AuthSchemeProvider>create()
.register("Bearer", new BearerSchemeFactory(realCredentials))
.build();
builder.setDefaultAuthSchemeRegistry(bearerRegistry);
}
return this;
}
public HttpClientConfigurator proxy(@Nullable ProxyDescriptor proxyDescriptor) {
configureProxy(proxyDescriptor);
return this;
}
private void configureProxy(ProxyDescriptor proxy) {
if (proxy != null) {
config.setProxy(new HttpHost(proxy.getHost(), proxy.getPort()));
if (proxy.getUsername() != null) {
Credentials creds = null;
if (proxy.getDomain() == null) {
creds = new UsernamePasswordCredentials(proxy.getUsername(),
CryptoHelper.decryptIfNeeded(proxy.getPassword()));
//This will demote the NTLM authentication scheme so that the proxy won't barf
//when we try to give it traditional credentials. If the proxy doesn't do NTLM
//then this won't hurt it (jcej at tragus dot org)
List<String> authPrefs = Arrays.asList(AuthSchemes.DIGEST, AuthSchemes.BASIC, AuthSchemes.NTLM);
config.setProxyPreferredAuthSchemes(authPrefs);
// preemptive proxy authentication
builder.addInterceptorFirst(new ProxyPreemptiveAuthInterceptor());
} else {
try {
String ntHost =
StringUtils.isBlank(proxy.getNtHost()) ? InetAddress.getLocalHost().getHostName() :
proxy.getNtHost();
creds = new NTCredentials(proxy.getUsername(),
CryptoHelper.decryptIfNeeded(proxy.getPassword()), ntHost, proxy.getDomain());
} catch (UnknownHostException e) {
log.error("Failed to determine required local hostname for NTLM credentials.", e);
}
}
if (creds != null) {
credsProvider.setCredentials(
new AuthScope(proxy.getHost(), proxy.getPort(), AuthScope.ANY_REALM), creds);
if (proxy.getRedirectedToHostsList() != null) {
for (String hostName : proxy.getRedirectedToHostsList()) {
credsProvider.setCredentials(
new AuthScope(hostName, AuthScope.ANY_PORT, AuthScope.ANY_REALM), creds);
}
}
}
}
}
}
private boolean hasCredentials() {
return credsProvider.getCredentials(AuthScope.ANY) != null;
}
static class DefaultHostRoutePlanner extends DefaultRoutePlanner {
private final HttpHost defaultHost;
public DefaultHostRoutePlanner(String defaultHost) {
super(DefaultSchemePortResolver.INSTANCE);
this.defaultHost = new HttpHost(defaultHost);
}
@Override
public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
if (host == null) {
host = defaultHost;
}
return super.determineRoute(host, request, context);
}
public HttpHost getDefaultHost() {
return defaultHost;
}
}
}
|
9232eaaa7020c3d5ee08bc665daea79848b9819b | 1,584 | java | Java | cow-server/src/main/java/org/wiredwidgets/cow/server/parse/BPMN2SaxParser.java | smart-cow/scow | 8c18327605f863bbcaf897bab701f78e98c08de8 | [
"Apache-2.0"
] | null | null | null | cow-server/src/main/java/org/wiredwidgets/cow/server/parse/BPMN2SaxParser.java | smart-cow/scow | 8c18327605f863bbcaf897bab701f78e98c08de8 | [
"Apache-2.0"
] | 5 | 2017-05-08T14:40:58.000Z | 2017-05-09T19:18:33.000Z | cow-server/src/main/java/org/wiredwidgets/cow/server/parse/BPMN2SaxParser.java | smart-cow/scow | 8c18327605f863bbcaf897bab701f78e98c08de8 | [
"Apache-2.0"
] | null | null | null | 29.886792 | 115 | 0.706439 | 996,403 | /**
* Approved for Public Release: 10-4800. Distribution Unlimited.
* Copyright 2014 The MITRE Corporation,
* 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.wiredwidgets.cow.server.parse;
import org.wiredwidgets.cow.server.api.service.Deployment;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author FITZPATRICK
*/
public class BPMN2SaxParser extends DefaultHandler{
private Deployment deploy;
public BPMN2SaxParser(){
deploy = new Deployment();
}
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException{
if (qName.equalsIgnoreCase("process")){
deploy.setId(attributes.getValue("id"));
deploy.setName(attributes.getValue("name"));
deploy.setState("active");
}
}
public Deployment getDeployment(){
return deploy;
}
}
|
9232eb13f91e5a78d3d6f7f0378fb1d4bbd82b71 | 2,567 | java | Java | src/test/java/com/codeborne/selenide/collections/NoneMatchTest.java | IrinaStyazhkina/selenide | 8673b408a3e1872f0b437a838da5c66d978ab3ba | [
"MIT"
] | 780 | 2018-10-09T22:33:24.000Z | 2022-03-30T16:44:57.000Z | src/test/java/com/codeborne/selenide/collections/NoneMatchTest.java | IrinaStyazhkina/selenide | 8673b408a3e1872f0b437a838da5c66d978ab3ba | [
"MIT"
] | 723 | 2018-10-09T22:13:30.000Z | 2022-03-29T12:08:10.000Z | src/test/java/com/codeborne/selenide/collections/NoneMatchTest.java | sidelnikovmike/selenide | 1ec66993f0e1c722d247811c3d63c8cbc5b138ea | [
"MIT"
] | 346 | 2015-01-06T12:26:38.000Z | 2018-10-09T18:50:36.000Z | 36.15493 | 117 | 0.721854 | 996,404 | package com.codeborne.selenide.collections;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.ex.ElementNotFound;
import com.codeborne.selenide.ex.MatcherError;
import com.codeborne.selenide.impl.CollectionSource;
import org.junit.jupiter.api.Test;
import static com.codeborne.selenide.Mocks.mockCollection;
import static com.codeborne.selenide.Mocks.mockElement;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
final class NoneMatchTest {
private final SelenideElement element1 = mockElement("Test-One");
private final SelenideElement element2 = mockElement("Test-Two");
private final SelenideElement element3 = mockElement("Test-Three");
private final CollectionSource collection = mockCollection("Collection description", element1, element2, element3);
@Test
void applyWithEmptyList() {
assertThat(new NoneMatch("Predicate description", it -> it.getText().equals("EmptyList"))
.test(mockCollection("Collection description").getElements()))
.isFalse();
}
@Test
void applyWithMatchingPredicate() {
assertThat(new NoneMatch("Predicate description", it -> it.getText().contains("Test"))
.test(collection.getElements()))
.isFalse();
}
@Test
void applyWithNonMatchingPredicate() {
assertThat(new NoneMatch("Predicate description", it -> it.getText().equals("NotPresent"))
.test(collection.getElements()))
.isTrue();
}
@Test
void failOnEmptyCollection() {
assertThatThrownBy(() ->
new NoneMatch("Predicate description", it -> it.getText().equals("Test"))
.fail(mockCollection("Collection description"),
emptyList(),
new Exception("Exception message"), 10000))
.isInstanceOf(ElementNotFound.class);
}
@Test
void failOnMatcherError() {
assertThatThrownBy(() ->
new NoneMatch("Predicate description", it -> it.getText().contains("One"))
.fail(collection,
collection.getElements(),
new Exception("Exception message"), 10000))
.isInstanceOf(MatcherError.class)
.hasMessageStartingWith(String.format("Collection matcher error" +
"%nExpected: none of elements to match [Predicate description] predicate" +
"%nCollection: Collection description"));
}
@Test
void testToString() {
assertThat(new NoneMatch("Predicate description", it -> true))
.hasToString("none match [Predicate description] predicate");
}
}
|
9232ec5d54245b79f55264b9a19462c38b586876 | 1,592 | java | Java | src/main/java/com/tivconsultancy/opentiv/imageproc/primitives/ImagePointInt.java | TIVConsultancy/openTIV | 13d36303e6d28599aa38af89086b82f92b2476e2 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tivconsultancy/opentiv/imageproc/primitives/ImagePointInt.java | TIVConsultancy/openTIV | 13d36303e6d28599aa38af89086b82f92b2476e2 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tivconsultancy/opentiv/imageproc/primitives/ImagePointInt.java | TIVConsultancy/openTIV | 13d36303e6d28599aa38af89086b82f92b2476e2 | [
"Apache-2.0"
] | null | null | null | 26.983051 | 75 | 0.651382 | 996,405 | /*
* Copyright 2020 TIVConsultancy.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tivconsultancy.opentiv.imageproc.primitives;
import com.tivconsultancy.opentiv.helpfunctions.matrix.MatrixEntry;
import java.io.Serializable;
/**
*
* @author Thomas Ziegenhein
*/
public class ImagePointInt extends MatrixEntry implements Serializable{
private static final long serialVersionUID = -6921653534671180391L;
public boolean bMarker = false;
public ImagePointInt(int i, int j) {
super(i, j);
}
public ImagePointInt(MatrixEntry me) {
super(me.i, me.j);
}
public ImagePointInt(ImagePoint op) {
super(op.getPos().y, op.getPos().x);
}
@Override
public boolean equals(Object o) {
if(this == null || o == null){
return false;
}
if (!(o instanceof ImagePointInt)) {
return false;
}
if (((ImagePointInt) o).i == this.i
&& ((ImagePointInt) o).j == this.j) {
return true;
}
return false;
}
}
|
9232ec78e69553ea066b69f47d18dad9989fa233 | 26,239 | java | Java | modules/tcpmon-eclipse-plugin/src/main/java/org/apache/ws/commons/tcpmon/eclipse/ui/Listener.java | antvale/tcpmon | 79e4a9038f8e047e6fba0264e9d7a29b33d12cc5 | [
"Apache-2.0"
] | null | null | null | modules/tcpmon-eclipse-plugin/src/main/java/org/apache/ws/commons/tcpmon/eclipse/ui/Listener.java | antvale/tcpmon | 79e4a9038f8e047e6fba0264e9d7a29b33d12cc5 | [
"Apache-2.0"
] | null | null | null | modules/tcpmon-eclipse-plugin/src/main/java/org/apache/ws/commons/tcpmon/eclipse/ui/Listener.java | antvale/tcpmon | 79e4a9038f8e047e6fba0264e9d7a29b33d12cc5 | [
"Apache-2.0"
] | null | null | null | 41.062598 | 134 | 0.584702 | 996,406 | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ws.commons.tcpmon.eclipse.ui;
import org.apache.ws.commons.tcpmon.TCPMonBundle;
import org.apache.ws.commons.tcpmon.core.engine.Interceptor;
import org.apache.ws.commons.tcpmon.core.engine.InterceptorConfiguration;
import org.apache.ws.commons.tcpmon.core.engine.InterceptorConfigurationBuilder;
import org.apache.ws.commons.tcpmon.core.engine.RequestResponseListener;
import org.apache.ws.commons.tcpmon.core.ui.AbstractListener;
import org.apache.ws.commons.tcpmon.core.ui.Configuration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.Vector;
/**
* This is similar to the main swing listener but includes SWT components instead of Swing ones
*
*/
class Listener extends AbstractListener {
private Composite leftPanel = null;
private Composite rightPanel = null;
private Composite textComposite = null;
private Text portField = null;
private Text hostField = null;
private Text tPortField = null;
private Button isProxyBox = null;
private Button stopButton = null;
public Button removeButton = null;
public Button removeAllButton = null;
private Button xmlFormatBox = null;
public Button saveButton = null;
public Button resendButton = null;
public Table connectionTable = null;
public TableEnhancer tableEnhancer = null;
private TabFolder tabFolder;
private TabItem portTabItem;
private Interceptor interceptor = null;
public final Vector requestResponses = new Vector();
private final InterceptorConfiguration baseConfiguration;
public Listener(TabFolder tabFolder, String name,
InterceptorConfiguration config) {
if (name == null) {
name = TCPMonBundle.getMessage("port01", "Port") + " " + config.getListenPort();
}
baseConfiguration = config;
this.tabFolder = tabFolder;
createPortTab(config);
}
public void createPortTab(InterceptorConfiguration config) {
portTabItem = new TabItem(tabFolder, SWT.NONE);
final Composite composite = new Composite(tabFolder, SWT.NONE);
GridLayout gl = new GridLayout();
gl.numColumns = 8;
composite.setLayout(gl);
portTabItem.setControl(composite);
stopButton = new Button(composite, SWT.NONE);
GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, false);
gd.widthHint = 71;
stopButton.setLayoutData(gd);
final String start = TCPMonBundle.getMessage("start00", "Start");
stopButton.setText(start);
final Label listenPortLabel = new Label(composite, SWT.NONE);
gd = new GridData();
gd.horizontalIndent = 5;
listenPortLabel.setLayoutData(gd);
listenPortLabel.setText(TCPMonBundle.getMessage("listenPort01", "Listen Port:"));
portField = new Text(composite, SWT.BORDER);
portField.setText("" + config.getListenPort());
gd = new GridData(SWT.FILL, SWT.CENTER, false, false);
gd.widthHint = 40;
portField.setLayoutData(gd);
(new Label(composite, SWT.NONE)).setText(TCPMonBundle.getMessage("host00", "Host:"));
hostField = new Text(composite, SWT.BORDER);
hostField.setText(config.getTargetHost());
gd = new GridData(SWT.FILL, SWT.CENTER, false, false);
gd.widthHint = 202;
hostField.setLayoutData(gd);
(new Label(composite, SWT.NONE)).setText(TCPMonBundle.getMessage("port02", "Port:"));
tPortField = new Text(composite, SWT.BORDER);
tPortField.setText("" + config.getTargetPort());
gd = new GridData(SWT.FILL, SWT.CENTER, false, false);
gd.widthHint = 40;
tPortField.setLayoutData(gd);
isProxyBox = new Button(composite, SWT.LEFT | SWT.CHECK);
isProxyBox.setAlignment(SWT.LEFT);
gd = new GridData(64, SWT.DEFAULT);
gd.verticalIndent = 2;
gd.horizontalIndent = 10;
isProxyBox.setLayoutData(gd);
isProxyBox.setText(TCPMonBundle.getMessage("proxy00", "Proxy"));
isProxyBox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
boolean state = ((Button) e.getSource()).getSelection();
tPortField.setEnabled(!state);
hostField.setEnabled(!state);
}
});
isProxyBox.setSelection(config.isProxy());
portField.setEditable(false);
hostField.setEditable(false);
tPortField.setEditable(false);
stopButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (stopButton.getText().equals(TCPMonBundle.getMessage("stop00", "Stop"))) {
stop();
} else {
start();
}
}
});
connectionTable = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
connectionTable.setHeaderVisible(true);
gd = new GridData(SWT.LEFT, SWT.FILL, true, false, 8, 1);
gd.heightHint = 102;
connectionTable.setLayoutData(gd);
final TableColumn stateColumn = new TableColumn(connectionTable, SWT.CENTER);
stateColumn.setWidth(47);
stateColumn.setText(TCPMonBundle.getMessage("state00", "State"));
final TableColumn timeColumn = new TableColumn(connectionTable, SWT.CENTER);
timeColumn.setWidth(100);
timeColumn.setText(TCPMonBundle.getMessage("time00", "Time"));
final TableColumn reqHostColumn = new TableColumn(connectionTable, SWT.CENTER);
reqHostColumn.setWidth(100);
reqHostColumn.setText(TCPMonBundle.getMessage("requestHost00", "Request Host"));
final TableColumn targetHostColumn = new TableColumn(connectionTable, SWT.CENTER);
targetHostColumn.setWidth(100);
targetHostColumn.setText(TCPMonBundle.getMessage("targetHost", "Target Host"));
final TableColumn requestColumn = new TableColumn(connectionTable, SWT.CENTER);
requestColumn.setWidth(100);
requestColumn.setText(TCPMonBundle.getMessage("request00", "Request..."));
final TableColumn elapsedTimeColumn = new TableColumn(connectionTable, SWT.CENTER);
elapsedTimeColumn.setWidth(140);
elapsedTimeColumn.setText(TCPMonBundle.getMessage("elapsed00", "Elapsed Time"));
final TableItem headerItem = new TableItem(connectionTable, SWT.BORDER);
headerItem.setText(new String[]{"--", "Most Recent", "--", "--", "--", "--"});
tableEnhancer = new TableEnhancer(connectionTable);
// SelectionListener part goes here - I THINK IT'S DONE
connectionTable.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleSelection();
}
});
final Composite buttonComposite = new Composite(composite, SWT.NONE);
buttonComposite.setLayout(new RowLayout());
gd = new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1);
gd.heightHint = 32;
gd.widthHint = 59;
buttonComposite.setLayoutData(gd);
removeButton = new Button(buttonComposite, SWT.NONE);
RowData rd = new RowData();
rd.width = 100;
removeButton.setLayoutData(rd);
final String removeSelected = TCPMonBundle.getMessage("removeSelected00", "Remove Selected");
removeButton.setText(removeSelected);
removeButton.setEnabled(false);
removeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (removeSelected.equals(((Button) e.getSource()).getText())) {
remove();
}
}
});
removeAllButton = new Button(buttonComposite, SWT.NONE);
rd = new RowData();
rd.width = 100;
removeAllButton.setLayoutData(rd);
final String removeAll = TCPMonBundle.getMessage("removeAll00", "Remove All");
removeAllButton.setText(removeAll);
removeAllButton.setEnabled(false);
removeAllButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (removeAll.equals(((Button) e.getSource()).getText())) {
removeAll();
}
}
});
textComposite = new Composite(composite, SWT.NONE);
textComposite.setLayout(new FillLayout(SWT.VERTICAL));
gd = new GridData(SWT.FILL, SWT.CENTER, false, false, 8, 1);
gd.widthHint = 589;
gd.heightHint = 230;
textComposite.setLayoutData(gd);
leftPanel = new Composite(textComposite, SWT.BORDER);
leftPanel.setLayout(new GridLayout(8, true));
rightPanel = new Composite(textComposite, SWT.BORDER);
rightPanel.setLayout(new GridLayout(8, true));
xmlFormatBox = new Button(composite, SWT.CHECK);
xmlFormatBox.setText(TCPMonBundle.getMessage("xmlFormat00", "XML Format"));
final Composite buttonComposite2 = new Composite(composite, SWT.NONE);
buttonComposite2.setLayout(new RowLayout());
gd = new GridData(SWT.FILL, SWT.FILL, false, false, 4, 1);
gd.heightHint = 27;
gd.widthHint = 27;
buttonComposite2.setLayoutData(gd);
saveButton = new Button(buttonComposite2, SWT.NONE);
rd = new RowData();
rd.width = 100;
saveButton.setLayoutData(rd);
final String save = TCPMonBundle.getMessage("save00", "Save");
saveButton.setText(save);
saveButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (save.equals(((Button) e.getSource()).getText())) {
save();
}
}
});
resendButton = new Button(buttonComposite2, SWT.NONE);
rd = new RowData();
rd.width = 100;
resendButton.setLayoutData(rd);
final String resend = TCPMonBundle.getMessage("resend00", "Resend");
resendButton.setText(resend);
resendButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (resend.equals(((Button) e.getSource()).getText())) {
resend();
}
}
});
Button switchButton = new Button(buttonComposite2, SWT.NONE);
rd = new RowData();
rd.width = 100;
switchButton.setLayoutData(rd);
final String switchStr = TCPMonBundle.getMessage("switch00", "Switch Layout");
switchButton.setText(switchStr);
switchButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (switchStr.equals(((Button) e.getSource()).getText())) {
if (((FillLayout) textComposite.getLayout()).type == SWT.HORIZONTAL) {
((FillLayout) textComposite.getLayout()).type = SWT.VERTICAL;
} else {
((FillLayout) textComposite.getLayout()).type = SWT.HORIZONTAL;
}
leftPanel.layout();
rightPanel.layout();
textComposite.layout();
}
}
});
final Composite buttonComposite3 = new Composite(composite, SWT.NONE);
buttonComposite3.setLayout(new RowLayout());
gd = new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1);
gd.horizontalIndent = 95;
gd.heightHint = 27;
gd.widthHint = 27;
buttonComposite3.setLayoutData(gd);
Button closeButton = new Button(buttonComposite3, SWT.None);
rd = new RowData();
rd.width = 60;
closeButton.setLayoutData(rd);
final String close = TCPMonBundle.getMessage("close00", "Close");
closeButton.setText(close);
closeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (close.equals(((Button) e.getSource()).getText())) {
close();
}
}
});
tableEnhancer.setSelectionInterval(0, 0);
start();
}
public void handleSelection() {
if (tableEnhancer.isSelectionEmpty()) {
setLeft(MainView.SWT_LABEL, " " + TCPMonBundle.getMessage("wait00",
"Waiting for Connection..."));
setRight(MainView.SWT_LABEL, "");
removeButton.setEnabled(false);
removeAllButton.setEnabled(false);
saveButton.setEnabled(false);
resendButton.setEnabled(false);
leftPanel.layout();
rightPanel.layout();
textComposite.layout();
} else {
int row = tableEnhancer.getLeadSelectionIndex();
if (row != tableEnhancer.getMaxSelectionIndex()) {
row = tableEnhancer.getMaxSelectionIndex();
}
if (row == 0) {
if (requestResponses.size() == 0) {
setLeft(MainView.SWT_LABEL, " " + TCPMonBundle.getMessage("wait00",
"Waiting for connection..."));
setRight(MainView.SWT_LABEL, "");
removeButton.setEnabled(false);
removeAllButton.setEnabled(false);
saveButton.setEnabled(false);
resendButton.setEnabled(false);
leftPanel.layout();
rightPanel.layout();
textComposite.layout();
} else {
RequestResponse requestResponse = (RequestResponse) requestResponses.lastElement();
removeChildren(leftPanel.getChildren());
removeChildren(rightPanel.getChildren());
((GridData) requestResponse.inputText.getLayoutData()).exclude = false;
requestResponse.inputText.setVisible(true);
((GridData) requestResponse.outputText.getLayoutData()).exclude = false;
requestResponse.outputText.setVisible(true);
removeButton.setEnabled(false);
removeAllButton.setEnabled(true);
saveButton.setEnabled(true);
resendButton.setEnabled(true);
leftPanel.layout();
rightPanel.layout();
textComposite.layout();
}
} else {
RequestResponse requestResponse = (RequestResponse) requestResponses.get(row - 1);
removeChildren(leftPanel.getChildren());
removeChildren(rightPanel.getChildren());
((GridData) requestResponse.inputText.getLayoutData()).exclude = false;
requestResponse.inputText.setVisible(true);
((GridData) requestResponse.outputText.getLayoutData()).exclude = false;
requestResponse.outputText.setVisible(true);
removeButton.setEnabled(true);
removeAllButton.setEnabled(true);
saveButton.setEnabled(true);
resendButton.setEnabled(true);
leftPanel.layout();
rightPanel.layout();
textComposite.layout();
}
}
}
public void start() {
InterceptorConfiguration config = getConfiguration().getInterceptorConfiguration();
int port = config.getListenPort();
portField.setText("" + port);
portTabItem.setText(TCPMonBundle.getMessage("port01", "Port") + " " + port);
tPortField.setText("" + config.getTargetPort());
interceptor = new Interceptor(config, this);
stopButton.setText(TCPMonBundle.getMessage("stop00", "Stop"));
portField.setEditable(false);
hostField.setEditable(false);
tPortField.setEditable(false);
isProxyBox.setEnabled(false);
}
public void stop() {
try {
interceptor.halt();
stopButton.setText(TCPMonBundle.getMessage("start00", "Start"));
portField.setEditable(true);
hostField.setEditable(true);
tPortField.setEditable(true);
isProxyBox.setEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void remove() {
int index;
RequestResponse requestResponse;
int[] selectionIndices = tableEnhancer.getSelectionIndicesWithoutZero();
for (int i = 0; i < selectionIndices.length; i++) {
index = selectionIndices[i];
requestResponse = (RequestResponse) requestResponses.get(index - 1 - i);
// if (con.isActive()) {
// MessageBox mb = new MessageBox(MainView.display.getActiveShell(), SWT.ICON_INFORMATION | SWT.OK);
// mb.setMessage(TCPMonBundle.getMessage("inform00", "Connection can be removed only when its status indicates Done"));
// mb.setText("Connection Active");
// mb.open();
// continue;
// }
// con.halt();
requestResponse.inputText.dispose();
requestResponse.outputText.dispose();
requestResponses.remove(requestResponse);
tableEnhancer.remove(index - i);
tableEnhancer.setSelectionInterval(0, 0);
}
}
public void removeAll() {
tableEnhancer.selectAll();
remove();
}
public void close() {
MessageBox mb = new MessageBox(MainView.display.getActiveShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
mb.setMessage(TCPMonBundle.getMessage("quit00", "Do you want to remove monitoring") + " " + portTabItem.getText());
mb.setText("Remove Monitor");
int response = mb.open();
if (response == SWT.YES) {
if (stopButton.getText().equals(TCPMonBundle.getMessage("stop00", "Stop"))) {
stop();
}
portTabItem.dispose();
}
}
public void save() {
FileDialog fd = new FileDialog(MainView.display.getActiveShell(), SWT.SAVE);
fd.setText("Save");
fd.setFilterPath(".");
String path = fd.open();
if (path != null) {
try {
File file = new File(path);
FileOutputStream out = new FileOutputStream(file);
int rc = tableEnhancer.getLeadSelectionIndex();
int n = 0;
for (Iterator i = requestResponses.iterator(); i.hasNext();
n++) {
RequestResponse requestResponse = (RequestResponse) i.next();
if (tableEnhancer.isSelectedIndex(n + 1)
|| (!(i.hasNext())
&& (tableEnhancer.getLeadSelectionIndex() == 0))) {
rc = Integer.parseInt(portField.getText());
out.write("\n==============\n".getBytes());
out.write(((TCPMonBundle.getMessage("listenPort01",
"Listen Port:")
+ " " + rc + "\n")).getBytes());
out.write((TCPMonBundle.getMessage("targetHost01",
"Target Host:")
+ " " + hostField.getText()
+ "\n").getBytes());
rc = Integer.parseInt(tPortField.getText());
out.write(((TCPMonBundle.getMessage("targetPort01",
"Target Port:")
+ " " + rc + "\n")).getBytes());
out.write((("==== "
+ TCPMonBundle.getMessage("request01", "Request")
+ " ====\n")).getBytes());
out.write(requestResponse.getRequestAsString().getBytes());
out.write((("==== "
+ TCPMonBundle.getMessage("response00", "Response")
+ " ====\n")).getBytes());
out.write(requestResponse.getResponseAsString().getBytes());
out.write("\n==============\n".getBytes());
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void resend() {
int rc;
RequestResponse requestResponse;
rc = tableEnhancer.getMaxSelectionIndex();
if (rc == 0) {
requestResponse = (RequestResponse) requestResponses.lastElement();
} else {
requestResponse = (RequestResponse) requestResponses.get(rc - 1);
}
if (rc > 0) {
tableEnhancer.clearSelection();
tableEnhancer.setSelectionInterval(0, 0);
}
resend(requestResponse);
}
public Object setLeft(int type, String text) {
Control[] children = leftPanel.getChildren();
removeChildren(children);
switch (type) {
case 0:
Label label = new Label(leftPanel, SWT.NONE);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.grabExcessHorizontalSpace = true;
gd.horizontalSpan = 8;
gd.exclude = false;
label.setLayoutData(gd);
label.setText(text);
leftPanel.layout();
textComposite.layout();
return label;
case 1:
Text leftText = new Text(leftPanel, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
GridData gd1 = new GridData(GridData.FILL_BOTH);
gd1.grabExcessHorizontalSpace = true;
gd1.horizontalSpan = 8;
gd1.exclude = false;
leftText.setLayoutData(gd1);
leftText.setText(text);
leftPanel.layout();
textComposite.layout();
return leftText;
}
return null;
}
public void layout() {
leftPanel.layout();
rightPanel.layout();
}
public Object setRight(int type, String text) {
Control[] children = rightPanel.getChildren();
removeChildren(children);
switch (type) {
case 0:
Label label = new Label(rightPanel, SWT.NONE);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.grabExcessHorizontalSpace = true;
gd.horizontalSpan = 8;
gd.exclude = false;
label.setLayoutData(gd);
label.setText(text);
rightPanel.layout();
textComposite.layout();
return label;
case 1:
Text rightText = new Text(rightPanel, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
GridData gd1 = new GridData(GridData.FILL_BOTH);
gd1.grabExcessHorizontalSpace = true;
gd1.horizontalSpan = 8;
rightText.setLayoutData(gd1);
rightText.setText(text);
rightPanel.layout();
textComposite.layout();
return rightText;
}
return null;
}
private void removeChildren(Control[] children) {
for (int i = 0; i < children.length; i++) {
((GridData) children[i].getLayoutData()).exclude = true;
children[i].setVisible(false);
children[i].getShell().layout(true);
}
}
public Configuration getConfiguration() {
final InterceptorConfigurationBuilder configBuilder = new InterceptorConfigurationBuilder(baseConfiguration);
final Configuration config = new Configuration();
MainView.display.syncExec(new Runnable() {
public void run() {
configBuilder.setListenPort(Integer.parseInt(portField.getText()));
configBuilder.setTargetHost(hostField.getText());
configBuilder.setTargetPort(Integer.parseInt(tPortField.getText()));
configBuilder.setProxy(isProxyBox.getSelection());
config.setXmlFormat(xmlFormatBox.getSelection());
}
});
config.setInterceptorConfiguration(configBuilder.build());
return config;
}
public void onServerSocketStart() {
MainView.display.syncExec(new Runnable() {
public void run() {
setLeft(MainView.SWT_LABEL, TCPMonBundle.getMessage("wait00", " Waiting for Connection..."));
}
});
}
public void onServerSocketError(final Throwable ex) {
MainView.display.syncExec(new Runnable() {
public void run() {
setLeft(MainView.SWT_LABEL, ex.toString());
setRight(MainView.SWT_LABEL, "");
stop();
}
});
}
public RequestResponseListener createRequestResponseListener(String fromHost) {
return new RequestResponse(this, fromHost);
}
}
|
9232ed7167cc21d31829613d081d1b6e50e701b8 | 8,224 | java | Java | sources/android-28/android/telephony/CellInfo.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | null | null | null | sources/android-28/android/telephony/CellInfo.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | null | null | null | sources/android-28/android/telephony/CellInfo.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | null | null | null | 30.124542 | 96 | 0.618799 | 996,407 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.telephony;
import android.annotation.IntDef;
import android.os.Parcel;
import android.os.Parcelable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Immutable cell information from a point in time.
*/
public abstract class CellInfo implements Parcelable {
// Type fields for parceling
/** @hide */
protected static final int TYPE_GSM = 1;
/** @hide */
protected static final int TYPE_CDMA = 2;
/** @hide */
protected static final int TYPE_LTE = 3;
/** @hide */
protected static final int TYPE_WCDMA = 4;
// Type to distinguish where time stamp gets recorded.
/** @hide */
public static final int TIMESTAMP_TYPE_UNKNOWN = 0;
/** @hide */
public static final int TIMESTAMP_TYPE_ANTENNA = 1;
/** @hide */
public static final int TIMESTAMP_TYPE_MODEM = 2;
/** @hide */
public static final int TIMESTAMP_TYPE_OEM_RIL = 3;
/** @hide */
public static final int TIMESTAMP_TYPE_JAVA_RIL = 4;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@IntDef({
CONNECTION_NONE,
CONNECTION_PRIMARY_SERVING,
CONNECTION_SECONDARY_SERVING,
CONNECTION_UNKNOWN
})
public @interface CellConnectionStatus {}
/**
* Cell is not a serving cell.
*
* <p>The cell has been measured but is neither a camped nor serving cell (3GPP 36.304).
*/
public static final int CONNECTION_NONE = 0;
/** UE is connected to cell for signalling and possibly data (3GPP 36.331, 25.331). */
public static final int CONNECTION_PRIMARY_SERVING = 1;
/** UE is connected to cell for data (3GPP 36.331, 25.331). */
public static final int CONNECTION_SECONDARY_SERVING = 2;
/** Connection status is unknown. */
public static final int CONNECTION_UNKNOWN = Integer.MAX_VALUE;
private int mCellConnectionStatus = CONNECTION_NONE;
// True if device is mRegistered to the mobile network
private boolean mRegistered;
// Observation time stamped as type in nanoseconds since boot
private long mTimeStamp;
// Where time stamp gets recorded.
// Value of TIMESTAMP_TYPE_XXXX
private int mTimeStampType;
/** @hide */
protected CellInfo() {
this.mRegistered = false;
this.mTimeStampType = TIMESTAMP_TYPE_UNKNOWN;
this.mTimeStamp = Long.MAX_VALUE;
}
/** @hide */
protected CellInfo(CellInfo ci) {
this.mRegistered = ci.mRegistered;
this.mTimeStampType = ci.mTimeStampType;
this.mTimeStamp = ci.mTimeStamp;
this.mCellConnectionStatus = ci.mCellConnectionStatus;
}
/** True if this cell is registered to the mobile network */
public boolean isRegistered() {
return mRegistered;
}
/** @hide */
public void setRegistered(boolean registered) {
mRegistered = registered;
}
/** Approximate time of this cell information in nanos since boot */
public long getTimeStamp() {
return mTimeStamp;
}
/** @hide */
public void setTimeStamp(long timeStamp) {
mTimeStamp = timeStamp;
}
/**
* Gets the connection status of this cell.
*
* @see #CONNECTION_NONE
* @see #CONNECTION_PRIMARY_SERVING
* @see #CONNECTION_SECONDARY_SERVING
* @see #CONNECTION_UNKNOWN
*
* @return The connection status of the cell.
*/
@CellConnectionStatus
public int getCellConnectionStatus() {
return mCellConnectionStatus;
}
/** @hide */
public void setCellConnectionStatus(@CellConnectionStatus int cellConnectionStatus) {
mCellConnectionStatus = cellConnectionStatus;
}
/**
* Where time stamp gets recorded.
* @return one of TIMESTAMP_TYPE_XXXX
*
* @hide
*/
public int getTimeStampType() {
return mTimeStampType;
}
/** @hide */
public void setTimeStampType(int timeStampType) {
if (timeStampType < TIMESTAMP_TYPE_UNKNOWN || timeStampType > TIMESTAMP_TYPE_JAVA_RIL) {
mTimeStampType = TIMESTAMP_TYPE_UNKNOWN;
} else {
mTimeStampType = timeStampType;
}
}
@Override
public int hashCode() {
int primeNum = 31;
return ((mRegistered ? 0 : 1) * primeNum) + ((int)(mTimeStamp / 1000) * primeNum)
+ (mTimeStampType * primeNum) + (mCellConnectionStatus * primeNum);
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (this == other) {
return true;
}
try {
CellInfo o = (CellInfo) other;
return mRegistered == o.mRegistered
&& mTimeStamp == o.mTimeStamp
&& mTimeStampType == o.mTimeStampType
&& mCellConnectionStatus == o.mCellConnectionStatus;
} catch (ClassCastException e) {
return false;
}
}
private static String timeStampTypeToString(int type) {
switch (type) {
case 1:
return "antenna";
case 2:
return "modem";
case 3:
return "oem_ril";
case 4:
return "java_ril";
default:
return "unknown";
}
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
String timeStampType;
sb.append("mRegistered=").append(mRegistered ? "YES" : "NO");
timeStampType = timeStampTypeToString(mTimeStampType);
sb.append(" mTimeStampType=").append(timeStampType);
sb.append(" mTimeStamp=").append(mTimeStamp).append("ns");
sb.append(" mCellConnectionStatus=").append(mCellConnectionStatus);
return sb.toString();
}
/**
* Implement the Parcelable interface
*/
@Override
public int describeContents() {
return 0;
}
/** Implement the Parcelable interface */
@Override
public abstract void writeToParcel(Parcel dest, int flags);
/**
* Used by child classes for parceling.
*
* @hide
*/
protected void writeToParcel(Parcel dest, int flags, int type) {
dest.writeInt(type);
dest.writeInt(mRegistered ? 1 : 0);
dest.writeInt(mTimeStampType);
dest.writeLong(mTimeStamp);
dest.writeInt(mCellConnectionStatus);
}
/**
* Used by child classes for parceling
*
* @hide
*/
protected CellInfo(Parcel in) {
mRegistered = (in.readInt() == 1) ? true : false;
mTimeStampType = in.readInt();
mTimeStamp = in.readLong();
mCellConnectionStatus = in.readInt();
}
/** Implement the Parcelable interface */
public static final Creator<CellInfo> CREATOR = new Creator<CellInfo>() {
@Override
public CellInfo createFromParcel(Parcel in) {
int type = in.readInt();
switch (type) {
case TYPE_GSM: return CellInfoGsm.createFromParcelBody(in);
case TYPE_CDMA: return CellInfoCdma.createFromParcelBody(in);
case TYPE_LTE: return CellInfoLte.createFromParcelBody(in);
case TYPE_WCDMA: return CellInfoWcdma.createFromParcelBody(in);
default: throw new RuntimeException("Bad CellInfo Parcel");
}
}
@Override
public CellInfo[] newArray(int size) {
return new CellInfo[size];
}
};
}
|
9232ee8e7f59e42f707e022896a3da8d1cc6af0b | 5,284 | java | Java | squirrel-foundation/src/test/java/org/squirrelframework/foundation/fsm/atm/ATMStateMachineTest.java | zproo/squirrel | aa7526dae975b3da70c18268d1ec30ce07b48ed1 | [
"Apache-2.0"
] | 1,711 | 2015-01-11T00:22:02.000Z | 2022-03-28T07:32:37.000Z | squirrel-foundation/src/test/java/org/squirrelframework/foundation/fsm/atm/ATMStateMachineTest.java | zproo/squirrel | aa7526dae975b3da70c18268d1ec30ce07b48ed1 | [
"Apache-2.0"
] | 86 | 2015-01-07T08:45:42.000Z | 2022-03-29T04:16:32.000Z | squirrel-foundation/src/test/java/org/squirrelframework/foundation/fsm/atm/ATMStateMachineTest.java | zproo/squirrel | aa7526dae975b3da70c18268d1ec30ce07b48ed1 | [
"Apache-2.0"
] | 483 | 2015-01-11T00:22:02.000Z | 2022-03-25T08:35:42.000Z | 51.803922 | 151 | 0.746593 | 996,408 | package org.squirrelframework.foundation.fsm.atm;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.squirrelframework.foundation.component.SquirrelPostProcessorProvider;
import org.squirrelframework.foundation.component.SquirrelProvider;
import org.squirrelframework.foundation.fsm.ConverterProvider;
import org.squirrelframework.foundation.fsm.SCXMLVisitor;
import org.squirrelframework.foundation.fsm.StateMachineBuilder;
import org.squirrelframework.foundation.fsm.StateMachineBuilderFactory;
import org.squirrelframework.foundation.fsm.StateMachineStatus;
import org.squirrelframework.foundation.fsm.UntypedStateMachineBuilder;
import org.squirrelframework.foundation.fsm.UntypedStateMachineImporter;
import org.squirrelframework.foundation.fsm.atm.ATMStateMachine.ATMState;
public class ATMStateMachineTest {
@AfterClass
public static void afterTest() {
ConverterProvider.INSTANCE.clearRegistry();
SquirrelPostProcessorProvider.getInstance().clearRegistry();
}
private ATMStateMachine stateMachine;
@Before
public void setup() {
StateMachineBuilder<ATMStateMachine, ATMState, String, Void> builder = StateMachineBuilderFactory.create(
ATMStateMachine.class, ATMState.class, String.class, Void.class);
builder.externalTransition().from(ATMState.Idle).to(ATMState.Loading).on("Connected");
builder.externalTransition().from(ATMState.Loading).to(ATMState.Disconnected).on("ConnectionClosed");
builder.externalTransition().from(ATMState.Loading).to(ATMState.InService).on("LoadSuccess");
builder.externalTransition().from(ATMState.Loading).to(ATMState.OutOfService).on("LoadFail");
builder.externalTransition().from(ATMState.OutOfService).to(ATMState.Disconnected).on("ConnectionLost");
builder.externalTransition().from(ATMState.OutOfService).to(ATMState.InService).on("Startup");
builder.externalTransition().from(ATMState.InService).to(ATMState.OutOfService).on("Shutdown");
builder.externalTransition().from(ATMState.InService).to(ATMState.Disconnected).on("ConnectionLost");
builder.externalTransition().from(ATMState.Disconnected).to(ATMState.InService).on("ConnectionRestored");
stateMachine = builder.newStateMachine(ATMState.Idle);
}
@After
public void teardown() {
if(stateMachine!=null && stateMachine.getStatus()!=StateMachineStatus.TERMINATED) {
stateMachine.terminate(null);
}
}
@Test
public void testIdelToInService() {
stateMachine.start();
assertThat(stateMachine.consumeLog(), is(equalTo("entryIdle")));
assertThat(stateMachine.getCurrentState(), is(equalTo(ATMState.Idle)));
stateMachine.fire("Connected");
assertThat(stateMachine.consumeLog(), is(equalTo("exitIdle.transitFromIdleToLoadingOnConnected.entryLoading")));
assertThat(stateMachine.getCurrentState(), is(equalTo(ATMState.Loading)));
stateMachine.fire("LoadSuccess");
assertThat(stateMachine.consumeLog(), is(equalTo("exitLoading.transitFromLoadingToInServiceOnLoadSuccess.entryInService")));
assertThat(stateMachine.getCurrentState(), is(equalTo(ATMState.InService)));
stateMachine.fire("Shutdown");
assertThat(stateMachine.consumeLog(), is(equalTo("exitInService.transitFromInServiceToOutOfServiceOnShutdown.entryOutOfService")));
assertThat(stateMachine.getCurrentState(), is(equalTo(ATMState.OutOfService)));
stateMachine.fire("ConnectionLost");
assertThat(stateMachine.consumeLog(), is(equalTo("exitOutOfService.transitFromOutOfServiceToDisconnectedOnConnectionLost.entryDisconnected")));
assertThat(stateMachine.getCurrentState(), is(equalTo(ATMState.Disconnected)));
stateMachine.fire("ConnectionRestored");
assertThat(stateMachine.consumeLog(), is(equalTo("exitDisconnected.transitFromDisconnectedToInServiceOnConnectionRestored.entryInService")));
assertThat(stateMachine.getCurrentState(), is(equalTo(ATMState.InService)));
}
@Test
public void exportAndImportATMStateMachine() {
SCXMLVisitor visitor = SquirrelProvider.getInstance().newInstance(SCXMLVisitor.class);
stateMachine.accept(visitor);
// visitor.convertSCXMLFile("ATMStateMachine", true);
String xmlDef = visitor.getScxml(false);
UntypedStateMachineBuilder builder = new UntypedStateMachineImporter().importDefinition(xmlDef);
ATMStateMachine stateMachine = builder.newAnyStateMachine(ATMState.Idle);
stateMachine.start();
assertThat(stateMachine.consumeLog(), is(equalTo("entryIdle")));
assertThat(stateMachine.getCurrentState(), is(equalTo(ATMState.Idle)));
stateMachine.fire("Connected");
assertThat(stateMachine.consumeLog(), is(equalTo("exitIdle.transitFromIdleToLoadingOnConnected.entryLoading")));
assertThat(stateMachine.getCurrentState(), is(equalTo(ATMState.Loading)));
}
}
|
9232eea908df295ffa036ea7def650b7dec5fc20 | 945 | java | Java | xdagwallet/app/src/main/java/com/xdag/wallet/ui/adapter/TransactionsRecordTimeProvider.java | wangxuguo/xdag-android | 3784377f6152905f65e0dcd07aea6bb3bf74c028 | [
"MIT"
] | 1 | 2018-07-23T22:56:46.000Z | 2018-07-23T22:56:46.000Z | xdagwallet/app/src/main/java/com/xdag/wallet/ui/adapter/TransactionsRecordTimeProvider.java | wangxuguo/xdag-android | 3784377f6152905f65e0dcd07aea6bb3bf74c028 | [
"MIT"
] | 3 | 2018-05-29T15:57:51.000Z | 2018-06-28T18:53:22.000Z | xdagwallet/app/src/main/java/com/xdag/wallet/ui/adapter/TransactionsRecordTimeProvider.java | wangxuguo/xdag-android | 3784377f6152905f65e0dcd07aea6bb3bf74c028 | [
"MIT"
] | null | null | null | 27.794118 | 80 | 0.726984 | 996,409 | package com.xdag.wallet.ui.adapter;
import com.chad.library.adapter.base.*;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.xdag.wallet.R;
import com.xdag.wallet.model.XdagTransactionModel;
import static com.xdag.wallet.ui.adapter.TransactionsRecordBRVAdapter.TYPE_TIME;
/**
* Created by wangxuguo on 2018/7/10.
*/
public class TransactionsRecordTimeProvider extends BaseItemProvider {
@Override
public int viewType() {
return TYPE_TIME;
}
@Override
public int layout() {
return R.layout.rv_item_transaction_time;
}
@Override
public void convert(BaseViewHolder helper, Object data, int position) {
if(data instanceof XdagTransactionModel){
XdagTransactionModel model = (XdagTransactionModel) data;
helper.setText(R.id.tv_transaction_time,model.getUTCTime());
}
}
}
|
9232ef1c3fd65083f5385db6f0d3c089f8223e2c | 6,741 | java | Java | net.powermatcher.api/test/net/powermatcher/api/monitoring/test/AgentEventTest.java | leimar-ros/PowerMatcher_v2 | 493521e1146ae59da65af24c1470d8eed59c60ff | [
"Apache-2.0"
] | 29 | 2015-02-09T10:14:13.000Z | 2022-01-14T01:51:36.000Z | net.powermatcher.api/test/net/powermatcher/api/monitoring/test/AgentEventTest.java | leimar-ros/PowerMatcher_v2 | 493521e1146ae59da65af24c1470d8eed59c60ff | [
"Apache-2.0"
] | 62 | 2015-01-05T13:23:48.000Z | 2022-01-17T02:43:40.000Z | net.powermatcher.api/test/net/powermatcher/api/monitoring/test/AgentEventTest.java | leimar-ros/PowerMatcher_v2 | 493521e1146ae59da65af24c1470d8eed59c60ff | [
"Apache-2.0"
] | 31 | 2015-03-01T11:14:26.000Z | 2020-10-16T14:40:33.000Z | 45.547297 | 117 | 0.5336 | 996,410 | package net.powermatcher.api.monitoring.test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import net.powermatcher.api.data.ArrayBidBuilder;
import net.powermatcher.api.data.Bid;
import net.powermatcher.api.data.MarketBasis;
import net.powermatcher.api.data.Price;
import net.powermatcher.api.messages.BidUpdate;
import net.powermatcher.api.messages.PriceUpdate;
import net.powermatcher.api.monitoring.events.AgentEvent;
import net.powermatcher.api.monitoring.events.IncomingBidUpdateEvent;
import net.powermatcher.api.monitoring.events.IncomingPriceUpdateEvent;
import net.powermatcher.api.monitoring.events.OutgoingBidUpdateEvent;
import net.powermatcher.api.monitoring.events.OutgoingPriceUpdateEvent;
/**
* JUnit tests for the {@link AgentEvent} class.
*
* @author FAN
* @version 2.1
*/
public class AgentEventTest {
private String clusterId;
private String agentId;
private String sessionId;
private Date timestamp;
private String fromAgent;
private MarketBasis marketBasis;
private Bid bid;
private BidUpdate bidUpdate;
private PriceUpdate priceUpdate;
@Before
public void setUp() {
clusterId = "testCluster";
agentId = "testAgent";
sessionId = "testSession";
timestamp = new Date();
fromAgent = "message from agent";
marketBasis = new MarketBasis("water", "EURO", 10, 0, 10);
bid = new ArrayBidBuilder(marketBasis).demand(0).build();
bidUpdate = new BidUpdate(bid, 9);
priceUpdate = new PriceUpdate(new Price(marketBasis, 10.0), 0);
}
@Test
public void testIncomingBidEvent() {
IncomingBidUpdateEvent ibe = new IncomingBidUpdateEvent(clusterId,
agentId,
sessionId,
timestamp,
fromAgent,
bidUpdate);
assertThat(ibe.getClusterId(), is(equalTo(clusterId)));
assertThat(ibe.getAgentId(), is(equalTo(agentId)));
assertThat(ibe.getSessionId(), is(equalTo(sessionId)));
assertThat(ibe.getTimestamp(), is(equalTo(timestamp)));
assertThat(ibe.getFromAgentId(), is(equalTo(fromAgent)));
assertThat(ibe.getBidUpdate(), is(equalTo(bidUpdate)));
}
@Test
public void testIncomingBidEventToString() {
IncomingBidUpdateEvent ibe = new IncomingBidUpdateEvent(clusterId,
agentId,
sessionId,
timestamp,
fromAgent,
bidUpdate);
String ibetoString = ibe.toString();
assertThat(ibetoString, is(notNullValue()));
}
@Test
public void testOutgoingBidEvent() {
OutgoingBidUpdateEvent obe = new OutgoingBidUpdateEvent(clusterId, agentId, sessionId, timestamp, bidUpdate);
assertThat(obe.getClusterId(), is(equalTo(clusterId)));
assertThat(obe.getAgentId(), is(equalTo(agentId)));
assertThat(obe.getSessionId(), is(equalTo(sessionId)));
assertThat(obe.getTimestamp(), is(equalTo(timestamp)));
assertThat(obe.getBidUpdate(), is(equalTo(bidUpdate)));
}
@Test
public void testOutgoingBidEventToString() {
OutgoingBidUpdateEvent obe = new OutgoingBidUpdateEvent(clusterId, agentId, sessionId, timestamp, bidUpdate);
String obetoString = obe.toString();
assertThat(obetoString, is(notNullValue()));
}
public void testIncomingPriceUpdateEvent() {
IncomingPriceUpdateEvent ice = new IncomingPriceUpdateEvent(clusterId,
agentId,
sessionId,
timestamp,
priceUpdate);
assertThat(ice.getClusterId(), is(equalTo(clusterId)));
assertThat(ice.getAgentId(), is(equalTo(agentId)));
assertThat(ice.getSessionId(), is(equalTo(sessionId)));
assertThat(ice.getTimestamp(), is(equalTo(timestamp)));
assertThat(ice.getPriceUpdate(), is(equalTo(priceUpdate)));
}
@Test
public void testIncomingPriceUpdateEventToString() {
IncomingPriceUpdateEvent ice = new IncomingPriceUpdateEvent(clusterId,
agentId,
sessionId,
timestamp,
priceUpdate);
String icetoString = ice.toString();
assertThat(icetoString, is(notNullValue()));
}
public void testOutgoingPriceUpdateEvent() {
OutgoingPriceUpdateEvent oce = new OutgoingPriceUpdateEvent(clusterId,
agentId,
sessionId,
timestamp,
priceUpdate);
assertThat(oce.getClusterId(), is(equalTo(clusterId)));
assertThat(oce.getAgentId(), is(equalTo(agentId)));
assertThat(oce.getSessionId(), is(equalTo(sessionId)));
assertThat(oce.getTimestamp(), is(equalTo(timestamp)));
assertThat(oce.getPriceUpdate(), is(equalTo(priceUpdate)));
}
@Test
public void testOutgoingPriceUpdateEventToString() {
OutgoingPriceUpdateEvent oce = new OutgoingPriceUpdateEvent(clusterId,
agentId,
sessionId,
timestamp,
priceUpdate);
String icetoString = oce.toString();
assertThat(icetoString, is(notNullValue()));
}
}
|
9232f0cabd40c5f1b9d7d9b83f07e27416d92dce | 8,137 | java | Java | core/src/test/java/org/apache/accumulo/core/metadata/schema/TabletMetadataTest.java | hkeebler/accumulo | 903119dac631b36009b389193d9d0bc04ed7fb37 | [
"Apache-2.0"
] | 2 | 2021-06-02T14:31:16.000Z | 2021-07-23T12:54:41.000Z | core/src/test/java/org/apache/accumulo/core/metadata/schema/TabletMetadataTest.java | hkeebler/accumulo | 903119dac631b36009b389193d9d0bc04ed7fb37 | [
"Apache-2.0"
] | 1 | 2022-01-13T15:20:39.000Z | 2022-01-13T15:20:39.000Z | core/src/test/java/org/apache/accumulo/core/metadata/schema/TabletMetadataTest.java | hkeebler/accumulo | 903119dac631b36009b389193d9d0bc04ed7fb37 | [
"Apache-2.0"
] | 1 | 2021-06-14T14:49:08.000Z | 2021-06-14T14:49:08.000Z | 48.434524 | 121 | 0.746098 | 996,411 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.metadata.schema;
import static java.util.stream.Collectors.toSet;
import static org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.ServerColumnFamily.COMPACT_COLUMN;
import static org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN;
import static org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.ServerColumnFamily.FLUSH_COLUMN;
import static org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.ServerColumnFamily.TIME_COLUMN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.EnumSet;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.dataImpl.KeyExtent;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.BulkFileColumnFamily;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.ClonedColumnFamily;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.CurrentLocationColumnFamily;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.DataFileColumnFamily;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.FutureLocationColumnFamily;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.LastLocationColumnFamily;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.ScanFileColumnFamily;
import org.apache.accumulo.core.metadata.schema.TabletMetadata.FetchedColumns;
import org.apache.accumulo.core.metadata.schema.TabletMetadata.LocationType;
import org.apache.accumulo.core.tabletserver.log.LogEntry;
import org.apache.accumulo.core.util.HostAndPort;
import org.apache.hadoop.io.Text;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
public class TabletMetadataTest {
@Test
public void testAllColumns() {
KeyExtent extent = new KeyExtent(TableId.of("5"), new Text("df"), new Text("da"));
Mutation mutation = extent.getPrevRowUpdateMutation();
COMPACT_COLUMN.put(mutation, new Value("5"));
DIRECTORY_COLUMN.put(mutation, new Value("/a/t/6/a/"));
FLUSH_COLUMN.put(mutation, new Value("6"));
TIME_COLUMN.put(mutation, new Value("M123456789"));
mutation.at().family(BulkFileColumnFamily.NAME).qualifier("bf1").put("");
mutation.at().family(BulkFileColumnFamily.NAME).qualifier("bf2").put("");
mutation.at().family(ClonedColumnFamily.NAME).qualifier("").put("OK");
DataFileValue dfv1 = new DataFileValue(555, 23);
mutation.at().family(DataFileColumnFamily.NAME).qualifier("df1").put(dfv1.encode());
DataFileValue dfv2 = new DataFileValue(234, 13);
mutation.at().family(DataFileColumnFamily.NAME).qualifier("df2").put(dfv2.encode());
mutation.at().family(CurrentLocationColumnFamily.NAME).qualifier("s001").put("server1:8555");
mutation.at().family(LastLocationColumnFamily.NAME).qualifier("s000").put("server2:8555");
LogEntry le1 = new LogEntry(extent, 55, "server1", "lf1");
mutation.at().family(le1.getColumnFamily()).qualifier(le1.getColumnQualifier())
.timestamp(le1.timestamp).put(le1.getValue());
LogEntry le2 = new LogEntry(extent, 57, "server1", "lf2");
mutation.at().family(le2.getColumnFamily()).qualifier(le2.getColumnQualifier())
.timestamp(le2.timestamp).put(le2.getValue());
mutation.at().family(ScanFileColumnFamily.NAME).qualifier("sf1").put("");
mutation.at().family(ScanFileColumnFamily.NAME).qualifier("sf2").put("");
SortedMap<Key,Value> rowMap = toRowMap(mutation);
TabletMetadata tm = TabletMetadata.convertRow(rowMap.entrySet().iterator(),
EnumSet.allOf(FetchedColumns.class), true);
assertEquals("OK", tm.getCloned());
assertEquals(5L, tm.getCompactId().getAsLong());
assertEquals("/a/t/6/a/", tm.getDir());
assertEquals(extent.getEndRow(), tm.getEndRow());
assertEquals(extent, tm.getExtent());
assertEquals(ImmutableSet.of("df1", "df2"), ImmutableSet.copyOf(tm.getFiles()));
assertEquals(ImmutableMap.of("df1", dfv1, "df2", dfv2), tm.getFilesMap());
assertEquals(6L, tm.getFlushId().getAsLong());
assertEquals(rowMap, tm.getKeyValues());
assertEquals(ImmutableSet.of("bf1", "bf2"), ImmutableSet.copyOf(tm.getLoaded()));
assertEquals(HostAndPort.fromParts("server1", 8555), tm.getLocation().getHostAndPort());
assertEquals("s001", tm.getLocation().getSession());
assertEquals(LocationType.CURRENT, tm.getLocation().getType());
assertTrue(tm.hasCurrent());
assertEquals(HostAndPort.fromParts("server2", 8555), tm.getLast().getHostAndPort());
assertEquals("s000", tm.getLast().getSession());
assertEquals(LocationType.LAST, tm.getLast().getType());
assertEquals(
ImmutableSet.of(le1.getName() + " " + le1.timestamp, le2.getName() + " " + le2.timestamp),
tm.getLogs().stream().map(le -> le.getName() + " " + le.timestamp).collect(toSet()));
assertEquals(extent.getPrevEndRow(), tm.getPrevEndRow());
assertEquals(extent.getTableId(), tm.getTableId());
assertTrue(tm.sawPrevEndRow());
assertEquals("M123456789", tm.getTime());
assertEquals(ImmutableSet.of("sf1", "sf2"), ImmutableSet.copyOf(tm.getScans()));
}
@Test
public void testFuture() {
KeyExtent extent = new KeyExtent(TableId.of("5"), new Text("df"), new Text("da"));
Mutation mutation = extent.getPrevRowUpdateMutation();
mutation.at().family(FutureLocationColumnFamily.NAME).qualifier("s001").put("server1:8555");
SortedMap<Key,Value> rowMap = toRowMap(mutation);
TabletMetadata tm = TabletMetadata.convertRow(rowMap.entrySet().iterator(),
EnumSet.allOf(FetchedColumns.class), false);
assertEquals(extent, tm.getExtent());
assertEquals(HostAndPort.fromParts("server1", 8555), tm.getLocation().getHostAndPort());
assertEquals("s001", tm.getLocation().getSession());
assertEquals(LocationType.FUTURE, tm.getLocation().getType());
assertFalse(tm.hasCurrent());
}
@Test(expected = IllegalStateException.class)
public void testFutureAndCurrent() {
KeyExtent extent = new KeyExtent(TableId.of("5"), new Text("df"), new Text("da"));
Mutation mutation = extent.getPrevRowUpdateMutation();
mutation.at().family(CurrentLocationColumnFamily.NAME).qualifier("s001").put("server1:8555");
mutation.at().family(FutureLocationColumnFamily.NAME).qualifier("s001").put("server1:8555");
SortedMap<Key,Value> rowMap = toRowMap(mutation);
TabletMetadata.convertRow(rowMap.entrySet().iterator(), EnumSet.allOf(FetchedColumns.class),
false);
}
private SortedMap<Key,Value> toRowMap(Mutation mutation) {
SortedMap<Key,Value> rowMap = new TreeMap<>();
mutation.getUpdates().forEach(cu -> {
Key k = new Key(mutation.getRow(), cu.getColumnFamily(), cu.getColumnQualifier(),
cu.getTimestamp());
Value v = new Value(cu.getValue());
rowMap.put(k, v);
});
return rowMap;
}
}
|
9232f1069b0772e0914ecd02a16b045ddf3abe2f | 11,124 | java | Java | app/src/main/java/com/ybj/myshopping/bean/ResultBean.java | AndGirl/MyShopping | 0c01fe78e192be9301f3217372f3a0e86a7358ca | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/ybj/myshopping/bean/ResultBean.java | AndGirl/MyShopping | 0c01fe78e192be9301f3217372f3a0e86a7358ca | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/ybj/myshopping/bean/ResultBean.java | AndGirl/MyShopping | 0c01fe78e192be9301f3217372f3a0e86a7358ca | [
"Apache-2.0"
] | null | null | null | 24.72 | 75 | 0.493707 | 996,412 | package com.ybj.myshopping.bean;
import java.io.Serializable;
import java.util.List;
/**
* Created by 杨阳洋 on 2017/2/10.
*/
public class ResultBean implements Serializable {
@Override
public String toString() {
return "ResultBean{" +
"seckill_info=" + seckill_info +
", banner_info=" + banner_info +
", channel_info=" + channel_info +
", act_info=" + act_info +
", hot_info=" + hot_info +
", recommend_info=" + recommend_info +
'}';
}
private SeckillInfoBean seckill_info;
private List<BannerInfoBean> banner_info;
private List<ChannelInfoBean> channel_info;
private List<ActInfoBean> act_info;
private List<HotInfoBean> hot_info;
private List<RecommendInfoBean> recommend_info;
public SeckillInfoBean getSeckill_info() {
return seckill_info;
}
public void setSeckill_info(SeckillInfoBean seckill_info) {
this.seckill_info = seckill_info;
}
public List<BannerInfoBean> getBanner_info() {
return banner_info;
}
public void setBanner_info(List<BannerInfoBean> banner_info) {
this.banner_info = banner_info;
}
public List<ChannelInfoBean> getChannel_info() {
return channel_info;
}
public void setChannel_info(List<ChannelInfoBean> channel_info) {
this.channel_info = channel_info;
}
public List<ActInfoBean> getAct_info() {
return act_info;
}
public void setAct_info(List<ActInfoBean> act_info) {
this.act_info = act_info;
}
public List<HotInfoBean> getHot_info() {
return hot_info;
}
public void setHot_info(List<HotInfoBean> hot_info) {
this.hot_info = hot_info;
}
public List<RecommendInfoBean> getRecommend_info() {
return recommend_info;
}
public void setRecommend_info(List<RecommendInfoBean> recommend_info) {
this.recommend_info = recommend_info;
}
public static class SeckillInfoBean {
private String start_time;
private String end_time;
private List<ListBean> list;
public String getStart_time() {
return start_time;
}
public void setStart_time(String start_time) {
this.start_time = start_time;
}
public String getEnd_time() {
return end_time;
}
public void setEnd_time(String end_time) {
this.end_time = end_time;
}
public List<ListBean> getList() {
return list;
}
public void setList(List<ListBean> list) {
this.list = list;
}
@Override
public String toString() {
return "SeckillInfoBean{" +
"start_time='" + start_time + '\'' +
", end_time='" + end_time + '\'' +
", list=" + list +
'}';
}
public static class ListBean {
private String product_id;
private String name;
private String cover_price;
private String origin_price;
private String figure;
public String getProduct_id() {
return product_id;
}
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCover_price() {
return cover_price;
}
public void setCover_price(String cover_price) {
this.cover_price = cover_price;
}
public String getOrigin_price() {
return origin_price;
}
public void setOrigin_price(String origin_price) {
this.origin_price = origin_price;
}
public String getFigure() {
return figure;
}
public void setFigure(String figure) {
this.figure = figure;
}
}
}
public static class BannerInfoBean {
private String image;
private int option;
private int type;
private ValueBean valueBean;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getOption() {
return option;
}
public void setOption(int option) {
this.option = option;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public ValueBean getValueBean() {
return valueBean;
}
public void setValueBean(ValueBean valueBean) {
this.valueBean = valueBean;
}
@Override
public String toString() {
return "BannerInfoBean{" +
"image='" + image + '\'' +
", option=" + option +
", type=" + type +
", valueBean=" + valueBean +
'}';
}
public static class ValueBean {
private String url;
private String product_id;
private String brand_id;
@Override
public String toString() {
return "ValueBean{" +
"url='" + url + '\'' +
", product_id='" + product_id + '\'' +
", brand_id='" + brand_id + '\'' +
'}';
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getProduct_id() {
return product_id;
}
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
public String getBrand_id() {
return brand_id;
}
public void setBrand_id(String brand_id) {
this.brand_id = brand_id;
}
}
}
public static class ChannelInfoBean {
private int option;
private int type;
private String channel_name;
private String image;
private ValueBean value;
public int getOption() {
return option;
}
public void setOption(int option) {
this.option = option;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getChannel_name() {
return channel_name;
}
public void setChannel_name(String channel_name) {
this.channel_name = channel_name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public static class ValueBean {
private String channel_id;
}
@Override
public String toString() {
return "ChannelInfoBean{" +
"option=" + option +
", type=" + type +
", channel_name='" + channel_name + '\'' +
", image='" + image + '\'' +
", value=" + value +
'}';
}
}
public static class ActInfoBean {
private String name;
private String icon_url;
private String url;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon_url() {
return icon_url;
}
public void setIcon_url(String icon_url) {
this.icon_url = icon_url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "ActInfoBean{" +
"name='" + name + '\'' +
", icon_url='" + icon_url + '\'' +
", url='" + url + '\'' +
'}';
}
}
public static class HotInfoBean {
private String product_id;
private String name;
private String cover_price;
private String figure;
public String getProduct_id() {
return product_id;
}
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCover_price() {
return cover_price;
}
public void setCover_price(String cover_price) {
this.cover_price = cover_price;
}
public String getFigure() {
return figure;
}
public void setFigure(String figure) {
this.figure = figure;
}
@Override
public String toString() {
return "HotInfoBean{" +
"product_id='" + product_id + '\'' +
", name='" + name + '\'' +
", cover_price='" + cover_price + '\'' +
", figure='" + figure + '\'' +
'}';
}
}
public static class RecommendInfoBean {
private String product_id;
private String name;
private String cover_price;
private String figure;
public String getProduct_id() {
return product_id;
}
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCover_price() {
return cover_price;
}
public void setCover_price(String cover_price) {
this.cover_price = cover_price;
}
public String getFigure() {
return figure;
}
public void setFigure(String figure) {
this.figure = figure;
}
@Override
public String toString() {
return "RecommendInfoBean{" +
"product_id='" + product_id + '\'' +
", name='" + name + '\'' +
", cover_price='" + cover_price + '\'' +
", figure='" + figure + '\'' +
'}';
}
}
}
|
9232f23a4c5a5a301be55740eba1dcbbcec13f5b | 2,674 | java | Java | src/main/java/cn/mireal/disruptor/advanced/Main.java | pursue-wind/hello-disruptor | 65cdb94ca06d57fe954242cf22131c1a4ce883cc | [
"Apache-2.0"
] | 3 | 2020-12-27T06:10:56.000Z | 2021-03-31T15:12:37.000Z | src/main/java/cn/mireal/disruptor/advanced/Main.java | pursue-wind/hello-disruptor | 65cdb94ca06d57fe954242cf22131c1a4ce883cc | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/mireal/disruptor/advanced/Main.java | pursue-wind/hello-disruptor | 65cdb94ca06d57fe954242cf22131c1a4ce883cc | [
"Apache-2.0"
] | null | null | null | 31.833333 | 104 | 0.623411 | 996,413 | package cn.mireal.disruptor.advanced;
import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.EventHandlerGroup;
import com.lmax.disruptor.dsl.ProducerType;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Mireal
* @version V1.0
* @date 2020/2/3 17:15
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
//构建一个线程池用于提交任务
ExecutorService es1 = Executors.newFixedThreadPool(1);
ExecutorService es = Executors.newFixedThreadPool(4);
//1 构建Disruptor
Disruptor<Trade> disruptor = new Disruptor<Trade>(
Trade::new,
1024 * 1024,
es,
ProducerType.SINGLE,
new BusySpinWaitStrategy());
//2 把消费者设置到Disruptor中 handleEventsWith
/**2.1 串行操作:*/
/* disruptor
.handleEventsWith(new Handler1())
.handleEventsWith(new Handler2())
.handleEventsWith(new Handler3());*/
/**2.2 并行操作: 可以有两种方式去进行*/
//1 handleEventsWith方法 添加多个handler实现即可
//2 handleEventsWith方法 分别进行调用
// disruptor.handleEventsWith(new Handler1(), new Handler2(), new Handler3());
// disruptor.handleEventsWith(new Handler2());
// disruptor.handleEventsWith(new Handler3());
/**2.3 菱形操作 (一)*/
/*
disruptor.handleEventsWith(new Handler1(), new Handler2())
.handleEventsWith(new Handler3());
*/
/**2.3 菱形操作 (二)*/
/* EventHandlerGroup<Trade> ehGroup = disruptor.handleEventsWith(new Handler1(), new Handler2());
ehGroup.then(new Handler3());*/
/**2.4 六边形操作 (二)*/
Handler1 h1 = new Handler1();
Handler2 h2 = new Handler2();
Handler3 h3 = new Handler3();
Handler4 h4 = new Handler4();
Handler5 h5 = new Handler5();
disruptor.handleEventsWith(h1, h4);
disruptor.after(h1).handleEventsWith(h2);
disruptor.after(h4).handleEventsWith(h5);
disruptor.after(h2, h5).handleEventsWith(h3);
//3 启动disruptor
RingBuffer<Trade> ringBuffer = disruptor.start();
CountDownLatch latch = new CountDownLatch(1);
long begin = System.currentTimeMillis();
es1.submit(new TradePushlisher(latch, disruptor));
latch.await(); //进行向下
disruptor.shutdown();
es.shutdown();
System.err.println("总耗时: " + (System.currentTimeMillis() - begin));
}
}
|
9232f5ba6b04031c4ab8771c519f6dd9107aa8c3 | 1,990 | java | Java | de.dc.javafx.xcore.workbench/src-gen/de/dc/javafx/xcore/workbench/NamedElement.java | chqu1012/de.dc.emf.javafx.xtext.lang | c6e6c8686285c8cb852c057693427b47e3662b84 | [
"Apache-2.0"
] | 5 | 2019-04-14T12:15:30.000Z | 2019-05-17T15:19:29.000Z | de.dc.javafx.xcore.workbench/src-gen/de/dc/javafx/xcore/workbench/NamedElement.java | chqu1012/de.dc.emf.javafx.xtext.lang | c6e6c8686285c8cb852c057693427b47e3662b84 | [
"Apache-2.0"
] | 456 | 2019-04-09T08:22:26.000Z | 2019-06-29T09:19:32.000Z | de.dc.javafx.xcore.workbench/src-gen/de/dc/javafx/xcore/workbench/NamedElement.java | chqu1012/de.dc.emf.javafx.xtext.lang | c6e6c8686285c8cb852c057693427b47e3662b84 | [
"Apache-2.0"
] | null | null | null | 28.428571 | 111 | 0.602513 | 996,414 | /**
*/
package de.dc.javafx.xcore.workbench;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Named Element</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link de.dc.javafx.xcore.workbench.NamedElement#get_Id <em>Id</em>}</li>
* <li>{@link de.dc.javafx.xcore.workbench.NamedElement#getName <em>Name</em>}</li>
* </ul>
*
* @see de.dc.javafx.xcore.workbench.WorkbenchPackage#getNamedElement()
* @model
* @generated
*/
public interface NamedElement extends EObject {
/**
* Returns the value of the '<em><b>Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Id</em>' attribute.
* @see #set_Id(String)
* @see de.dc.javafx.xcore.workbench.WorkbenchPackage#getNamedElement__Id()
* @model unique="false"
* @generated
*/
String get_Id();
/**
* Sets the value of the '{@link de.dc.javafx.xcore.workbench.NamedElement#get_Id <em>Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Id</em>' attribute.
* @see #get_Id()
* @generated
*/
void set_Id(String value);
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see de.dc.javafx.xcore.workbench.WorkbenchPackage#getNamedElement_Name()
* @model unique="false"
* @generated
*/
String getName();
/**
* Sets the value of the '{@link de.dc.javafx.xcore.workbench.NamedElement#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // NamedElement
|
9232f656cac54bbcf9d3ea3b8fef148462cd3d0a | 449 | java | Java | android/src/main/java/com/reactnativenfcsuppress/NFCException.java | Gothfrid/react-native-nfc-suppress | eaec17544ee149b6968bb9a821e28e2912dc6351 | [
"MIT"
] | null | null | null | android/src/main/java/com/reactnativenfcsuppress/NFCException.java | Gothfrid/react-native-nfc-suppress | eaec17544ee149b6968bb9a821e28e2912dc6351 | [
"MIT"
] | null | null | null | android/src/main/java/com/reactnativenfcsuppress/NFCException.java | Gothfrid/react-native-nfc-suppress | eaec17544ee149b6968bb9a821e28e2912dc6351 | [
"MIT"
] | null | null | null | 18.708333 | 69 | 0.69265 | 996,415 | package com.reactnativenfcsuppress;
public class NFCException extends Exception {
private String code;
public NFCException(String code, String message) {
super(message);
this.setCode(code);
}
public NFCException(String code, String message, Throwable cause) {
super(message, cause);
this.setCode(code);
}
public String getCode() {
return code;
}
public void setCode(String code){
this.code = code;
}
}
|
9232f80d2433d2415d6668256a06967f188a4d8a | 1,133 | java | Java | src/main/java/de/dhbw/trekker/FilterAPI.java | DorianSnowball/FileTrekker | 875ac714a9ec6af93bbb7a93369a6dbe8b98d871 | [
"MIT"
] | null | null | null | src/main/java/de/dhbw/trekker/FilterAPI.java | DorianSnowball/FileTrekker | 875ac714a9ec6af93bbb7a93369a6dbe8b98d871 | [
"MIT"
] | null | null | null | src/main/java/de/dhbw/trekker/FilterAPI.java | DorianSnowball/FileTrekker | 875ac714a9ec6af93bbb7a93369a6dbe8b98d871 | [
"MIT"
] | null | null | null | 22.215686 | 76 | 0.64872 | 996,416 | package de.dhbw.trekker;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FilterAPI {
private String name;
private HashMap<String, Integer> combinations = new HashMap<>();
private List<Instant> occurrencesTime = new ArrayList<>();
private int count;
public FilterAPI(String name) {
this.name = name;
}
public void count() {
count++;
}
public void addCombinationWith(String apiName) {
combinations.put(apiName, combinations.getOrDefault(apiName,0) + 1);
}
public int getCount() {
return count;
}
public String getName() {
return name;
}
public HashMap<String, Integer> getCombinations() {
return combinations;
}
/**
* Returns the sorted OccurrencesTimeList
* @return sorted OccurrencesTimeList
*/
public List<Instant> getOccurrencesTime() {
occurrencesTime.sort(Instant::compareTo);
return occurrencesTime;
}
public void addOccurrenceTime(Instant time) {
occurrencesTime.add(time);
}
}
|
9232f8183e9dbb12a2e9f9b4e8338550fb388cbb | 1,406 | java | Java | apollo-runtime/src/main/java/com/apollographql/apollo/internal/util/ApolloLogger.java | airbnb/apollo-android | 44c9f021c13099b493de3c545d63ff91c27818e8 | [
"MIT"
] | 75 | 2017-03-12T15:13:28.000Z | 2021-07-29T19:40:02.000Z | apollo-runtime/src/main/java/com/apollographql/apollo/internal/util/ApolloLogger.java | airbnb/apollo-android | 44c9f021c13099b493de3c545d63ff91c27818e8 | [
"MIT"
] | 1 | 2019-10-24T23:01:10.000Z | 2019-10-25T07:18:08.000Z | apollo-runtime/src/main/java/com/apollographql/apollo/internal/util/ApolloLogger.java | sav007/apollo-android | 60b9dd4ed099bc3058e8b468aa3a40318e05911d | [
"MIT"
] | 7 | 2017-03-07T02:58:41.000Z | 2021-07-29T19:40:15.000Z | 28.693878 | 98 | 0.703414 | 996,417 | package com.apollographql.apollo.internal.util;
import com.apollographql.apollo.Logger;
import com.apollographql.apollo.api.internal.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static com.apollographql.apollo.api.internal.Utils.checkNotNull;
public final class ApolloLogger {
private final Optional<Logger> logger;
public ApolloLogger(@Nonnull Optional<Logger> logger) {
this.logger = checkNotNull(logger, "logger == null");
}
public void d(@Nonnull String message, Object... args) {
log(Logger.DEBUG, message, null, args);
}
public void d(@Nullable Throwable t, @Nonnull String message, Object... args) {
log(Logger.DEBUG, message, t, args);
}
public void w(@Nonnull String message, Object... args) {
log(Logger.WARN, message, null, args);
}
public void w(@Nullable Throwable t, @Nonnull String message, Object... args) {
log(Logger.WARN, message, t, args);
}
public void e(@Nonnull String message, Object... args) {
log(Logger.ERROR, message, null, args);
}
public void e(@Nullable Throwable t, @Nonnull String message, Object... args) {
log(Logger.ERROR, message, t, args);
}
private void log(int priority, @Nonnull String message, @Nullable Throwable t, Object... args) {
if (logger.isPresent()) {
logger.get().log(priority, message, Optional.fromNullable(t), args);
}
}
}
|
9232f8f9eb22ccc9315432246e9bed68caa7aefe | 248 | java | Java | java9-examples/src/main/java/module-info.java | r0haaaan/vertx-examples | c24b4e15a68d028b362c92d77c69fff11cf94745 | [
"Apache-2.0"
] | 3 | 2018-07-09T08:05:36.000Z | 2018-07-09T08:05:40.000Z | java9-examples/src/main/java/module-info.java | yooJoviChou/vertx-examples | 74cb9ca8c607fb417918e53dda680d2273e8b310 | [
"Apache-2.0"
] | 1 | 2022-02-11T00:30:06.000Z | 2022-02-11T00:30:06.000Z | java9-examples/src/main/java/module-info.java | yooJoviChou/vertx-examples | 74cb9ca8c607fb417918e53dda680d2273e8b310 | [
"Apache-2.0"
] | 1 | 2018-07-20T08:39:46.000Z | 2018-07-20T08:39:46.000Z | 20.666667 | 88 | 0.758065 | 996,418 | // Opening the module allows Vertx to access the server-keystore.jks via the classloader
open module java9.examples {
requires vertx.core;
requires vertx.web;
requires vertx.jdbc.client;
requires vertx.sql.common;
requires java.sql;
}
|
9232f9d72bf65b00860faae4c0a9d801b934a716 | 4,801 | java | Java | src/test/java/se/almstudio/booking/api/repository/impl/DefaultRoomRepositoryTest.java | alireza-mahzoon/booking-api | b5c3589b62f042688819eb557c94d94f7121927c | [
"Apache-2.0"
] | null | null | null | src/test/java/se/almstudio/booking/api/repository/impl/DefaultRoomRepositoryTest.java | alireza-mahzoon/booking-api | b5c3589b62f042688819eb557c94d94f7121927c | [
"Apache-2.0"
] | 1 | 2022-02-16T01:11:37.000Z | 2022-02-16T01:11:37.000Z | src/test/java/se/almstudio/booking/api/repository/impl/DefaultRoomRepositoryTest.java | alireza-mahzoon/booking-api | b5c3589b62f042688819eb557c94d94f7121927c | [
"Apache-2.0"
] | null | null | null | 35.828358 | 89 | 0.746511 | 996,419 | package se.almstudio.booking.api.repository.impl;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import se.almstudio.booking.api.model.entity.Hotel;
import se.almstudio.booking.api.model.entity.Room;
import se.almstudio.booking.api.model.entity.RoomType;
import java.time.LocalDateTime;
public class DefaultRoomRepositoryTest {
private static Long hotelId;
private static Long roomTypeId;
private static Long roomTypeUpdateId;
@BeforeClass
public static void beforeClass() {
DefaultHotelRepository hotelRepository = new DefaultHotelRepository();
Hotel hotel = new Hotel();
hotel.setName("Scandic");
hotel.setCity("Stockholm");
hotel.setCountry("Sweden");
hotel.setAddress("Sundby");
hotel.setRegistered(LocalDateTime.now());
hotel.setUpdated(LocalDateTime.now());
hotelId = hotelRepository.create(hotel);
DefaultRoomTypeRepository roomTypeRepository = new DefaultRoomTypeRepository();
RoomType roomType = new RoomType();
roomType.setHotelId(hotelId);
roomType.setName("typeOne");
roomType.setDescription("oneBed");
roomType.setCapacity(1);
roomType.setRegistered(LocalDateTime.now());
roomType.setUpdated(LocalDateTime.now());
roomTypeId = roomTypeRepository.create(roomType);
DefaultRoomTypeRepository roomTypeUpdateRepository = new DefaultRoomTypeRepository();
RoomType roomTypeUpdate = new RoomType();
roomTypeUpdate.setHotelId(hotelId);
roomTypeUpdate.setName("typeTwo");
roomTypeUpdate.setDescription("TwoBeds");
roomTypeUpdate.setCapacity(2);
roomTypeUpdate.setRegistered(LocalDateTime.now());
roomTypeUpdate.setUpdated(LocalDateTime.now());
roomTypeUpdateId = roomTypeUpdateRepository.create(roomType);
}
@AfterClass
public static void afterClass() {
DefaultRoomRepository roomRepository = new DefaultRoomRepository();
roomRepository.deleteRoomByHotelID(hotelId);
DefaultRoomTypeRepository roomTypeRepository = new DefaultRoomTypeRepository();
roomTypeRepository.delete(roomTypeId);
roomTypeRepository.delete(roomTypeUpdateId);
DefaultHotelRepository hotelRepository = new DefaultHotelRepository();
hotelRepository.delete(hotelId);
}
@Test
public void testCreateRoomExpectNoneNullId() {
DefaultRoomRepository roomRepository = new DefaultRoomRepository();
Room room = new Room();
room.setHotelId(hotelId);
room.setNumber(99);
room.setPhoneNumber("964389");
room.setFloor(25);
room.setRoomTypeId(roomTypeId);
room.setRegistered(LocalDateTime.now());
room.setUpdated(LocalDateTime.now());
Long result = roomRepository.create(room);
Assert.assertNotNull(result);
Assert.assertNotEquals(0L, result.longValue());
}
@Test
public void testReadRoomByRoomIdExpectRoom() {
DefaultRoomRepository roomRepository = new DefaultRoomRepository();
Room room = new Room();
room.setHotelId(hotelId);
room.setNumber(83);
room.setPhoneNumber("4623784");
room.setFloor(23);
room.setRoomTypeId(roomTypeId);
Long resultRoomCreated = roomRepository.create(room);
Room roomCreated = roomRepository.findById(resultRoomCreated);
Assert.assertEquals(room.getHotelId(), roomCreated.getHotelId());
Assert.assertEquals(room.getNumber(), roomCreated.getNumber());
Assert.assertEquals(room.getPhoneNumber(), roomCreated.getPhoneNumber());
Assert.assertEquals(room.getFloor(), roomCreated.getFloor());
Assert.assertEquals(room.getRoomTypeId(), roomCreated.getRoomTypeId());
}
@Test
public void testUpdateRoomExpectTrue() {
DefaultRoomRepository roomRepository = new DefaultRoomRepository();
Room room = new Room();
room.setHotelId(hotelId);
room.setNumber(99);
room.setPhoneNumber("964389");
room.setFloor(25);
room.setRoomTypeId(roomTypeId);
room.setRegistered(LocalDateTime.now());
room.setUpdated(LocalDateTime.now());
Long roomId = roomRepository.create(room);
room.setNumber(88);
room.setPhoneNumber("631826");
room.setFloor(30);
room.setRoomTypeId(roomTypeUpdateId);
room.setId(roomId);
boolean resultUpdate = roomRepository.update(room);
Assert.assertTrue(resultUpdate);
}
@Test
public void testDeleteRoomExpectTrue() {
DefaultRoomRepository roomRepository = new DefaultRoomRepository();
Room room = new Room();
room.setHotelId(hotelId);
room.setNumber(99);
room.setPhoneNumber("964389");
room.setFloor(25);
room.setRoomTypeId(roomTypeId);
room.setRegistered(LocalDateTime.now());
room.setUpdated(LocalDateTime.now());
Long roomId = roomRepository.create(room);
boolean resultDelete = roomRepository.delete(roomId);
Assert.assertTrue(resultDelete);
}
}
|
9232fb67569aa47ff6d977662505ed5f4132cdd0 | 3,131 | java | Java | app/src/main/java/com/lqr/wechat/ui/presenter/MainAtPresenter.java | yuzhongrong/BlockChat | 0d8af2a37b43519974aaeddc1ba5fdb920f02c5f | [
"MIT"
] | 3 | 2019-06-03T12:50:51.000Z | 2021-02-21T06:43:00.000Z | app/src/main/java/com/lqr/wechat/ui/presenter/MainAtPresenter.java | yuzhongrong/BlockChat | 0d8af2a37b43519974aaeddc1ba5fdb920f02c5f | [
"MIT"
] | null | null | null | app/src/main/java/com/lqr/wechat/ui/presenter/MainAtPresenter.java | yuzhongrong/BlockChat | 0d8af2a37b43519974aaeddc1ba5fdb920f02c5f | [
"MIT"
] | 1 | 2021-02-21T06:42:39.000Z | 2021-02-21T06:42:39.000Z | 31 | 122 | 0.569786 | 996,420 | package com.lqr.wechat.ui.presenter;
import com.ipeercloud.com.controler.GsSocketManager;
import com.lqr.wechat.R;
import com.lqr.wechat.app.AppConst;
import com.lqr.wechat.app.MyApp;
import com.lqr.wechat.db.DBManager;
import com.lqr.wechat.manager.BroadcastManager;
import com.lqr.wechat.model.cache.UserCache;
import com.lqr.wechat.ui.base.BaseActivity;
import com.lqr.wechat.ui.base.BasePresenter;
import com.lqr.wechat.ui.view.IMainAtView;
import com.lqr.wechat.util.LogUtils;
import com.lqr.wechat.util.UIUtils;
import io.rong.imlib.RongIMClient;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class MainAtPresenter extends BasePresenter<IMainAtView> {
public MainAtPresenter(BaseActivity context) {
super(context);
connect(UserCache.getToken());
//同步所有用户信息
DBManager.getInstance().getAllUserInfo();
initConnect("http://sz.goonas.com",8190,"13662664466","1");
}
public void initConnect(String serverIp, int port, String userName, String pwd){
Observable.just("")
.observeOn(Schedulers.io())
.map(new Func1<String, Boolean>() {
@Override
public Boolean call(String aVoid) {
return GsSocketManager.getInstance().gsGproxyInit(serverIp,port,userName,pwd);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s->{if(s){LogUtils.d("-----连接成功--->");}else{LogUtils.d("-----连接失败--->");}}
,e-> LogUtils.sf(e.getLocalizedMessage()));
}
/**
* 建立与融云服务器的连接
*
* @param token
*/
private void connect(String token) {
if (UIUtils.getContext().getApplicationInfo().packageName.equals(MyApp.getCurProcessName(UIUtils.getContext()))) {
/**
* IMKit SDK调用第二步,建立与服务器的连接
*/
RongIMClient.connect(token, new RongIMClient.ConnectCallback() {
/**
* Token 错误,在线上环境下主要是因为 Token 已经过期,您需要向 App Server 重新请求一个新的 Token
*/
@Override
public void onTokenIncorrect() {
LogUtils.e("--onTokenIncorrect");
}
/**
* 连接融云成功
* @param userid 当前 token
*/
@Override
public void onSuccess(String userid) {
LogUtils.e("--onSuccess---" + userid);
BroadcastManager.getInstance(mContext).sendBroadcast(AppConst.UPDATE_CONVERSATIONS);
}
/**
* 连接融云失败
* @param errorCode 错误码,可到官网 查看错误码对应的注释
*/
@Override
public void onError(RongIMClient.ErrorCode errorCode) {
LogUtils.e("--onError" + errorCode);
UIUtils.showToast(UIUtils.getString(R.string.disconnect_server));
}
});
}
}
}
|
9232fbf3c0e5a740c526e3771427ed657c51de22 | 918 | java | Java | _src/Module 2/Chapter_02/webstore/src/main/java/com/packt/webstore/controller/ProductController.java | paullewallencom/spring-978-1-7871-2755-5 | 541209a03d35f7d804dff5242e6053c62df8983e | [
"Apache-2.0"
] | 42 | 2016-10-13T02:26:38.000Z | 2021-07-19T02:04:48.000Z | _src/Module 2/Chapter_02/webstore/src/main/java/com/packt/webstore/controller/ProductController.java | paullewallencom/spring-978-1-7871-2755-5 | 541209a03d35f7d804dff5242e6053c62df8983e | [
"Apache-2.0"
] | 25 | 2020-05-15T22:14:02.000Z | 2021-12-09T22:03:07.000Z | _src/Module 2/Chapter_02/webstore/src/main/java/com/packt/webstore/controller/ProductController.java | paullewallencom/spring-978-1-7871-2755-5 | 541209a03d35f7d804dff5242e6053c62df8983e | [
"Apache-2.0"
] | 50 | 2016-08-04T06:34:13.000Z | 2021-05-06T21:31:21.000Z | 24.810811 | 71 | 0.798475 | 996,421 | package com.packt.webstore.controller;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.packt.webstore.domain.Product;
import com.packt.webstore.domain.repository.ProductRepository;
import com.packt.webstore.service.ProductService;
@Controller
public class ProductController {
@Autowired
private ProductRepository productRepository;
@Autowired
private ProductService productService;
@RequestMapping("/products")
public String list(Model model) {
model.addAttribute("products", productRepository.getAllProducts());
return "products";
}
@RequestMapping("/update/stock")
public String updateStock(Model model) {
productService.updateAllStock();
return "redirect:/products";
}
}
|
9232fc116eda72c040d1323655ffeac1cb3cdfa2 | 1,241 | java | Java | app/src/main/java/com/workbook/liuwb/workbook/actions/appstructure/mvp/v1/UserContract.java | bobo-lwenb/workbook | 9057c0ed87d0241a7704c7dfb9e285a378c2224e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/workbook/liuwb/workbook/actions/appstructure/mvp/v1/UserContract.java | bobo-lwenb/workbook | 9057c0ed87d0241a7704c7dfb9e285a378c2224e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/workbook/liuwb/workbook/actions/appstructure/mvp/v1/UserContract.java | bobo-lwenb/workbook | 9057c0ed87d0241a7704c7dfb9e285a378c2224e | [
"Apache-2.0"
] | null | null | null | 17.985507 | 78 | 0.488316 | 996,422 | package com.workbook.liuwb.workbook.actions.appstructure.mvp.v1;
import com.workbook.liuwb.workbook.actions.appstructure.mvp.v1.model.UserBean;
/**
* 契约接口,用来存放User相关的Model,View 和 Presenter的接口
*/
public interface UserContract {
interface Model {
/**
* 从SharedPreferences中获取UserBean对象
*
* @return 取得的对象
*/
UserBean loadUser();
/**
* 将用户信息保存到SharedPreferences中
*
* @param userBean
* @return 是否成功保存
*/
boolean saveUser(UserBean userBean);
}
interface View extends BaseView<Presenter> {
/**
* @return 返回从编辑框输入的名字
*/
String getInputName();
/**
* @return 返回从编辑框输入的年龄
*/
int getInputAge();
/**
* 更新UI,更新显示姓名
*
* @param name
*/
void setName(String name);
/**
* 更新UI,更新显示年龄
*
* @param age
*/
void setAge(int age);
}
interface Presenter extends BasePresenter {
/**
* 加载用户信息
*/
void loadUser();
/**
* @return 是否成功保存
* 保存用户信息
*/
boolean saveUser();
}
}
|
9232fc8a6528d0501d48105a3e9c7b6db983ed61 | 951 | java | Java | basic/src/main/java/com/flyonsky/concurrent/TimerSchedule.java | flyonskycn/java-study | 84de0744d80cd5435771f9e5e39173509d2fad0f | [
"Apache-2.0"
] | null | null | null | basic/src/main/java/com/flyonsky/concurrent/TimerSchedule.java | flyonskycn/java-study | 84de0744d80cd5435771f9e5e39173509d2fad0f | [
"Apache-2.0"
] | null | null | null | basic/src/main/java/com/flyonsky/concurrent/TimerSchedule.java | flyonskycn/java-study | 84de0744d80cd5435771f9e5e39173509d2fad0f | [
"Apache-2.0"
] | null | null | null | 24.384615 | 92 | 0.560463 | 996,423 | package com.flyonsky.concurrent;
import java.text.MessageFormat;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author luowengang
* @date 2020/9/6 20:01
*/
public class TimerSchedule {
public static void main(String[] args) {
Timer t = new Timer();
for(int i =0;i <10;i ++){
t.schedule( new TimerService(i ), 1000);
}
}
private static class TimerService extends TimerTask {
private int num ;
public TimerService(int i){
this.num = i ;
}
@Override
public void run() {
int l = new Random().nextInt();
System. out.println(MessageFormat.format( "thread{0} is success", this. num));
if(l % 2 == 0){
System. out.println(MessageFormat.format( "thread{0} is Error", this. num));
throw new NullPointerException();
}
}
}
}
|
9232fceeb39eb25f02f62b3e31f641003db8c2d0 | 494 | java | Java | cuner-hystrix-turbine/src/main/java/cuner/HystrixTurbineApp.java | distantguang/studycloud | f2108419b0280cf953f9c7ac83f3d7fe02aee5db | [
"Apache-2.0"
] | null | null | null | cuner-hystrix-turbine/src/main/java/cuner/HystrixTurbineApp.java | distantguang/studycloud | f2108419b0280cf953f9c7ac83f3d7fe02aee5db | [
"Apache-2.0"
] | null | null | null | cuner-hystrix-turbine/src/main/java/cuner/HystrixTurbineApp.java | distantguang/studycloud | f2108419b0280cf953f9c7ac83f3d7fe02aee5db | [
"Apache-2.0"
] | null | null | null | 30.875 | 82 | 0.827935 | 996,424 | package cuner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;
@SpringBootApplication
@EnableHystrixDashboard
@EnableTurbine
public class HystrixTurbineApp {
public static void main(String[] args) {
SpringApplication.run(HystrixTurbineApp.class, args);
}
}
|
9232fcf6def3d68bd2351c1ed9923497d5c97b84 | 197 | java | Java | src/main/java/nl/tsfs/rager/model/Configuration.java | Nicate/Rager | 12ae608d12c3f89553697654562efd157fd4a232 | [
"MIT"
] | null | null | null | src/main/java/nl/tsfs/rager/model/Configuration.java | Nicate/Rager | 12ae608d12c3f89553697654562efd157fd4a232 | [
"MIT"
] | 1 | 2018-01-12T23:48:37.000Z | 2018-02-24T01:43:15.000Z | src/main/java/nl/tsfs/rager/model/Configuration.java | TwoStepsFromSpace/Rager | 12ae608d12c3f89553697654562efd157fd4a232 | [
"MIT"
] | null | null | null | 16.416667 | 68 | 0.720812 | 996,425 | package nl.tsfs.rager.model;
public class Configuration extends Persistable {
private static final long serialVersionUID = 3714466867514132841L;
public Configuration() {
}
}
|
9232fedc5f62f02cc9b82c1ce52a26cd03af06dd | 1,041 | java | Java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java | PromiseChan/dubbo | 2062cdb2c537000c86555570c8d6c894f88bb7b7 | [
"Apache-2.0"
] | 18,012 | 2015-01-01T00:59:11.000Z | 2018-03-19T09:21:57.000Z | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java | PromiseChan/dubbo | 2062cdb2c537000c86555570c8d6c894f88bb7b7 | [
"Apache-2.0"
] | 5,223 | 2019-05-24T14:39:50.000Z | 2022-03-31T10:27:18.000Z | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java | PromiseChan/dubbo | 2062cdb2c537000c86555570c8d6c894f88bb7b7 | [
"Apache-2.0"
] | 10,640 | 2015-01-03T08:47:16.000Z | 2018-03-19T09:00:46.000Z | 37.178571 | 75 | 0.748319 | 996,426 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
/**
* A class to covert {@link String} to the target-typed value
*
* @see Converter
* @since 2.7.6
*/
@FunctionalInterface
public interface StringConverter<T> extends Converter<String, T> {
}
|
9232ffa44e697d676355c7edb5871441aa52585b | 1,405 | java | Java | dl-manager/dl-manager-core/src/main/java/com/ucar/datalink/manager/core/web/dto/interceptor/InterceptorView.java | Diffblue-benchmarks/DataLink | 51279288914d6b1d5158cc020bb07744de6eecd7 | [
"Apache-2.0"
] | 971 | 2018-09-29T11:31:16.000Z | 2022-03-28T17:26:44.000Z | dl-manager/dl-manager-core/src/main/java/com/ucar/datalink/manager/core/web/dto/interceptor/InterceptorView.java | Diffblue-benchmarks/DataLink | 51279288914d6b1d5158cc020bb07744de6eecd7 | [
"Apache-2.0"
] | 45 | 2018-10-23T02:52:45.000Z | 2021-01-09T08:57:12.000Z | dl-manager/dl-manager-core/src/main/java/com/ucar/datalink/manager/core/web/dto/interceptor/InterceptorView.java | Diffblue-benchmarks/DataLink | 51279288914d6b1d5158cc020bb07744de6eecd7 | [
"Apache-2.0"
] | 382 | 2018-09-30T09:45:32.000Z | 2022-03-04T01:50:49.000Z | 18.733333 | 60 | 0.614235 | 996,427 | package com.ucar.datalink.manager.core.web.dto.interceptor;
import com.ucar.datalink.domain.interceptor.InterceptorType;
import java.util.Date;
/**
* Created by sqq on 2017/5/24.
*/
public class InterceptorView {
private Long id;
private String name;
private String desc;
private InterceptorType type;
private String content;
private Date createTime;
private Date modifyTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public InterceptorType getType() {
return type;
}
public void setType(InterceptorType type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
}
|
923300316d438ba2e90c139ce0f6efa2197d2814 | 643 | java | Java | src/main/java/leetcode/Problem553.java | fredyw/leetcode | 792dce91c2aa387ea666c05975c0c9aa2890b5a0 | [
"MIT"
] | 2 | 2017-06-28T03:13:17.000Z | 2019-07-07T02:18:28.000Z | src/main/java/leetcode/Problem553.java | fredyw/leetcode | 792dce91c2aa387ea666c05975c0c9aa2890b5a0 | [
"MIT"
] | null | null | null | src/main/java/leetcode/Problem553.java | fredyw/leetcode | 792dce91c2aa387ea666c05975c0c9aa2890b5a0 | [
"MIT"
] | 1 | 2017-06-28T03:13:21.000Z | 2017-06-28T03:13:21.000Z | 25.72 | 57 | 0.452566 | 996,428 | package leetcode;
/**
* https://leetcode.com/problems/optimal-division/
*/
public class Problem553 {
public String optimalDivision(int[] nums) {
if (nums.length == 1) {
return Integer.toString(nums[0]);
} else if (nums.length == 2) {
return nums[0] + "/" + nums[1];
}
String result = Integer.toString(nums[0]) + "/(";
for (int i = 2; i < nums.length; i++) {
if (i + 1 < nums.length) {
result += nums[i] + "/";
} else {
result += nums[i];
}
}
result += ")";
return result;
}
}
|
923300463de68589f627e948d9d1ddada60f0322 | 4,556 | java | Java | min-dataset/train/zest/org.eclipse.zest.tests/src/org/eclipse/zest/tests/IFigureProviderTests.java | giganticode/icse-2020 | 80235ada6a02273e7062f159a6ee34c99178a5ab | [
"Apache-2.0"
] | 2 | 2020-12-14T19:10:37.000Z | 2022-01-21T10:54:35.000Z | min-dataset/train/zest/org.eclipse.zest.tests/src/org/eclipse/zest/tests/IFigureProviderTests.java | giganticode/icse-2020 | 80235ada6a02273e7062f159a6ee34c99178a5ab | [
"Apache-2.0"
] | 6 | 2020-01-28T23:16:34.000Z | 2022-02-10T00:44:45.000Z | min-dataset/train/zest/org.eclipse.zest.tests/src/org/eclipse/zest/tests/IFigureProviderTests.java | giganticode/icse-2020 | 80235ada6a02273e7062f159a6ee34c99178a5ab | [
"Apache-2.0"
] | null | null | null | 27.281437 | 81 | 0.695566 | 996,429 | /*******************************************************************************
* Copyright (c) 2011 Fabian Steeg. 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
* <p/>
* Contributors: Fabian Steeg - initial tests
*******************************************************************************/
package org.eclipse.zest.tests;
import junit.framework.TestCase;
import org.eclipse.draw2d.BorderLayout;
import org.eclipse.draw2d.Ellipse;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.zest.core.viewers.GraphViewer;
import org.eclipse.zest.core.viewers.IFigureProvider;
import org.eclipse.zest.core.viewers.IGraphContentProvider;
import org.eclipse.zest.core.widgets.custom.CGraphNode;
import org.eclipse.zest.tests.GraphViewerTests.SampleGraphContentProvider;
import org.eclipse.zest.tests.GraphViewerTests.SampleGraphEntityContentProvider;
/**
* Tests for the {@link IFigureProvider} class.
*
* @author Fabian Steeg (fsteeg)
*
*/
public class IFigureProviderTests extends TestCase {
private GraphViewer viewer;
private Shell shell;
/**
* Set up the shell and viewer to use in the tests.
*
* @see junit.framework.TestCase#setUp()
*/
public void setUp() {
shell = new Shell();
viewer = new GraphViewer(shell, SWT.NONE);
}
/**
* Test with IGraphContentProvider that provides destinations only.
*/
public void testWithDestinationProvider() {
testWith(new DestinationContentProvider());
}
/**
* Test with IGraphContentProvider that provides sources only.
*/
public void testWithSourceProvider() {
testWith(new SourceContentProvider());
}
/**
* Test with IGraphContentProvider that provides destinations and sources.
*/
public void testWithGraphProvider() {
testWith(new SampleGraphEntityContentProvider());
}
/**
* Test with IGraphEntityContentProvider.
*/
public void testWithGraphEntityProvider() {
testWith(new SampleGraphContentProvider());
}
private void testWith(IStructuredContentProvider contentProvider) {
viewer.setContentProvider(contentProvider);
viewer.setLabelProvider(new CustomLabelProvider());
viewer.setInput(new Object());
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < viewer.getGraphControl().getNodes().size(); i++) {
CGraphNode n = (CGraphNode) viewer.getGraphControl().getNodes()
.get(i);
buffer.append(((Label) n.getFigure().getChildren().get(0))
.getText());
}
String string = buffer.toString();
assertTrue("Label 1 should be in figure labels", string.contains("1"));
assertTrue("Label 2 should be in figure labels", string.contains("2"));
assertTrue("Label 3 should be in figure labels", string.contains("3"));
}
private class DestinationContentProvider implements IGraphContentProvider {
public void dispose() {
}
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
}
public Object getDestination(Object r) {
if (r.equals("1to2"))
return "2";
if (r.equals("2to3"))
return "3";
if (r.equals("3to1"))
return "1";
return null;
}
public Object[] getElements(Object arg0) {
return new String[] { "1to2", "2to3", "3to1" };
}
public Object getSource(Object r) {
return null;
}
}
private class SourceContentProvider implements IGraphContentProvider {
public void dispose() {
}
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
}
public Object getDestination(Object r) {
return null;
}
public Object[] getElements(Object arg0) {
return new String[] { "1to2", "2to3", "3to1" };
}
public Object getSource(Object r) {
if (r.equals("1to2"))
return "1";
if (r.equals("2to3"))
return "2";
if (r.equals("3to1"))
return "3";
return null;
}
}
private class CustomLabelProvider extends LabelProvider implements
IFigureProvider {
public String getText(Object node) {
return node.toString();
}
public IFigure getFigure(Object node) {
Ellipse e = new Ellipse();
e.setSize(40, 40);
e.setLayoutManager(new BorderLayout());
e.add(new Label(node.toString()), BorderLayout.CENTER);
return e;
}
}
}
|
923300a83be698a5efab0d408a755bc31864a7ec | 6,726 | java | Java | utilcode/src/main/java/com/common/utilcode/util/ProcessUtils.java | androidroadies/AndroidUtils | a6d8f5c635441656d5f4ecc1da16efa2029d1afc | [
"MIT"
] | 1 | 2019-05-06T07:08:17.000Z | 2019-05-06T07:08:17.000Z | utilcode/src/main/java/com/common/utilcode/util/ProcessUtils.java | androidroadies/AndroidUtils | a6d8f5c635441656d5f4ecc1da16efa2029d1afc | [
"MIT"
] | null | null | null | utilcode/src/main/java/com/common/utilcode/util/ProcessUtils.java | androidroadies/AndroidUtils | a6d8f5c635441656d5f4ecc1da16efa2029d1afc | [
"MIT"
] | null | null | null | 42.840764 | 143 | 0.624591 | 996,430 | package com.common.utilcode.util;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.provider.Settings;
import android.support.annotation.NonNull;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* <pre>
* author: Mayank Dudhatra
* blog : androidroadies.blogspot.in
* time : 2016/10/18
* desc : 进程相关工具类
* </pre>
*/
public final class ProcessUtils {
private ProcessUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* 获取前台线程包名
* <p>当不是查看当前App,且SDK大于21时,
* 需添加权限 {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>}</p>
*
* @return 前台应用包名
*/
public static String getForegroundProcessName() {
ActivityManager manager = (ActivityManager) Utils.getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pInfo = manager.getRunningAppProcesses();
if (pInfo != null && pInfo.size() != 0) {
for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) {
if (aInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return aInfo.processName;
}
}
}
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
PackageManager packageManager = Utils.getContext().getPackageManager();
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
System.out.println(list);
if (list.size() > 0) {// 有"有权查看使用权限的应用"选项
try {
ApplicationInfo info = packageManager.getApplicationInfo(Utils.getContext().getPackageName(), 0);
AppOpsManager aom = (AppOpsManager) Utils.getContext().getSystemService(Context.APP_OPS_SERVICE);
if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
Utils.getContext().startActivity(intent);
}
if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
LogUtils.d("getForegroundApp", "没有打开\"有权查看使用权限的应用\"选项");
return null;
}
UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getContext().getSystemService(Context.USAGE_STATS_SERVICE);
long endTime = System.currentTimeMillis();
long beginTime = endTime - 86400000 * 7;
List<UsageStats> usageStatses = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, beginTime, endTime);
if (usageStatses == null || usageStatses.isEmpty()) return null;
UsageStats recentStats = null;
for (UsageStats usageStats : usageStatses) {
if (recentStats == null || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
recentStats = usageStats;
}
}
return recentStats == null ? null : recentStats.getPackageName();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
} else {
LogUtils.d("getForegroundApp", "无\"有权查看使用权限的应用\"选项");
}
}
return null;
}
/**
* 获取后台服务进程
* <p>需添加权限 {@code <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>}</p>
*
* @return 后台服务进程
*/
public static Set<String> getAllBackgroundProcesses() {
ActivityManager am = (ActivityManager) Utils.getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
Set<String> set = new HashSet<>();
for (ActivityManager.RunningAppProcessInfo aInfo : info) {
Collections.addAll(set, aInfo.pkgList);
}
return set;
}
/**
* 杀死所有的后台服务进程
* <p>需添加权限 {@code <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>}</p>
*
* @return 被暂时杀死的服务集合
*/
public static Set<String> killAllBackgroundProcesses() {
ActivityManager am = (ActivityManager) Utils.getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
Set<String> set = new HashSet<>();
for (ActivityManager.RunningAppProcessInfo aInfo : info) {
for (String pkg : aInfo.pkgList) {
am.killBackgroundProcesses(pkg);
set.add(pkg);
}
}
info = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo aInfo : info) {
for (String pkg : aInfo.pkgList) {
set.remove(pkg);
}
}
return set;
}
/**
* 杀死后台服务进程
* <p>需添加权限 {@code <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>}</p>
*
* @param packageName 包名
* @return {@code true}: 杀死成功<br>{@code false}: 杀死失败
*/
public static boolean killBackgroundProcesses(@NonNull String packageName) {
ActivityManager am = (ActivityManager) Utils.getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
if (info == null || info.size() == 0) return true;
for (ActivityManager.RunningAppProcessInfo aInfo : info) {
if (Arrays.asList(aInfo.pkgList).contains(packageName)) {
am.killBackgroundProcesses(packageName);
}
}
info = am.getRunningAppProcesses();
if (info == null || info.size() == 0) return true;
for (ActivityManager.RunningAppProcessInfo aInfo : info) {
if (Arrays.asList(aInfo.pkgList).contains(packageName)) {
return false;
}
}
return true;
}
}
|
923300adb605f1837be3cc8f8b858358d70e2d7f | 3,893 | java | Java | src/main/java/de/badw/strauss/glyphpicker/view/renderer/GlyphVectorRenderer.java | richard-strauss-werke/glyphpicker | 1320b1d1d06897cb8f02f1e42750e6cfd1a9e552 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/badw/strauss/glyphpicker/view/renderer/GlyphVectorRenderer.java | richard-strauss-werke/glyphpicker | 1320b1d1d06897cb8f02f1e42750e6cfd1a9e552 | [
"Apache-2.0"
] | 7 | 2015-01-26T12:02:29.000Z | 2015-02-10T10:53:59.000Z | src/main/java/de/badw/strauss/glyphpicker/view/renderer/GlyphVectorRenderer.java | aerhard/glyphpicker | 1320b1d1d06897cb8f02f1e42750e6cfd1a9e552 | [
"Apache-2.0"
] | null | null | null | 29.717557 | 83 | 0.649884 | 996,431 | /**
* Copyright 2015 Alexander Erhard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.badw.strauss.glyphpicker.view.renderer;
import de.badw.strauss.glyphpicker.model.GlyphDefinition;
import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;
import java.util.HashMap;
import java.util.Map;
import static java.awt.font.TextAttribute.*;
/**
* A font-based GlyphRenderer rendering vectors.
*/
public class GlyphVectorRenderer extends GlyphRenderer {
/**
* The Constant serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* The font render context.
*/
private final FontRenderContext frc;
/**
* The font attributes.
*/
private final Map<TextAttribute, Integer> attr;
/**
* The font name.
*/
private String fontName = null;
/**
* The scaling factor.
*/
private float factor = 0.73f;
/**
* The characters to render.
*/
private String ch = null;
/**
* Instantiates a new GlyphVectorRenderer.
*
* @param container the container
*/
public GlyphVectorRenderer(JComponent container) {
super(container);
frc = new FontRenderContext(null, true, true);
setText(null);
attr = new HashMap<TextAttribute, Integer>();
attr.put(KERNING, KERNING_ON);
attr.put(LIGATURES, LIGATURES_ON);
}
/* (non-Javadoc)
* @see GlyphRenderer#getRendererComponent(GlyphDefinition, boolean)
*/
public Component getRendererComponent(GlyphDefinition gd, boolean isSelected) {
ch = gd.getMappedChars();
fontName = gd.getDataSource().getFontName();
factor = gd.getDataSource().getSizeFactor();
configureBackground(isSelected);
return this;
}
/* (non-Javadoc)
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (ch != null && fontName != null) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawText(g2, ch, fontName);
}
}
/**
* Draws a glyph to the component.
*
* @param g2 the graphic context
* @param text the text
* @param fontName the font name
*/
private void drawText(Graphics2D g2, String text, String fontName) {
int fontSize = Math.round(getHeight() * factor);
Font baseFont = new Font(fontName, Font.PLAIN, fontSize);
Font font = baseFont.deriveFont(attr);
GlyphVector gv = font.createGlyphVector(frc, text);
Rectangle pixelBounds = gv.getPixelBounds(frc, 0, 0);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
float offsetX = pixelBounds.x + (pixelBounds.width / 2);
float offsetY = pixelBounds.y + (pixelBounds.height / 2);
AffineTransform at = new AffineTransform();
at.translate(centerX - offsetX, centerY - offsetY);
Shape outline = gv.getOutline();
outline = at.createTransformedShape(outline);
g2.fill(outline);
}
} |
923300ddfa60796b14aded63d9bf1a81d136b1e0 | 1,416 | java | Java | src/main/java/io/github/henryssondaniel/teacup/protocol/http/node/UriSetter.java | HenryssonDaniel/teacup-java-protocol-http | 6efb9ddf10d4fc69c315ac01f40ee24098b08612 | [
"MIT"
] | null | null | null | src/main/java/io/github/henryssondaniel/teacup/protocol/http/node/UriSetter.java | HenryssonDaniel/teacup-java-protocol-http | 6efb9ddf10d4fc69c315ac01f40ee24098b08612 | [
"MIT"
] | null | null | null | src/main/java/io/github/henryssondaniel/teacup/protocol/http/node/UriSetter.java | HenryssonDaniel/teacup-java-protocol-http | 6efb9ddf10d4fc69c315ac01f40ee24098b08612 | [
"MIT"
] | null | null | null | 32.181818 | 78 | 0.806497 | 996,432 | package io.github.henryssondaniel.teacup.protocol.http.node;
import io.github.henryssondaniel.teacup.core.assertion.GenericBooleanAssert;
import io.github.henryssondaniel.teacup.core.assertion.GenericIntegerAssert;
import io.github.henryssondaniel.teacup.core.assertion.GenericObjectAssert;
import io.github.henryssondaniel.teacup.core.assertion.GenericStringAssert;
import java.net.URI;
interface UriSetter extends Setter<URI, GenericObjectAssert<URI, ?>>, Uri {
void setAbsolute(GenericBooleanAssert<?> absolute);
void setAuthority(GenericStringAssert<?> authority);
void setFragment(GenericStringAssert<?> fragment);
void setHost(GenericStringAssert<?> host);
void setOpaque(GenericBooleanAssert<?> opaque);
void setPath(GenericStringAssert<?> path);
void setPort(GenericIntegerAssert<?> port);
void setQuery(GenericStringAssert<?> query);
void setRawAuthority(GenericStringAssert<?> rawAuthority);
void setRawFragment(GenericStringAssert<?> rawFragment);
void setRawPath(GenericStringAssert<?> rawPath);
void setRawQuery(GenericStringAssert<?> rawQuery);
void setRawSchemeSpecificPart(GenericStringAssert<?> rawSchemeSpecificPart);
void setRawUserInfo(GenericStringAssert<?> rawUserInfo);
void setScheme(GenericStringAssert<?> scheme);
void setSchemeSpecificPart(GenericStringAssert<?> schemeSpecificPart);
void setUserInfo(GenericStringAssert<?> userInfo);
}
|
923302fbc1fa4ac6e60d5f815f825d31c312585d | 1,614 | java | Java | spring-integration-core/src/test/java/org/springframework/integration/gateway/TestChannelInterceptor.java | KyeongMoon/spring-integration | fa060900b0434627c4a520a2ae84a7a20dae735f | [
"Apache-2.0"
] | 1,093 | 2015-01-01T15:28:50.000Z | 2022-03-29T18:30:56.000Z | spring-integration-core/src/test/java/org/springframework/integration/gateway/TestChannelInterceptor.java | KyeongMoon/spring-integration | fa060900b0434627c4a520a2ae84a7a20dae735f | [
"Apache-2.0"
] | 1,920 | 2015-01-05T12:16:48.000Z | 2022-03-31T16:58:41.000Z | spring-integration-core/src/test/java/org/springframework/integration/gateway/TestChannelInterceptor.java | KyeongMoon/spring-integration | fa060900b0434627c4a520a2ae84a7a20dae735f | [
"Apache-2.0"
] | 922 | 2015-01-05T05:10:05.000Z | 2022-03-30T21:06:32.000Z | 26.9 | 81 | 0.752169 | 996,433 | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.gateway;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;
/**
* @author Mark Fisher
* @author Gary Russell
*/
public class TestChannelInterceptor implements ChannelInterceptor {
private final AtomicInteger sentCount = new AtomicInteger();
private final AtomicInteger receivedCount = new AtomicInteger();
public int getSentCount() {
return this.sentCount.get();
}
public int getReceivedCount() {
return this.receivedCount.get();
}
@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
if (sent) {
this.sentCount.incrementAndGet();
}
}
@Override
public Message<?> postReceive(Message<?> message, MessageChannel channel) {
if (message != null) {
this.receivedCount.incrementAndGet();
}
return message;
}
}
|
923303079e1da0ae7efc42fb53266c1a09662637 | 4,926 | java | Java | drools-compiler/src/test/java/org/drools/compiler/oopath/OOPathCastTest.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 5 | 2016-07-31T17:00:18.000Z | 2022-01-11T04:34:29.000Z | drools-compiler/src/test/java/org/drools/compiler/oopath/OOPathCastTest.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 4 | 2019-08-15T11:38:50.000Z | 2021-03-02T09:01:40.000Z | drools-compiler/src/test/java/org/drools/compiler/oopath/OOPathCastTest.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 1 | 2021-08-08T03:36:42.000Z | 2021-08-08T03:36:42.000Z | 36.488889 | 129 | 0.573894 | 996,434 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.compiler.oopath;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.drools.compiler.oopath.model.BabyBoy;
import org.drools.compiler.oopath.model.BabyGirl;
import org.drools.compiler.oopath.model.Man;
import org.drools.compiler.oopath.model.Toy;
import org.drools.compiler.oopath.model.Woman;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import static org.junit.Assert.assertTrue;
public class OOPathCastTest {
@Test
public void testInlineCast() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Man( $toy: /wife/children#BabyGirl/toys )\n" +
"then\n" +
" list.add( $toy.getName() );\n" +
"end\n";
final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
.build()
.newKieSession();
final List<String> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Woman alice = new Woman( "Alice", 38 );
final Man bob = new Man( "Bob", 40 );
bob.setWife( alice );
final BabyBoy charlie = new BabyBoy( "Charles", 12 );
final BabyGirl debbie = new BabyGirl( "Debbie", 8 );
alice.addChild( charlie );
alice.addChild( debbie );
charlie.addToy( new Toy( "car" ) );
charlie.addToy( new Toy( "ball" ) );
debbie.addToy( new Toy( "doll" ) );
ksession.insert( bob );
ksession.fireAllRules();
Assertions.assertThat(list).containsExactlyInAnyOrder("doll");
}
@Test
public void testInvalidCast() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Man( $toy: /wife/children#Man/toys )\n" +
"then\n" +
" list.add( $toy.getName() );\n" +
"end\n";
final KieServices ks = KieServices.Factory.get();
final KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
final Results results = ks.newKieBuilder( kfs ).buildAll().getResults();
assertTrue( results.hasMessages( Message.Level.ERROR ) );
}
@Test
public void testInlineCastWithConstraint() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Man( name == \"Bob\", $name: /wife/children#BabyGirl[ favoriteDollName.startsWith(\"A\") ].name )\n" +
"then\n" +
" list.add( $name );\n" +
"end\n";
final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
.build()
.newKieSession();
final List<String> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Woman alice = new Woman( "Alice", 38 );
final Man bob = new Man( "Bob", 40 );
bob.setWife( alice );
final BabyBoy charlie = new BabyBoy( "Charles", 12 );
final BabyGirl debbie = new BabyGirl( "Debbie", 8, "Anna" );
final BabyGirl elisabeth = new BabyGirl( "Elisabeth", 5, "Zoe" );
final BabyGirl farrah = new BabyGirl( "Farrah", 3, "Agatha" );
alice.addChild( charlie );
alice.addChild( debbie );
alice.addChild( elisabeth );
alice.addChild( farrah );
ksession.insert( bob );
ksession.fireAllRules();
Assertions.assertThat(list).containsExactlyInAnyOrder("Debbie", "Farrah");
}
}
|
92330353280b45448eba26f3d4460b10c2627a47 | 1,357 | java | Java | src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java | MrDoritos/BetterQuesting | 89120612117f71ae884f067ec18a74451cd7c313 | [
"MIT"
] | 75 | 2015-12-15T23:13:43.000Z | 2020-10-30T10:49:14.000Z | src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java | MrDoritos/BetterQuesting | 89120612117f71ae884f067ec18a74451cd7c313 | [
"MIT"
] | 735 | 2015-12-16T05:55:39.000Z | 2022-03-31T11:31:05.000Z | src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java | MrDoritos/BetterQuesting | 89120612117f71ae884f067ec18a74451cd7c313 | [
"MIT"
] | 72 | 2016-02-03T13:40:12.000Z | 2022-02-02T22:25:15.000Z | 20.253731 | 102 | 0.544584 | 996,435 | package betterquesting.api2.client.gui.resources.colors;
import net.minecraft.client.renderer.GlStateManager;
import java.awt.*;
public class GuiColorStatic implements IGuiColor
{
private final int argb;
public GuiColorStatic(int color)
{
this.argb = color;
}
public GuiColorStatic(int red, int green, int blue, int alpha)
{
this.argb = ((alpha & 255) << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255);
}
public GuiColorStatic(float red, float green, float blue, float alpha)
{
this((int)(red * 255), (int)(green * 255), (int)(blue * 255), (int)(alpha * 255));
}
public GuiColorStatic(Color color)
{
this(color.getRGB());
}
@Override
public int getRGB()
{
return argb;
}
@Override
public float getRed()
{
return (argb >> 16 & 255) / 255F;
}
@Override
public float getGreen()
{
return (argb >> 8 & 255) / 255F;
}
@Override
public float getBlue()
{
return (argb & 255) / 255F;
}
@Override
public float getAlpha()
{
return (argb >> 24 & 255) / 255F;
}
@Override
public void applyGlColor()
{
GlStateManager.color(getRed(), getGreen(), getBlue(), getAlpha());
}
}
|
92330383af44c2012b537d149d918278ee40c127 | 68,042 | java | Java | src/impl/jena/OWLModelImpl.java | chachi21/owl-s | 198d268a8ce33dcd588a7b0a824df2a6ad9b5aa9 | [
"MIT"
] | 1 | 2015-10-16T12:07:46.000Z | 2015-10-16T12:07:46.000Z | src/impl/jena/OWLModelImpl.java | TinyTinyAn/owl-s | 198d268a8ce33dcd588a7b0a824df2a6ad9b5aa9 | [
"MIT"
] | null | null | null | src/impl/jena/OWLModelImpl.java | TinyTinyAn/owl-s | 198d268a8ce33dcd588a7b0a824df2a6ad9b5aa9 | [
"MIT"
] | null | null | null | 40.573643 | 147 | 0.626613 | 996,436 | /*
* Created on Dec 16, 2004
*/
package impl.jena;
import impl.owl.XSDDataTypes;
import impl.owl.list.RDFListImpl;
import impl.owls.generic.expression.SWRLExpressionImpl;
import impl.owls.generic.list.OWLSObjListImpl;
import impl.owls.grounding.GroundingImpl;
import impl.owls.grounding.JavaAtomicGroundingImpl;
import impl.owls.grounding.UPnPAtomicGroundingImpl;
import impl.owls.grounding.UPnPMessageMapImpl;
import impl.owls.grounding.WSDLAtomicGroundingImpl;
import impl.owls.grounding.WSDLMessageMapImpl;
import impl.owls.grounding.WSDLOperationRefImpl;
import impl.owls.process.AtomicProcessImpl;
import impl.owls.process.CompositeProcessImpl;
import impl.owls.process.ResultImpl;
import impl.owls.process.ValueDataImpl;
import impl.owls.process.ValueOfImpl;
import impl.owls.process.binding.InputBindingImpl;
import impl.owls.process.binding.OutputBindingImpl;
import impl.owls.process.constructs.AnyOrderImpl;
import impl.owls.process.constructs.ChoiceImpl;
import impl.owls.process.constructs.ForEachImpl;
import impl.owls.process.constructs.IfThenElseImpl;
import impl.owls.process.constructs.PerformImpl;
import impl.owls.process.constructs.ProduceImpl;
import impl.owls.process.constructs.RepeatUntilImpl;
import impl.owls.process.constructs.RepeatWhileImpl;
import impl.owls.process.constructs.SequenceImpl;
import impl.owls.process.constructs.SplitImpl;
import impl.owls.process.constructs.SplitJoinImpl;
import impl.owls.process.parameter.InputImpl;
import impl.owls.process.parameter.LocalImpl;
import impl.owls.process.parameter.OutputImpl;
import impl.owls.profile.ProfileImpl;
import impl.owls.profile.ServiceParameterImpl;
import impl.owls.service.ServiceImpl;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mindswap.exceptions.LockNotSupportedException;
import org.mindswap.exceptions.NotImplementedException;
import org.mindswap.exceptions.UnboundVariableException;
import org.mindswap.owl.OWLClass;
import org.mindswap.owl.OWLConfig;
import org.mindswap.owl.OWLDataProperty;
import org.mindswap.owl.OWLDataType;
import org.mindswap.owl.OWLDataValue;
import org.mindswap.owl.OWLDataValueList;
import org.mindswap.owl.OWLEntity;
import org.mindswap.owl.OWLFactory;
import org.mindswap.owl.OWLIndividual;
import org.mindswap.owl.OWLIndividualList;
import org.mindswap.owl.OWLModel;
import org.mindswap.owl.OWLObject;
import org.mindswap.owl.OWLObjectProperty;
import org.mindswap.owl.OWLOntology;
import org.mindswap.owl.OWLProperty;
import org.mindswap.owl.OWLType;
import org.mindswap.owl.OWLValue;
import org.mindswap.owl.OWLWriter;
import org.mindswap.owl.list.ListVocabulary;
import org.mindswap.owl.list.RDFList;
import org.mindswap.owl.vocabulary.SWRL;
import org.mindswap.owl.vocabulary.SWRLB;
import org.mindswap.owls.OWLSFactory;
import org.mindswap.owls.generic.expression.Expression;
import org.mindswap.owls.generic.list.OWLSObjList;
import org.mindswap.owls.grounding.Grounding;
import org.mindswap.owls.grounding.JavaAtomicGrounding;
import org.mindswap.owls.grounding.MessageMap;
import org.mindswap.owls.grounding.UPnPAtomicGrounding;
import org.mindswap.owls.grounding.WSDLAtomicGrounding;
import org.mindswap.owls.grounding.WSDLOperationRef;
import org.mindswap.owls.process.AnyOrder;
import org.mindswap.owls.process.AtomicProcess;
import org.mindswap.owls.process.Choice;
import org.mindswap.owls.process.CompositeProcess;
import org.mindswap.owls.process.Condition;
import org.mindswap.owls.process.ControlConstruct;
import org.mindswap.owls.process.ControlConstructBag;
import org.mindswap.owls.process.ControlConstructList;
import org.mindswap.owls.process.ForEach;
import org.mindswap.owls.process.IfThenElse;
import org.mindswap.owls.process.Input;
import org.mindswap.owls.process.InputBinding;
import org.mindswap.owls.process.Local;
import org.mindswap.owls.process.Output;
import org.mindswap.owls.process.OutputBinding;
import org.mindswap.owls.process.Perform;
import org.mindswap.owls.process.Process;
import org.mindswap.owls.process.Produce;
import org.mindswap.owls.process.RepeatUntil;
import org.mindswap.owls.process.RepeatWhile;
import org.mindswap.owls.process.Result;
import org.mindswap.owls.process.Sequence;
import org.mindswap.owls.process.SimpleProcess;
import org.mindswap.owls.process.Split;
import org.mindswap.owls.process.SplitJoin;
import org.mindswap.owls.process.ValueData;
import org.mindswap.owls.process.ValueOf;
import org.mindswap.owls.profile.Profile;
import org.mindswap.owls.profile.ServiceParameter;
import org.mindswap.owls.service.Service;
import org.mindswap.owls.vocabulary.FLAServiceOnt;
import org.mindswap.owls.vocabulary.MoreGroundings;
import org.mindswap.owls.vocabulary.OWLS;
import org.mindswap.pellet.jena.PelletInfGraph;
import org.mindswap.pellet.jena.PelletReasoner;
import org.mindswap.query.ABoxQuery;
import org.mindswap.query.ValueMap;
import org.mindswap.swrl.Atom;
import org.mindswap.swrl.AtomList;
import org.mindswap.swrl.BuiltinAtom;
import org.mindswap.swrl.ClassAtom;
import org.mindswap.swrl.DataPropertyAtom;
import org.mindswap.swrl.DifferentIndividualsAtom;
import org.mindswap.swrl.IndividualPropertyAtom;
import org.mindswap.swrl.SWRLObject;
import org.mindswap.swrl.SameIndividualAtom;
import org.mindswap.swrl.Variable;
import org.mindswap.utils.URIUtils;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntDocumentManager;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.core.Binding0;
import com.hp.hpl.jena.query.core.Constraint;
import com.hp.hpl.jena.query.core.ElementFilter;
import com.hp.hpl.jena.query.core.ElementGroup;
import com.hp.hpl.jena.query.core.ResultBinding;
import com.hp.hpl.jena.query.engine1.ExecutionContext;
import com.hp.hpl.jena.query.expr.E_Add;
import com.hp.hpl.jena.query.expr.E_Equal;
import com.hp.hpl.jena.query.expr.E_GreaterThan;
import com.hp.hpl.jena.query.expr.E_GreaterThanOrEqual;
import com.hp.hpl.jena.query.expr.E_LessThan;
import com.hp.hpl.jena.query.expr.E_NotEqual;
import com.hp.hpl.jena.query.expr.E_Subtract;
import com.hp.hpl.jena.query.expr.Expr;
import com.hp.hpl.jena.query.expr.NodeValue;
import com.hp.hpl.jena.query.expr.NodeVar;
import com.hp.hpl.jena.query.util.Utils;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.reasoner.Reasoner;
import com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.util.iterator.Map1;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.vocabulary.ReasonerVocabulary;
/**
* @author Evren Sirin
*/
public abstract class OWLModelImpl implements OWLModel, org.mindswap.owls.OWLSModel {
protected OntModel ontModel;
private OntModelSpec spec;
protected Reasoner reasoner;
protected OWLOntology baseOntology;
protected OWLWriter writer;
public OWLModelImpl(Model model) {
spec = new OntModelSpec( OntModelSpec.OWL_MEM );
OntDocumentManager docManager = new OntDocumentManager();
docManager.setProcessImports( false );
spec.setDocumentManager( docManager );
ontModel = ModelFactory.createOntologyModel( spec, model );
}
public Object getImplementation() {
return ontModel;
}
public OntModel getOntModel() {
return ontModel;
}
public void prepare() {
ontModel.prepare();
}
public void classify() {
if(reasoner instanceof PelletReasoner) {
((PelletInfGraph)ontModel.getGraph()).classify();
}
}
public boolean isClassified() {
if(reasoner instanceof PelletReasoner) {
return ((PelletInfGraph)ontModel.getGraph()).isClassified();
}
return true;
}
public boolean isConsistent() {
if(reasoner instanceof PelletReasoner) {
return ((PelletInfGraph)ontModel.getGraph()).isConsistent();
}
return true;
// ValidityReport validation = ontModel.validate();
//
// // if there is no validation report assume everything is fine
// return ( validation == null ) || validation.isValid();
}
public void setBaseOntology(OWLOntology ontology) {
this.baseOntology = ontology;
}
public OWLOntology getBaseOntology() {
return baseOntology;
}
// public void enableReasoner(boolean enabled) {
// if(reasoner == null)
// throw new IllegalArgumentException(
// "There is no reasoner attached to enable/disable. First attach a reasoner using setReasoner function!");
// }
public void setReasoner(Reasoner reasoner) {
this.reasoner = reasoner;
spec.setReasoner(reasoner);
List subGraphs = ontModel.getSubGraphs();
Model baseModel = ontModel.getBaseModel();
ontModel = ModelFactory.createOntologyModel( spec, baseModel );
for(Iterator i = subGraphs.iterator(); i.hasNext();) {
Graph graph = (Graph) i.next();
Model wrap = ModelFactory.createModelForGraph( graph );
ontModel.addSubModel( wrap, false );
}
ontModel.rebind();
}
public void setReasoner(String reasonerName) {
Reasoner reasoner = (Reasoner) OWLFactory.getReasoner(reasonerName);
if(reasonerName != null && reasoner == null)
throw new IllegalArgumentException(
"Reasoner named " + reasonerName + " is not found!");
setReasoner(reasoner);
}
public void setReasoner(Object reasoner) {
if(reasoner instanceof Reasoner || reasoner == null)
setReasoner((Reasoner) reasoner);
else
throw new IllegalArgumentException(
"Jena implementation only supports reasoners that implements the " + Reasoner.class);
}
public Object getReasoner() {
return reasoner;
}
public OWLSObjList createList() {
ListVocabulary vocabulary = OWLS.ObjList;
// TODO cache nil list
OWLIndividual nil = createIndividual( vocabulary.nil().getURI() );
OWLSObjListImpl list = new OWLSObjListImpl( nil );
list.setVocabulary( vocabulary );
return list;
}
public OWLSObjList createList(OWLIndividual item) {
OWLSObjList list = createList();
list = (OWLSObjList) list.insert( item );
return list;
}
public OWLSObjList createList(OWLIndividualList items) {
OWLSObjList list = createList();
for( int i = items.size(); i >= 0; i++ )
list = (OWLSObjList) list.insert( items.individualAt( i ) );
return list;
}
public RDFList createList(ListVocabulary vocabulary) {
// TODO cache nil list
OWLIndividual nil = createIndividual( vocabulary.nil().getURI() );
RDFListImpl list = new RDFListImpl( nil );
list.setVocabulary( vocabulary );
return list;
}
public RDFList createList(ListVocabulary vocabulary, OWLIndividual item) {
RDFList list = createList( vocabulary );
list = list.insert( item );
return list;
}
public RDFList createList(ListVocabulary vocabulary, OWLIndividualList items) {
RDFList list = createList( vocabulary );
for( int i = items.size(); i >= 0; i++ )
list = list.insert( items.individualAt( i ) );
return list;
}
protected Resource asResource(URI uri) {
return ontModel.getResource(uri.toString());
}
protected boolean containsResource(Resource r) {
return ontModel.containsResource(r);
}
protected Property asProperty(URI uri) {
return ontModel.getProperty(uri.toString());
}
public OWLType getType(URI uri) {
OWLType type = getDataType(uri);
if(type == null)
type = getClass(uri);
return type;
}
public OWLDataType getDataType(URI uri) {
return XSDDataTypes.getDataType(uri);
}
public OWLObject getObject(URI uri) {
OWLObject entity = null;
if(entity == null) entity = getClass(uri);
if(entity == null) entity = getObjectProperty(uri);
if(entity == null) entity = getDataProperty(uri);
if(entity == null) entity = getDataType(uri);
if(entity == null) entity = getIndividual(uri);
return entity;
}
public OWLEntity getEntity(URI uri) {
OWLEntity entity = null;
if(entity == null) entity = getClass(uri);
if(entity == null) entity = getObjectProperty(uri);
if(entity == null) entity = getDataProperty(uri);
if(entity == null) entity = getIndividual(uri);
return entity;
}
public OWLClass getClass(URI uri) {
return getClass(asResource(uri));
}
public OWLClass getClass(Resource res) {
OWLClass c = null;
if(res.canAs(OntClass.class)) {
c = wrapClass(res, null);
}
return c;
}
public OWLIndividual getIndividual(URI uri) {
Resource res = ontModel.getIndividual(uri.toString());
return (res == null) ? null : wrapIndividual(res, null);
}
public OWLIndividualList getIndividuals() {
return getAllIndividuals( ontModel.listSubjects(), null );
}
public OWLProperty getProperty(URI uri) {
OWLProperty prop = getObjectProperty(uri);
if(prop == null)
prop = getDataProperty(uri);
return prop;
}
public OWLObjectProperty getObjectProperty(URI uri) {
OWLObjectProperty p = null;
Property prop = asProperty(uri);
if(ontModel.contains(prop, RDF.type, OWL.ObjectProperty)) {
p = wrapObjectProperty(prop, null);
}
return p;
}
public OWLDataProperty getDataProperty(URI uri) {
OWLDataProperty p = null;
Property prop = asProperty(uri);
if(ontModel.contains(prop, RDF.type, OWL.DatatypeProperty)) {
p = wrapDataProperty(prop, null);
}
return p;
}
public boolean isSameAs(OWLIndividual ind1, OWLIndividual ind2) {
return ontModel.contains(
(Resource) ind1.getImplementation(),
OWL.sameAs,
(Resource) ind2.getImplementation());
}
public OWLIndividualList getSameIndividuals(OWLIndividual ind) {
return getAllIndividuals(
ontModel.listSubjectsWithProperty(
OWL.sameAs,
(Resource) ind.getImplementation()),
ind.getOntology());
}
public boolean isDifferentFrom(OWLIndividual ind1, OWLIndividual ind2) {
return ontModel.contains(
(Resource) ind1.getImplementation(),
OWL.differentFrom,
(Resource) ind2.getImplementation());
}
public OWLIndividualList getDifferentIndividuals(OWLIndividual ind) {
return getAllIndividuals(
ontModel.listSubjectsWithProperty(
OWL.differentFrom,
(Resource) ind.getImplementation()),
ind.getOntology());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#isSubClassOf(org.mindswap.owl.OWLClass, org.mindswap.owl.OWLClass)
*/
public boolean isSubClassOf(OWLClass c1, OWLClass c2) {
return ontModel.contains(
(Resource) c1.getImplementation(),
RDFS.subClassOf,
(Resource) c2.getImplementation());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#isDisjoint(org.mindswap.owl.OWLClass, org.mindswap.owl.OWLClass)
*/
public boolean isDisjoint(OWLClass c1, OWLClass c2) {
return ontModel.contains(
(Resource) c1.getImplementation(),
OWL.disjointWith,
(Resource) c2.getImplementation());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#isEquivalent(org.mindswap.owl.OWLType, org.mindswap.owl.OWLType)
*/
public boolean isEquivalent(OWLType t1, OWLType t2) {
if(t1.equals(t2))
return true;
if(t1 instanceof OWLClass && t2 instanceof OWLClass) {
return ontModel.contains(
(Resource) t1.getImplementation(),
OWL.equivalentClass,
(Resource) t2.getImplementation());
}
// FIXME datatype equivalance
if(t1 instanceof OWLDataType && t2 instanceof OWLDataType)
return t1.equals(t2);
return false;
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#isDisjoint(org.mindswap.owl.OWLType, org.mindswap.owl.OWLType)
*/
public boolean isDisjoint(OWLType t1, OWLType t2) {
if(t1 instanceof OWLClass && t2 instanceof OWLClass)
return isDisjoint((OWLClass) t1, (OWLClass) t2);
// FIXME datatype disjointness
if(t1 instanceof OWLDataType && t2 instanceof OWLDataType)
return !isEquivalent(t1, t2);
return true;
}
public Set getSubClasses(OWLClass c) {
return getSubClasses(c, false);
}
public Set getSubClasses(OWLClass c, boolean direct) {
Property subClassOf = direct
? ReasonerVocabulary.directSubClassOf
: RDFS.subClassOf;
return getAllClasses(
ontModel.listSubjectsWithProperty(
subClassOf,
(Resource) c.getImplementation()),
c.getOntology());
}
public Set getSubProperties(OWLProperty p) {
if(p instanceof OWLObjectProperty) {
return getAllObjectProperties(
ontModel.listSubjectsWithProperty(
RDFS.subPropertyOf,
(Resource) p.getImplementation()),
p.getOntology());
}
else {
return getAllDataProperties(
ontModel.listSubjectsWithProperty(
RDFS.subPropertyOf,
(Resource) p.getImplementation()),
p.getOntology());
}
}
public Set getEquivalentProperties(OWLProperty p) {
if(p instanceof OWLObjectProperty) {
return getAllObjectProperties(
ontModel.listSubjectsWithProperty(
OWL.equivalentClass,
(Resource) p.getImplementation()),
p.getOntology());
}
else {
return getAllDataProperties(
ontModel.listSubjectsWithProperty(
OWL.equivalentClass,
(Resource) p.getImplementation()),
p.getOntology());
}
}
public Set getSuperProperties(OWLProperty p) {
if(p instanceof OWLObjectProperty) {
return getAllObjectProperties(
ontModel.listObjectsOfProperty(
(Resource) p.getImplementation(),
RDFS.subPropertyOf),
p.getOntology());
}
else {
return getAllDataProperties(
ontModel.listObjectsOfProperty(
(Resource) p.getImplementation(),
RDFS.subPropertyOf),
p.getOntology());
}
}
public Set getSuperClasses(OWLClass c) {
return getSuperClasses(c, false);
}
public Set getSuperClasses(OWLClass c, boolean direct) {
Property subClassOf = direct
? ReasonerVocabulary.directSubClassOf
: RDFS.subClassOf;
return getAllClasses(
ontModel.listObjectsOfProperty(
(Resource) c.getImplementation(),
subClassOf),
c.getOntology());
}
public Set getEquivalentClasses(OWLClass c) {
return getAllClasses(
ontModel.listSubjectsWithProperty(
OWL.equivalentClass,
(Resource) c.getImplementation()),
c.getOntology());
}
public OWLIndividualList getInstances(OWLClass c) {
return getAllIndividuals(
ontModel.listSubjectsWithProperty(
RDF.type,
(Resource) c.getImplementation()),
c.getOntology());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getTypes(org.mindswap.owl.OWLIndividual)
*/
public Set getTypes(OWLIndividual ind) {
return getAllClasses(
ontModel.listObjectsOfProperty(
(Resource) ind.getImplementation(),
RDF.type),
ind.getOntology());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getProperty(org.mindswap.owl.OWLIndividual, org.mindswap.owl.OWLObjectProperty)
*/
public OWLIndividual getProperty(OWLIndividual ind, OWLObjectProperty prop) {
return getFirstIndividual(
ontModel.listObjectsOfProperty(
(Resource) ind.getImplementation(),
(Property) prop.getImplementation()),
ind.getOntology());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getProperties(org.mindswap.owl.OWLIndividual, org.mindswap.owl.OWLObjectProperty)
*/
public OWLIndividualList getProperties(OWLIndividual ind, OWLObjectProperty prop) {
return getAllIndividuals(
ontModel.listObjectsOfProperty(
(Resource) ind.getImplementation(),
(Property) prop.getImplementation()),
ind.getOntology());
}
final public static List SKIP_PROPS = Arrays.asList(new Property[] {
RDF.type, RDFS.subClassOf,
ReasonerVocabulary.directSubClassOf,
ReasonerVocabulary.directSubPropertyOf,
ReasonerVocabulary.directRDFType,
OWL.hasValue, OWL.allValuesFrom, OWL.someValuesFrom,
OWL.minCardinality, OWL.maxCardinality, OWL.cardinality });
private Map getProperties(Resource resource, OWLOntology ontology) {
Map result = new HashMap();
Iterator i = ontModel.listStatements(
resource,
null,
(RDFNode) null);
while(i.hasNext()) {
Statement stmt = (Statement) i.next();
Property pred = stmt.getPredicate();
if(SKIP_PROPS.contains(pred))
continue;
// OWLProperty prop = getProperty(URI.create(pred.getURI()));
// if(prop != null) {
// if(prop instanceof OWLObjectProperty) {
// OWLIndividualList list = (OWLIndividualList) result.get(prop);
// if(list == null) {
// list = OWLFactory.createIndividualList();
// result.put(prop, list);
// }
// list.add(OWLModelImpl.this.wrapIndividual(stmt.getResource()));
// }
// else {
// OWLIndividualList list = (OWLIndividualList) result.get(prop);
// if(list == null) {
// list = OWLFactory.createIndividualList();
// result.put(prop, list);
// }
// list.add(OWLModelImpl.this.wrapDataValue(stmt.getLiteral()));
// }
// }
RDFNode value = stmt.getObject();
if(value instanceof Resource) {
OWLObjectProperty prop = baseOntology.createObjectProperty(URI.create(pred.getURI()));
OWLIndividualList list = (OWLIndividualList) result.get(prop);
if(list == null) {
list = OWLFactory.createIndividualList();
result.put(prop, list);
}
list.add(OWLModelImpl.this.wrapIndividual(stmt.getResource(), ontology));
}
else {
OWLDataProperty prop = baseOntology.createDataProperty(URI.create(pred.getURI()));
OWLDataValueList list = (OWLDataValueList) result.get(prop);
if(list == null) {
list = OWLFactory.createDataValueList();
result.put(prop, list);
}
list.add(OWLModelImpl.this.wrapDataValue(stmt.getLiteral(), ontology));
}
}
return result;
}
public List getDeclaredProperties(OWLClass claz) {
return getDeclaredProperties(claz, true);
}
public List getDeclaredProperties(OWLClass claz, boolean direct) {
List result = OWLFactory.createIndividualList();
OntResource ontRes = ontModel.getOntResource((Resource) claz.getImplementation());
OntClass ontClaz = ontRes.asClass();
ExtendedIterator i = ontClaz.listDeclaredProperties(direct);
while(i.hasNext()) {
OntProperty ontProp = (OntProperty) i.next();
if(SKIP_PROPS.contains(ontProp))
continue;
if (ontProp.isDatatypeProperty()) {
OWLDataProperty prop = baseOntology.createDataProperty(URI.create(ontProp.getURI()));
result.add(prop);
} else {
OWLObjectProperty prop = baseOntology.createObjectProperty(URI.create(ontProp.getURI()));
result.add(prop);
}
}
return result;
}
public Map getProperties(OWLClass claz) {
return getProperties((Resource) claz.getImplementation(), claz.getOntology());
}
public Map getProperties(OWLIndividual ind) {
return getProperties((Resource) ind.getImplementation(), ind.getOntology());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getProperty(org.mindswap.owl.OWLIndividual, org.mindswap.owl.OWLDataProperty)
*/
public OWLDataValue getProperty(OWLIndividual ind, OWLDataProperty prop) {
OWLDataValue result = null;
int maxPriority = -1;
OWLDataValueList list = getAllDataValues(
ontModel.listObjectsOfProperty(
(Resource) ind.getImplementation(),
(Property) prop.getImplementation()),
ind.getOntology());
for(int i = 0; i < list.size(); i++) {
OWLDataValue value = list.valueAt(i);
int priority = OWLConfig.DEFAULT_LANG_LIST.indexOf(value.getLanguage());
if(priority == 0)
return value;
else if(priority > maxPriority) {
result = value;
maxPriority = priority;
}
}
return result;
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getProperty(org.mindswap.owl.OWLIndividual, org.mindswap.owl.OWLDataProperty, java.lang.String)
*/
public OWLDataValue getProperty(OWLIndividual ind, OWLDataProperty prop, String lang) {
OWLDataValueList list = getAllDataValues(
ontModel.listObjectsOfProperty(
(Resource) ind.getImplementation(),
(Property) prop.getImplementation()),
ind.getOntology());
for(int i = 0; i < list.size(); i++) {
OWLDataValue value = list.valueAt(i);
if(lang == null || value.getLanguage().equals(lang))
return value;
}
return null;
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getProperties(org.mindswap.owl.OWLIndividual, org.mindswap.owl.OWLDataProperty)
*/
public OWLDataValueList getProperties(OWLIndividual ind, OWLDataProperty prop) {
return getAllDataValues(
ontModel.listObjectsOfProperty(
(Resource) ind.getImplementation(),
(Property) prop.getImplementation()),
ind.getOntology());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getIncomingProperty(org.mindswap.owl.OWLObjectProperty, org.mindswap.owl.OWLIndividual)
*/
public OWLIndividual getIncomingProperty(OWLObjectProperty prop, OWLIndividual ind) {
return getFirstIndividual(
ontModel.listSubjectsWithProperty(
(Property) prop.getImplementation(),
(Resource) ind.getImplementation()),
ind.getOntology());
}
public OWLIndividualList getIncomingProperties(OWLObjectProperty prop, OWLIndividual ind) {
return getAllIndividuals(
ontModel.listSubjectsWithProperty(
(Property) prop.getImplementation(),
(Resource) ind.getImplementation()),
ind.getOntology());
}
public OWLIndividualList getIncomingProperties(OWLIndividual ind) {
return getAllIndividuals(
ontModel.listStatements(
null,
null,
(Resource) ind.getImplementation()).mapWith(
new Map1(){
public Object map1(Object o) { return ((Statement) o).getSubject(); }
}),
ind.getOntology());
}
public OWLIndividual getIncomingProperty(OWLDataProperty prop, OWLDataValue value) {
return getFirstIndividual(
ontModel.listSubjectsWithProperty(
(Property) prop.getImplementation(),
(Literal) value.getImplementation()), prop.getOntology());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getIncomingProperties(org.mindswap.owl.OWLDataProperty, org.mindswap.owl.OWLIndividual)
*/
public OWLIndividualList getIncomingProperties(OWLDataProperty prop, OWLDataValue value) {
return getAllIndividuals(
ontModel.listSubjectsWithProperty(
(Property) prop.getImplementation(),
(Literal) value.getImplementation()), prop.getOntology());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#hasProperty(org.mindswap.owl.OWLIndividual, org.mindswap.owl.OWLProperty)
*/
public boolean hasProperty(OWLIndividual ind, OWLProperty prop) {
return ontModel.contains(
(Resource) ind.getImplementation(),
(Property) prop.getImplementation(),
(RDFNode) null);
}
public boolean hasProperty(OWLIndividual ind, OWLProperty prop, OWLValue value) {
return ontModel.contains(
(Resource) ind.getImplementation(),
(Property) prop.getImplementation(),
(RDFNode) value.getImplementation());
}
/* (non-Javadoc)
* @see org.mindswap.owl.OWLModel#getType(org.mindswap.owl.OWLIndividual)
*/
public OWLClass getType(OWLIndividual ind) {
Resource res = (Resource) ind.getImplementation();
res = (Resource) res.inModel(ontModel);
OntResource ontR = (OntResource) res.as(OntResource.class);
Resource type = ontR.getRDFType(true);
return (type == null) ? null : OWLModelImpl.this.wrapClass(type, ind.getOntology());
}
public boolean isType(OWLIndividual ind, OWLClass c) {
return ontModel.contains(
(Resource) ind.getImplementation(),
RDF.type,
(Resource) c.getImplementation());
}
public boolean isEnumerated(OWLClass c) {
return ontModel.contains(
(Resource) c.getImplementation(),
OWL.oneOf,
(Resource) null);
}
public OWLIndividualList getEnumerations(OWLClass c) {
Statement stmt =
ontModel.getProperty(
(Resource) c.getImplementation(),
OWL.oneOf);
if(stmt == null)
return null;
com.hp.hpl.jena.rdf.model.RDFList oneOf =
(com.hp.hpl.jena.rdf.model.RDFList)
stmt.getResource().as(com.hp.hpl.jena.rdf.model.RDFList.class);
return getAllIndividuals(oneOf.iterator(), c.getOntology());
}
private Set getAllObjectProperties(Iterator i, OWLOntology ont) {
Set set = new HashSet();
while(i.hasNext()) {
Resource r = (Resource) i.next();
set.add(OWLModelImpl.this.wrapObjectProperty((Property) r.as(Property.class), ont));
}
return set;
}
private Set getAllDataProperties(Iterator i, OWLOntology ont) {
Set set = new HashSet();
while(i.hasNext()) {
Resource r = (Resource) i.next();
set.add(OWLModelImpl.this.wrapDataProperty((Property) r.as(Property.class), ont));
}
return set;
}
protected Set getAllClasses(Iterator i, OWLOntology ont) {
Set set = new HashSet();
while(i.hasNext()) {
set.add(OWLModelImpl.this.wrapClass((Resource) i.next(), ont));
}
return set;
}
private OWLIndividualList getAllIndividuals(Iterator i, OWLOntology ont) {
OWLIndividualList list = OWLFactory.createIndividualList();
while(i.hasNext()) {
RDFNode node = (RDFNode) i.next();
if(node instanceof Resource)
list.add(wrapIndividual((Resource) node, ont));
}
return list;
}
private OWLIndividual getFirstIndividual(Iterator i, OWLOntology ont) {
while(i.hasNext()) {
RDFNode node = (RDFNode) i.next();
if(node instanceof Resource) {
return wrapIndividual((Resource) node, ont);
}
}
return null;
}
private OWLDataValueList getAllDataValues(Iterator i, OWLOntology ont) {
OWLDataValueList list = OWLFactory.createDataValueList();
while(i.hasNext()) {
RDFNode node = (RDFNode) i.next();
if(node instanceof Literal)
list.add(wrapDataValue((Literal) node, ont));
}
return list;
}
protected abstract OWLDataValue wrapDataValue(Literal l, OWLOntology ont);
protected abstract OWLIndividual wrapIndividual(Resource r, OWLOntology ont);
protected abstract OWLClass wrapClass(Resource r, OWLOntology ont);
protected abstract OWLObjectProperty wrapObjectProperty(Property p, OWLOntology ont);
protected abstract OWLDataProperty wrapDataProperty(Property p, OWLOntology ont);
public void applyGround( AtomList atoms ) {
apply( atoms, true );
}
public void apply( AtomList atoms ) throws UnboundVariableException {
apply( atoms, false );
}
private void apply( AtomList atoms, boolean skipUnground ) {
LOOP:
for( AtomList list = atoms; !list.isEmpty(); list = (AtomList) list.getRest() ) {
Atom atom = (Atom) list.getFirst();
for(int i = 0; i < atom.getArgumentCount(); i++) {
SWRLObject arg = atom.getArgument( i );
if( arg.isVariable() ) {
if( skipUnground )
continue LOOP;
else
throw new UnboundVariableException( (Variable) arg );
}
}
if(atom instanceof ClassAtom) {
ClassAtom classAtom = (ClassAtom) atom;
OWLClass c = classAtom.getClassPredicate();
OWLIndividual ind = classAtom.getArgument1();
addType(ind, c);
}
else if(atom instanceof IndividualPropertyAtom) {
IndividualPropertyAtom propAtom = (IndividualPropertyAtom) atom;
OWLObjectProperty pred = propAtom.getPropertyPredicate();
OWLIndividual subj = propAtom.getArgument1();
OWLIndividual obj = propAtom.getArgument2();
addProperty(subj, pred, obj);
}
else if(atom instanceof DataPropertyAtom) {
DataPropertyAtom propAtom = (DataPropertyAtom) atom;
OWLDataProperty pred = propAtom.getPropertyPredicate();
OWLIndividual subj = propAtom.getArgument1();
OWLDataValue obj = (OWLDataValue) propAtom.getArgument2();
addProperty(subj, pred, obj);
}
else if(atom instanceof SameIndividualAtom) {
throw new NotImplementedException();
}
else if(atom instanceof DifferentIndividualsAtom) {
throw new NotImplementedException();
}
else
throw new RuntimeException("Unknown atom type: " + atom);
}
}
public boolean isTrue(ABoxQuery query) {
return !query( query ).isEmpty();
}
public boolean isTrue(Condition condition) {
return isTrue( condition.getBody().toQuery() );
}
public boolean isTrue(Condition condition, ValueMap values) {
AtomList atoms = condition.getBody();
// assume that no expression body evaluates to true
if( atoms == null )
return true;
atoms = atoms.apply( values );
ABoxQuery query = atoms.toQuery();
return !query( query ).isEmpty();
}
private Node makeNode(OWLObject term) {
if(term instanceof Variable) {
String varName = ((Variable) term).getLocalName();
if(varName == null || varName.equals(""))
throw new IllegalArgumentException(
"There is no local name for the variable URI " + ((Variable) term).getURI());
return Node.createVariable( varName );
}
else
return ((RDFNode) term.getImplementation()).asNode();
}
private Node makeNode( NodeValue nodeVal ) {
if ( nodeVal.isBooleanRaw() )
return Node.createLiteral(nodeVal.getBoolean()?"true":"false", null, XSDDatatype.XSDboolean) ;
if ( nodeVal.isDate() )
return Node.createLiteral(Utils.calendarToXSDDateTimeString(nodeVal.getDate()), null, XSDDatatype.XSDdateTime) ;
if ( nodeVal.isInteger() )
return Node.createLiteral(Long.toString(nodeVal.getInteger()), null, XSDDatatype.XSDinteger) ;
if ( nodeVal.isDouble() )
return Node.createLiteral(Double.toString(nodeVal.getDouble()), null, XSDDatatype.XSDdouble) ;
if ( nodeVal.isString() )
return Node.createLiteral(nodeVal.getString()) ;
throw new RuntimeException( "Unrecognized node type" );
}
public QueryExecution makeJenaQuery( AtomList body, Model model ) {
// AtomList body = q.getBody();
// List resultVars = q.getResultVars();
ResultBinding initialBinding = new ResultBinding( model );
initialBinding.add( "test", OWL.Thing );
ElementGroup group = new ElementGroup();
List constraints = new ArrayList();
for( AtomList list = body; !list.isEmpty(); list = (AtomList) list.getRest() ) {
Atom atom = (Atom) list.getFirst();
int argCount = atom.getArgumentCount();
Node s = null, p = null, o = null;
s = makeNode( atom.getArgument( 0 ) );
if( argCount > 1 )
o = makeNode( atom.getArgument( 1 ) );
if(atom instanceof BuiltinAtom) {
OWLIndividual builtin = ((BuiltinAtom) atom).getBuiltin();
Expr arg1 = s.isVariable() ? (Expr) new NodeVar( s.getName() ) : NodeValue.makeNode( s );
Expr arg2 = o.isVariable() ? (Expr) new NodeVar(o.getName() ) : NodeValue.makeNode( o );
Expr arg3 = null;
if(argCount > 2) {
Node node3 = makeNode( atom.getArgument( 2 ) );
arg3 = node3.isVariable() ? (Expr) new NodeVar(node3.getName() ) : NodeValue.makeNode( node3 );
}
Expr c = null;
if ( builtin.equals( SWRLB.equal ) ) {
if( arg1.isConstant() ) {
if( arg2.isConstant() )
c = new E_Equal( arg1, arg2 );
else
initialBinding.add( o.getName(), ontModel.asRDFNode( makeNode( arg1.getConstant() ) ) );
}
else {
if( arg2.isConstant() )
initialBinding.add( s.getName(), ontModel.asRDFNode( arg2.getConstant().asNode() ) );
else
c = new E_Equal( arg1, arg2 );
}
}
else if ( builtin.equals( SWRLB.notEqual ) )
c = new E_NotEqual( arg1, arg2 );
else if ( builtin.equals( SWRLB.greaterThan ) )
c = new E_GreaterThan( arg1, arg2 );
else if ( builtin.equals( SWRLB.greaterThanOrEqual ) )
c = new E_GreaterThanOrEqual( arg1, arg2 );
else if ( builtin.equals( SWRLB.lessThan ) )
c = new E_LessThan( arg1, arg2 );
else if ( builtin.equals( SWRLB.lessThanOrEqual ) )
c = new E_GreaterThanOrEqual( arg1, arg2 );
else if ( builtin.equals( SWRLB.add ) ) {
if( !arg1.isConstant() && arg2.isConstant() && arg3.isConstant() ) {
Expr expr = new E_Add( arg2, arg3 );
NodeValue result = expr.eval( new Binding0(), new ExecutionContext() );
initialBinding.add( arg1.getVarName(), ontModel.asRDFNode( makeNode( result.getConstant() ) ) );
}
else if( arg1.isConstant() && !arg2.isConstant() && arg3.isConstant() ) {
Expr expr = new E_Subtract( arg1, arg3 );
NodeValue result = expr.eval( new Binding0(), new ExecutionContext() );
initialBinding.add( arg2.getVarName(), ontModel.asRDFNode( result.getConstant().asNode() ) );
}
else if( arg1.isConstant() && arg2.isConstant() && !arg3.isConstant() ) {
Expr expr = new E_Subtract( arg1, arg2 );
NodeValue result = expr.eval( new Binding0(), new ExecutionContext() );
initialBinding.add( arg3.getVarName(), ontModel.asRDFNode( result.getConstant().asNode() ) );
}
else
c = new E_Equal( arg1, new E_Subtract( arg2, arg3 ) );
}
else if ( builtin.equals( SWRLB.subtract ) ) {
if( !arg1.isConstant() && arg2.isConstant() && arg3.isConstant() ) {
Expr expr = new E_Subtract( arg2, arg3 );
NodeValue result = expr.eval( new Binding0(), new ExecutionContext() );
initialBinding.add( arg1.getVarName(), ontModel.asRDFNode( makeNode( result.getConstant() ) ) );
}
else if( arg1.isConstant() && !arg2.isConstant() && arg3.isConstant() ) {
Expr expr = new E_Add( arg1, arg3 );
NodeValue result = expr.eval( new Binding0(), new ExecutionContext() );
initialBinding.add( arg2.getVarName(), ontModel.asRDFNode( result.getConstant().asNode() ) );
}
else if( arg1.isConstant() && arg2.isConstant() && !arg3.isConstant() ) {
Expr expr = new E_Subtract( arg2, arg1 );
NodeValue result = expr.eval( new Binding0(), new ExecutionContext() );
initialBinding.add( arg3.getVarName(), ontModel.asRDFNode( result.getConstant().asNode() ) );
}
else
c = new E_Equal( arg1, new E_Subtract( arg2, arg3 ) );
}
else
throw new NotImplementedException( builtin.toPrettyString() );
if( c != null )
constraints.add(c);
}
else {
if(atom instanceof ClassAtom) {
p = RDF.type.asNode();
o = makeNode(((ClassAtom) atom).getClassPredicate());
}
else if(atom instanceof IndividualPropertyAtom)
p = makeNode(((IndividualPropertyAtom) atom).getPropertyPredicate());
else if(atom instanceof DataPropertyAtom)
p = makeNode(((DataPropertyAtom) atom).getPropertyPredicate());
else if(atom instanceof SameIndividualAtom)
p = OWL.sameAs.asNode();
else if(atom instanceof DifferentIndividualsAtom)
p = OWL.differentFrom.asNode();
else
throw new RuntimeException("Unknown atom type " + atom);
group.addTriple( Triple.create( s, p, o ) );
}
}
if( !constraints.isEmpty() ) {
for( Iterator i = constraints.iterator(); i.hasNext(); ) {
Constraint c = (Constraint) i.next();
group.addElement( new ElementFilter( c ) );
}
}
Query sparql = new Query();
sparql.setQueryType( Query.QueryTypeSelect );
sparql.setQueryElement( group );
// FIXME Set the result vars
sparql.setQueryResultStar( true );
// return sparql;
return QueryExecutionFactory.create( sparql, ontModel, initialBinding );
}
public List query(String rdql) {
ABoxQuery query = OWLFactory.createRDQLParser( this ).parse( rdql );
return query( query );
}
public List query(ABoxQuery query, ValueMap values) {
ABoxQuery q = query.apply( values );
return query( q );
}
public List query(ABoxQuery query) {
List result = new ArrayList();
List resultVars = query.getResultVars();
AtomList atoms = query.getBody();
// Query sparql = makeJenaQuery( atoms );
// QueryExecution qe = QueryExecutionFactory.create( sparql, ontModel );
QueryExecution qe = makeJenaQuery( atoms, ontModel );
ResultSet results = qe.execSelect();
while(results.hasNext()) {
QuerySolution binding = results.nextSolution();
ValueMap map = new ValueMap();
for(int i = 0; i < resultVars.size(); i++) {
Variable var = (Variable) resultVars.get(i);
String rdqlVar = var.getLocalName();
RDFNode value = binding.get(rdqlVar);
if( value != null ) {
OWLValue owlValue = null;
if(value instanceof Literal)
owlValue = new OWLDataValueImpl((Literal) value);
else {
Resource resource = (Resource) value;
owlValue = new OWLIndividualImpl(baseOntology, resource);
}
map.setValue(var, owlValue);
}
}
result.add(map);
}
return result;
}
// public List query(ABoxQuery query, ValueMap values) {
// List result = new ArrayList();
// List resultVars = query.getResultVars();
//// String rdqlStr = query.toRDQL();
// Query rdql = makeJenaQuery( query.getBody() );
// QueryEngine qe = new QueryEngine( rdql );
// qe.setDataSet( new DataSource1( ontModel ) );
//
// ResultBindingImpl initBinding = null;
// if( values != null || !values.isEmpty() ) {
// initBinding = new ResultBindingImpl();
//
// for(Iterator i = values.getVariables().iterator(); i.hasNext();) {
// Variable var = (Variable) i.next();
// OWLValue value = values.getValue( var );
//
// initBinding.add( var.getLocalName(), (RDFNode) value.getImplementation() );
// }
// }
//
// QueryResults results = qe.exec( initBinding );
// while(results.hasNext()) {
// ResultBinding binding = (ResultBinding) results.next();
// ValueMap map = new ValueMap();
// for(int i = 0; i < resultVars.size(); i++) {
// Variable var = (Variable) resultVars.get(i);
// String rdqlVar = var.getLocalName();
// RDFNode value = (RDFNode) binding.get(rdqlVar);
//
// if( value != null ) {
// OWLValue owlValue = null;
// if(value instanceof Literal)
// owlValue = new OWLDataValueImpl((Literal) value);
// else {
// Resource resource = (Resource) value;
// owlValue = new OWLIndividualImpl(baseOntology, resource);
// }
// map.setValue(var, owlValue);
// }
// }
// result.add(map);
// }
//
// return result;
// }
public boolean isSubTypeOf(OWLDataType t1, OWLDataType t2) {
// FIXME datatype subsumption
return t1.equals(t2);
}
public boolean isSubTypeOf(OWLType t1, OWLType t2) {
if(t1 instanceof OWLClass && t2 instanceof OWLClass)
return isSubClassOf((OWLClass) t1, (OWLClass) t2);
if(t1 instanceof OWLDataType && t2 instanceof OWLDataType)
return isSubTypeOf((OWLDataType) t1, (OWLDataType) t2);
return false;
}
public AnyOrder createAnyOrder() { return createAnyOrder(createInstance(OWLS.Process.AnyOrder)); }
public AnyOrder createAnyOrder(URI uri) { return createAnyOrder(createInstance(OWLS.Process.AnyOrder, uri)); }
public AnyOrder createAnyOrder(OWLIndividual ind) { return new AnyOrderImpl(ind); }
public AtomicProcess createAtomicProcess() { return new AtomicProcessImpl(createInstance(OWLS.Process.AtomicProcess)); }
public AtomicProcess createAtomicProcess(URI uri) { return new AtomicProcessImpl(createInstance(OWLS.Process.AtomicProcess, uri)); }
public AtomicProcess createAtomicProcess(OWLIndividual ind) { return new AtomicProcessImpl(ind); }
public Choice createChoice() { return createChoice(createInstance(OWLS.Process.Choice)); }
public Choice createChoice(URI uri) { return createChoice(createInstance(OWLS.Process.Choice, uri)); }
public Choice createChoice(OWLIndividual ind) { return new ChoiceImpl(ind); }
public CompositeProcess createCompositeProcess() { return createCompositeProcess(createInstance(OWLS.Process.CompositeProcess)); }
public CompositeProcess createCompositeProcess(URI uri) { return createCompositeProcess(createInstance(OWLS.Process.CompositeProcess, uri)); }
public CompositeProcess createCompositeProcess(OWLIndividual ind) {
return new CompositeProcessImpl(ind);
}
public Condition createSWRLCondition() { return new SWRLExpressionImpl(createInstance(OWLS.Expression.SWRL_Condition)); }
public Condition createSWRLCondition(URI uri) { return new SWRLExpressionImpl(createInstance(OWLS.Expression.SWRL_Condition, uri)); }
public Condition createSWRLCondition(OWLIndividual ind) { return new SWRLExpressionImpl(ind); }
public Expression createSWRLExpression() { return new SWRLExpressionImpl(createInstance(OWLS.Expression.SWRL_Expression)); }
public Expression createSWRLExpression(URI uri) { return new SWRLExpressionImpl(createInstance(OWLS.Expression.SWRL_Expression, uri)); }
public Expression createSWRLExpression(OWLIndividual ind) { return new SWRLExpressionImpl(ind); }
public ForEach createForEach() { return createForEach(createInstance(OWLS.Process.ForEach)); }
public ForEach createForEach(URI uri) { return createForEach(createInstance(OWLS.Process.ForEach, uri)); }
public ForEach createForEach(OWLIndividual ind) {
return new ForEachImpl(ind);
}
public Grounding createGrounding() { return createGrounding(createInstance(OWLS.Grounding.WsdlGrounding)); }
public Grounding createGrounding(URI uri) { return createGrounding(createInstance(OWLS.Grounding.WsdlGrounding, uri)); }
public Grounding createGrounding(OWLIndividual ind) {
return new GroundingImpl(ind);
}
public IfThenElse createIfThenElse() { return new IfThenElseImpl(createInstance(OWLS.Process.IfThenElse)); }
public IfThenElse createIfThenElse(URI uri) { return new IfThenElseImpl(createInstance(OWLS.Process.IfThenElse, uri)); }
public IfThenElse createIfThenElse(OWLIndividual ind) {
return new IfThenElseImpl(ind);
}
public Input createInput() { return new InputImpl(createInstance(OWLS.Process.Input)); }
public Input createInput(URI uri) { return new InputImpl(createInstance(OWLS.Process.Input, uri)); }
public Input createInput(OWLIndividual ind) { return new InputImpl(ind); }
public InputBinding createInputBinding() { return new InputBindingImpl(createInstance(OWLS.Process.InputBinding)); }
public InputBinding createInputBinding(URI uri) { return new InputBindingImpl(createInstance(OWLS.Process.InputBinding, uri)); }
public InputBinding createInputBinding(OWLIndividual ind) { return new InputBindingImpl(ind); }
public Local createLocal() { return createLocal(createInstance(OWLS.Process.Local)); }
public Local createLocal(URI uri) { return createLocal(createInstance(OWLS.Process.Local, uri)); }
public Local createLocal(OWLIndividual ind) { return new LocalImpl(ind); }
public MessageMap createWSDLMessageMap(OWLIndividual ind) {
return new WSDLMessageMapImpl(ind);
}
public MessageMap createWSDLInputMessageMap() { return createWSDLMessageMap(createInstance(OWLS.Grounding.WsdlInputMessageMap)); }
public MessageMap createWSDLInputMessageMap(URI uri) {
return createWSDLMessageMap(createInstance(OWLS.Grounding.WsdlInputMessageMap, uri));
}
public MessageMap createWSDLOutputMessageMap() { return createWSDLMessageMap(createInstance(OWLS.Grounding.WsdlOutputMessageMap)); }
public MessageMap createWSDLOutputMessageMap(URI uri) {
return createWSDLMessageMap(createInstance(OWLS.Grounding.WsdlOutputMessageMap, uri));
}
public MessageMap createUPnPMessageMap() { return createUPnPMessageMap(createInstance(FLAServiceOnt.UPnPMap)); }
public MessageMap createUPnPMessageMap(URI uri) {
return createUPnPMessageMap(createInstance(FLAServiceOnt.UPnPMap, uri));
}
public MessageMap createUPnPMessageMap(OWLIndividual ind) {
return new UPnPMessageMapImpl(ind);
}
public Output createOutput() { return new OutputImpl(createInstance(OWLS.Process.Output)); }
public Output createOutput(URI uri) { return new OutputImpl(createInstance(OWLS.Process.Output, uri)); }
public Output createOutput(OWLIndividual ind) { return new OutputImpl(ind); }
public OutputBinding createOutputBinding() { return new OutputBindingImpl(createInstance(OWLS.Process.OutputBinding)); }
public OutputBinding createOutputBinding(URI uri) { return new OutputBindingImpl(createInstance(OWLS.Process.OutputBinding, uri)); }
public OutputBinding createOutputBinding(OWLIndividual ind) { return new OutputBindingImpl(ind); }
public Perform createPerform() { return new PerformImpl(createInstance(OWLS.Process.Perform)); }
public Perform createPerform(URI uri) { return new PerformImpl(createInstance(OWLS.Process.Perform, uri)); }
public Perform createPerform(OWLIndividual ind) { return new PerformImpl(ind); }
public Produce createProduce() { return createProduce(createInstance(OWLS.Process.Produce)); }
public Produce createProduce(URI uri) { return createProduce(createInstance(OWLS.Process.Produce, uri)); }
public Produce createProduce(OWLIndividual ind) {
return new ProduceImpl(ind);
}
public Profile createProfile() { return createProfile(createInstance(OWLS.Profile.Profile)); }
public Profile createProfile(URI uri) { return createProfile(createInstance(OWLS.Profile.Profile, uri)); }
public Profile createProfile(OWLIndividual ind) {
return new ProfileImpl(ind);
}
public RepeatUntil createRepeatUntil() { return new RepeatUntilImpl(createInstance(OWLS.Process.RepeatUntil)); }
public RepeatUntil createRepeatUntil(URI uri) { return new RepeatUntilImpl(createInstance(OWLS.Process.RepeatUntil, uri)); }
public RepeatUntil createRepeatUntil(OWLIndividual ind) {
return new RepeatUntilImpl(ind);
}
public RepeatWhile createRepeatWhile() { return new RepeatWhileImpl(createInstance(OWLS.Process.RepeatWhile)); }
public RepeatWhile createRepeatWhile(URI uri) { return new RepeatWhileImpl(createInstance(OWLS.Process.RepeatWhile, uri)); }
public RepeatWhile createRepeatWhile(OWLIndividual ind) {
return new RepeatWhileImpl(ind);
}
public Result createResult() { return new ResultImpl(createInstance(OWLS.Process.Result)); }
public Result createResult(URI uri) { return new ResultImpl(createInstance(OWLS.Process.Result, uri)); }
public Result createResult(OWLIndividual ind) { return new ResultImpl(ind); }
public Sequence createSequence() { return createSequence(createInstance(OWLS.Process.Sequence)); }
public Sequence createSequence(URI uri) { return createSequence(createInstance(OWLS.Process.Sequence, uri)); }
public Sequence createSequence(OWLIndividual ind) {
return new SequenceImpl(ind);
}
public Service createService() { return createService(createInstance(OWLS.Service.Service)); }
public Service createService(URI uri) { return createService(createInstance(OWLS.Service.Service, uri)); }
public Service createService(OWLIndividual ind) {
return new ServiceImpl(ind);
}
public ServiceParameter createServiceParameter() { return createServiceParameter(createInstance(OWLS.Profile.ServiceParameter)); }
public ServiceParameter createServiceParameter(URI uri) { return createServiceParameter(createInstance(OWLS.Profile.ServiceParameter, uri)); }
public ServiceParameter createServiceParameter(OWLIndividual ind) {
return new ServiceParameterImpl(ind);
}
public Split createSplit() { return createSplit(createInstance(OWLS.Process.Split)); }
public Split createSplit(URI uri) { return createSplit(createInstance(OWLS.Process.Split, uri)); }
public Split createSplit(OWLIndividual ind) {
return new SplitImpl(ind);
}
public SplitJoin createSplitJoin() { return createSplitJoin(createInstance(OWLS.Process.SplitJoin)); }
public SplitJoin createSplitJoin(URI uri) { return createSplitJoin(createInstance(OWLS.Process.SplitJoin, uri)); }
public SplitJoin createSplitJoin(OWLIndividual ind) {
return new SplitJoinImpl(ind);
}
public UPnPAtomicGrounding createUPnPAtomicGrounding() {
return createUPnPAtomicGrounding(createInstance(FLAServiceOnt.UPnPAtomicProcessGrounding));
}
public UPnPAtomicGrounding createUPnPAtomicGrounding(URI uri) {
return createUPnPAtomicGrounding(createInstance(FLAServiceOnt.UPnPAtomicProcessGrounding, uri));
}
public UPnPAtomicGrounding createUPnPAtomicGrounding(OWLIndividual ind) {
return new UPnPAtomicGroundingImpl(ind);
}
// added 15.4.2005 by Michael Daenzer
public JavaAtomicGrounding createJavaAtomicGrounding() {
return createJavaAtomicGrounding(createInstance(MoreGroundings.JavaAtomicProcessGrounding));
}
public JavaAtomicGrounding createJavaAtomicGrounding(URI uri) {
return createJavaAtomicGrounding(createInstance(MoreGroundings.JavaAtomicProcessGrounding, uri));
}
public JavaAtomicGrounding createJavaAtomicGrounding(OWLIndividual ind) {
return new JavaAtomicGroundingImpl(ind);
}
public Grounding createJavaGrounding() { return createJavaGrounding(createInstance(MoreGroundings.JavaGrounding)); }
public Grounding createJavaGrounding(URI uri) { return createJavaGrounding(createInstance(MoreGroundings.JavaGrounding, uri)); }
public Grounding createJavaGrounding(OWLIndividual ind) {
return new GroundingImpl(ind);
}
// end added by Michael Daenzer
public ValueOf createValueOf() { return new ValueOfImpl(createInstance(OWLS.Process.ValueOf)); }
public ValueOf createValueOf(URI uri) { return new ValueOfImpl(createInstance(OWLS.Process.ValueOf, uri)); }
public ValueOf createValueOf(OWLIndividual ind) { return new ValueOfImpl(ind); }
public ValueData createValueData(OWLValue dataValue) {
return new ValueDataImpl(dataValue);
}
public WSDLAtomicGrounding createWSDLAtomicGrounding() {
return createWSDLAtomicGrounding(createInstance(OWLS.Grounding.WsdlAtomicProcessGrounding));
}
public WSDLAtomicGrounding createWSDLAtomicGrounding(URI uri) {
return createWSDLAtomicGrounding(createInstance(OWLS.Grounding.WsdlAtomicProcessGrounding, uri));
}
public WSDLAtomicGrounding createWSDLAtomicGrounding(OWLIndividual ind) {
return new WSDLAtomicGroundingImpl(ind);
}
public WSDLOperationRef createWSDLOperationRef() {
return new WSDLOperationRefImpl(createInstance(OWLS.Grounding.WsdlOperationRef));
}
public WSDLOperationRef createWSDLOperationRef(URI uri) {
return new WSDLOperationRefImpl(createInstance(OWLS.Grounding.WsdlOperationRef, uri));
}
public List getServices() {
return OWLSFactory.wrapList(getInstances(OWLS.Service.Service), Service.class);
}
public Service getService(URI serviceURI) {
OWLIndividual ind = getIndividual(serviceURI);
return (ind == null) ? null : (Service) ind.castTo(Service.class);
}
public List getProfiles() {
return OWLSFactory.wrapList(getInstances(OWLS.Profile.Profile), Service.class);
}
public Profile getProfile(URI profileURI) {
OWLIndividual ind = getIndividual(profileURI);
return (ind == null) ? null : (Profile) ind.castTo( Profile.class );
}
public List getProcesses() {
return OWLSFactory.wrapList(getInstances(OWLS.Process.Process), Process.class);
}
public List getProcesses(int type) {
switch(type) {
case Process.ANY:
return OWLSFactory.wrapList(getInstances(OWLS.Process.Process), Process.class);
case Process.ATOMIC:
return OWLSFactory.wrapList(getInstances(OWLS.Process.AtomicProcess), AtomicProcess.class);
case Process.COMPOSITE:
return OWLSFactory.wrapList(getInstances(OWLS.Process.CompositeProcess), CompositeProcess.class);
case Process.SIMPLE:
return OWLSFactory.wrapList(getInstances(OWLS.Process.SimpleProcess), SimpleProcess.class);
default:
break;
}
return null;
}
public Process getProcess(URI processURI) {
OWLIndividual ind = getIndividual(processURI);
return (ind == null) ? null : (Process) ind.castTo( Process.class );
}
public ControlConstructList createControlConstructList(ControlConstruct cc) {
RDFList list = createList( OWLS.CCList, cc );
return (ControlConstructList) list.castTo(ControlConstructList.class);
}
public ControlConstructBag createControlConstructBag(ControlConstruct cc) {
RDFList list = createList( OWLS.CCBag, cc );
return (ControlConstructBag) list.castTo(ControlConstructBag.class);
}
public boolean isLockSupported() {
return true;
}
public void lockForRead() throws LockNotSupportedException {
ontModel.enterCriticalSection(Lock.READ);
}
public void lockForWrite() throws LockNotSupportedException {
ontModel.enterCriticalSection(Lock.WRITE);
}
public void releaseLock() throws LockNotSupportedException {
ontModel.leaveCriticalSection();
}
public OWLWriter getWriter() {
if( writer == null ){
writer = OWLFactory.createWriter();
writer.setNsPrefix("service", OWLS.Service.URI);
writer.setNsPrefix("profile", OWLS.Profile.URI);
writer.setNsPrefix("process", OWLS.Process.URI);
writer.setNsPrefix("grounding", OWLS.Grounding.URI);
writer.setNsPrefix("expression", OWLS.Expression.URI);
writer.setNsPrefix("swrl", SWRL.URI);
writer.setNsPrefix("list", URIUtils.getNameSpace(OWLS.ObjList.List().getURI().toString()));
writer.addPrettyType(OWLS.Service.Service);
writer.addPrettyType(OWLS.Service.ServiceGrounding);
writer.addPrettyType(OWLS.Profile.Profile);
writer.addPrettyType(OWLS.Process.Process);
writer.addPrettyType(OWLS.Process.AtomicProcess);
writer.addPrettyType(OWLS.Process.CompositeProcess);
writer.addPrettyType(OWLS.Process.SimpleProcess);
writer.addPrettyType(OWLS.Process.Perform);
writer.addPrettyType(OWLS.Grounding.WsdlGrounding);
writer.addPrettyType(OWLS.Grounding.WsdlAtomicProcessGrounding);
}
return writer;
}
public void write(Writer out) {
getWriter().write(this, out);
}
public void write(Writer out, URI baseURI) {
getWriter().write(this, out, baseURI);
}
public void write(OutputStream out) {
getWriter().write(this, out);
}
public void write(OutputStream out, URI baseURI) {
getWriter().write(this, out, baseURI);
}
}
|
9233043cee5c263ff799b58c44a84c7bad2ee6b6 | 6,788 | java | Java | src/main/java/org/neptunepowered/vanilla/mixin/core/nbt/MixinNBTTagCompound.java | CanaryBukkitTeam/Neptune | 6a246e42c7a9dfa661a12a332a5243267fb6c4d3 | [
"MIT"
] | 11 | 2015-08-25T07:32:19.000Z | 2017-04-17T16:50:22.000Z | src/main/java/org/neptunepowered/vanilla/mixin/core/nbt/MixinNBTTagCompound.java | CanaryBukkitTeam/Neptune | 6a246e42c7a9dfa661a12a332a5243267fb6c4d3 | [
"MIT"
] | 10 | 2015-07-23T18:39:30.000Z | 2016-10-04T21:47:53.000Z | src/main/java/org/neptunepowered/vanilla/mixin/core/nbt/MixinNBTTagCompound.java | CanaryBukkitTeam/Neptune | 6a246e42c7a9dfa661a12a332a5243267fb6c4d3 | [
"MIT"
] | 3 | 2018-02-10T12:58:41.000Z | 2020-10-06T18:46:11.000Z | 30.035398 | 111 | 0.686506 | 996,437 | /*
* This file is part of NeptuneVanilla, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2017, Jamie Mansfield <https://github.com/jamierocks>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.neptunepowered.vanilla.mixin.core.nbt;
import net.canarymod.api.nbt.BaseTag;
import net.canarymod.api.nbt.CompoundTag;
import net.canarymod.api.nbt.ListTag;
import net.canarymod.api.nbt.NBTTagType;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
@Mixin(NBTTagCompound.class)
public abstract class MixinNBTTagCompound extends MixinNBTBase<CompoundTag> implements CompoundTag {
@Shadow private Map<String, NBTBase> tagMap;
@Shadow public abstract int getInteger(String key);
@Shadow public abstract void setTag(String key, NBTBase value);
@Shadow public abstract void setByte(String key, byte value);
@Shadow public abstract void setShort(String key, short value);
@Shadow public abstract void setInteger(String key, int value);
@Shadow public abstract void setLong(String key, long value);
@Shadow public abstract void setFloat(String key, float value);
@Shadow public abstract void setDouble(String key, double value);
@Shadow public abstract void setString(String key, String value);
@Shadow public abstract void setByteArray(String key, byte[] value);
@Shadow public abstract void setIntArray(String key, int[] value);
@Shadow public abstract void setBoolean(String key, boolean value);
@Shadow public abstract NBTBase getTag(String key);
@Shadow public abstract boolean hasKey(String key, int type);
@Shadow public abstract NBTTagCompound shadow$getCompoundTag(String key);
@Shadow public abstract byte getByte(String key);
@Shadow public abstract short getShort(String key);
@Shadow public abstract long getLong(String key);
@Shadow public abstract float getFloat(String key);
@Shadow public abstract double getDouble(String key);
@Shadow public abstract String getString(String key);
@Shadow public abstract byte[] getByteArray(String key);
@Shadow public abstract int[] getIntArray(String key);
@Shadow public abstract boolean getBoolean(String key);
@Override
public Collection<BaseTag> values() {
return (Collection) this.tagMap.values();
}
@Override
public Set<String> keySet() {
return this.tagMap.keySet();
}
@Override
public void put(String key, BaseTag value) {
this.setTag(key, (NBTBase) value);
}
@Override
public void put(String key, byte value) {
this.setByte(key, value);
}
@Override
public void put(String key, short value) {
this.setShort(key, value);
}
@Override
public void put(String key, int value) {
this.setInteger(key, value);
}
@Override
public void put(String key, long value) {
this.setLong(key, value);
}
@Override
public void put(String key, float value) {
this.setFloat(key, value);
}
@Override
public void put(String key, double value) {
this.setDouble(key, value);
}
@Override
public void put(String key, String value) {
this.setString(key, value);
}
@Override
public void put(String key, byte[] value) {
this.setByteArray(key, value);
}
@Override
public void put(String key, int[] value) {
this.setIntArray(key, value);
}
@Override
public void put(String key, CompoundTag value) {
this.setTag(key, (NBTTagCompound) value);
}
@Override
public void put(String key, boolean value) {
this.setBoolean(key, value);
}
@Override
public BaseTag get(String key) {
return (BaseTag) this.getTag(key);
}
@Override
public boolean containsKey(String key) {
return this.tagMap.containsKey(key);
}
@Override
public boolean containsKey(String key, NBTTagType type) {
return type != NBTTagType.UNKNOWN && hasKey(key, type == NBTTagType.ANY_NUMERIC ? 99 : type.ordinal());
}
@Intrinsic
public byte tag$getByte(String key) {
return this.getByte(key);
}
@Intrinsic
public short tag$getShort(String key) {
return this.getShort(key);
}
@Override
public int getInt(String key) {
return this.getInteger(key);
}
@Intrinsic
public long tag$getLong(String key) {
return this.getLong(key);
}
@Intrinsic
public float tag$getFloat(String key) {
return this.getFloat(key);
}
@Intrinsic
public double tag$getDouble(String key) {
return this.getDouble(key);
}
@Intrinsic
public String tag$getString(String key) {
return this.getString(key);
}
@Intrinsic
public byte[] tag$getByteArray(String key) {
return this.getByteArray(key);
}
@Intrinsic
public int[] tag$getIntArray(String key) {
return this.getIntArray(key);
}
@Intrinsic
public CompoundTag getCompoundTag(String key) {
return (CompoundTag) this.shadow$getCompoundTag(key);
}
@Override
public <E extends BaseTag> ListTag<E> getListTag(String key) {
return null;
}
@Intrinsic
public boolean tag$getBoolean(String key) {
return this.getBoolean(key);
}
@Override
public void remove(String key) {
this.tagMap.remove(key);
}
@Override
public boolean isEmpty() {
return this.tagMap.isEmpty();
}
}
|
92330604904b42ee3baedaf302292097c0e32805 | 300 | java | Java | src/main/java/com/szczepix/quitsmoker/dao/IHelperRepository.java | szczepix1983/quitsmoker | b676bd5233fd625ae24fca09092de946f1ef5f9b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/szczepix/quitsmoker/dao/IHelperRepository.java | szczepix1983/quitsmoker | b676bd5233fd625ae24fca09092de946f1ef5f9b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/szczepix/quitsmoker/dao/IHelperRepository.java | szczepix1983/quitsmoker | b676bd5233fd625ae24fca09092de946f1ef5f9b | [
"Apache-2.0"
] | null | null | null | 27.272727 | 82 | 0.853333 | 996,438 | package com.szczepix.quitsmoker.dao;
import com.szczepix.quitsmoker.entities.HelperEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface IHelperRepository extends CrudRepository<HelperEntity, Integer> {
}
|
9233068950a5aaf66d2fd87fbf9a6ab6864ad707 | 1,713 | java | Java | canal-glue-core/src/main/java/cn/throwx/canal/gule/common/FieldNamingPolicy.java | zjcscut/canal-glue | 65cf346a93788d375ee0e987d67d81ea4f039bb6 | [
"MIT"
] | 13 | 2020-10-07T04:08:58.000Z | 2022-01-25T07:21:14.000Z | canal-glue-core/src/main/java/cn/throwx/canal/gule/common/FieldNamingPolicy.java | zjcscut/canal-glue | 65cf346a93788d375ee0e987d67d81ea4f039bb6 | [
"MIT"
] | null | null | null | canal-glue-core/src/main/java/cn/throwx/canal/gule/common/FieldNamingPolicy.java | zjcscut/canal-glue | 65cf346a93788d375ee0e987d67d81ea4f039bb6 | [
"MIT"
] | 2 | 2020-10-17T01:15:24.000Z | 2021-12-16T07:18:14.000Z | 27.190476 | 61 | 0.500876 | 996,439 | package cn.throwx.canal.gule.common;
/**
* @author throwable
* @version v1
* @description 属性名 -> 列名命名转换策略, 默认认为所有属性都是标准驼峰命名
* @since 2020/9/24 22:07
*/
public enum FieldNamingPolicy implements NamingPolicy {
/**
* 返回属性的原始名称作为列名,如"customerName" -> "customerName"
*/
DEFAULT {
@Override
public String convert(String source) {
return source;
}
},
/**
* 属性的原始名称转为下划线大写作为列名,如"customerName" -> "CUSTOMER_NAME"
*/
UPPER_UNDERSCORE {
@Override
public String convert(String source) {
StringBuilder content = new StringBuilder();
int len = source.length();
for (int i = 0; i < len; i++) {
char c = source.charAt(i);
if (Character.isUpperCase(c)) {
content.append(UNDER_LINE);
}
content.append(Character.toUpperCase(c));
}
return content.toString();
}
},
/**
* 属性的原始名称转为下划线小写作为列名,如"customerName" -> "customer_name"
*/
LOWER_UNDERSCORE {
@Override
public String convert(String source) {
StringBuilder content = new StringBuilder();
int len = source.length();
for (int i = 0; i < len; i++) {
char c = source.charAt(i);
if (Character.isUpperCase(c)) {
content.append(UNDER_LINE);
}
content.append(Character.toLowerCase(c));
}
return content.toString();
}
},
;
private static final String UNDER_LINE = "_";
}
|
923306e0f393164e208a0deb9e8bd2ab19922a64 | 3,716 | java | Java | src/main/java/org/jeecgframework/core/common/model/json/TreeGrid.java | java-app-scans/jeecg | 2608008efc47594c8920d4de74f3b3d475c348c2 | [
"Apache-2.0"
] | 2,138 | 2015-01-21T13:11:37.000Z | 2021-08-15T14:09:39.000Z | src/main/java/org/jeecgframework/core/common/model/json/TreeGrid.java | java-app-scans/jeecg | 2608008efc47594c8920d4de74f3b3d475c348c2 | [
"Apache-2.0"
] | 56 | 2015-12-07T07:02:24.000Z | 2021-06-25T13:56:51.000Z | src/main/java/org/jeecgframework/core/common/model/json/TreeGrid.java | java-app-scans/jeecg | 2608008efc47594c8920d4de74f3b3d475c348c2 | [
"Apache-2.0"
] | 1,329 | 2015-01-13T05:23:30.000Z | 2021-08-13T16:20:07.000Z | 24.773333 | 101 | 0.597417 | 996,440 | package org.jeecgframework.core.common.model.json;
import com.alibaba.fastjson.JSON;
import java.util.HashMap;
import java.util.Map;
public class TreeGrid implements java.io.Serializable {
private String id;
private String text;
private String parentId;
private String parentText;
private String code;
private String src;
private String note;
private Map<String,String> attributes;// 其他参数
private String operations;// 其他参数
private String state = "open";// 是否展开(open,closed)
private String order;//排序
private Map<String, Object> fieldMap; // 存储实体字段信息容器: key-字段名称,value-字段值
private String functionType;// 其他参数
private String iconStyle;//菜单图表样式
public String getFunctionType() {
return functionType;
}
public void setFunctionType(String functionType) {
this.functionType = functionType;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public String getOperations() {
return operations;
}
public void setOperations(String operations) {
this.operations = operations;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public String getParentText() {
return parentText;
}
public void setParentText(String parentText) {
this.parentText = parentText;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Map<String, Object> getFieldMap() {
return fieldMap;
}
public void setFieldMap(Map<String, Object> fieldMap) {
this.fieldMap = fieldMap;
}
public String toJson() {
return "{" +
"'id':'" + id + '\'' +
", 'text':'" + text + '\'' +
", 'parentId':'" + parentId + '\'' +
", 'parentText':'" + parentText + '\'' +
", 'code':'" + code + '\'' +
", 'src':'" + src + '\'' +
", 'note':'" + note + '\'' +
", 'attributes':" + attributes +
", 'operations':'" + operations + '\'' +
", 'state':'" + state + '\'' +
", 'order':'" + order + '\'' +
", 'iconStyle':'" + iconStyle + '\'' +
assembleFieldsJson() +
'}';
}
private String assembleFieldsJson() {
String fieldsJson = ", 'fieldMap':" + JSON.toJSON(fieldMap);
if (fieldMap != null && fieldMap.size() > 0) {
Map<String, Object> resultMap = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : fieldMap.entrySet()) {
resultMap.put("fieldMap." + entry.getKey(), entry.getValue());
}
fieldsJson += ", " + JSON.toJSON(resultMap).toString().replace("{", "").replace("}", "");
}
return fieldsJson;
}
public String getIconStyle() {
return iconStyle;
}
public void setIconStyle(String iconStyle) {
this.iconStyle = iconStyle;
}
}
|
9233075e2e6b279dfbd93b70da8a7ada81284741 | 1,418 | java | Java | chapter_003/src/main/java/ru/job4j/iterator/IteratorArray.java | simvip/isliusar | 357cda33c3d6a96e9627411468daa437d5b37fb1 | [
"Apache-2.0"
] | null | null | null | chapter_003/src/main/java/ru/job4j/iterator/IteratorArray.java | simvip/isliusar | 357cda33c3d6a96e9627411468daa437d5b37fb1 | [
"Apache-2.0"
] | null | null | null | chapter_003/src/main/java/ru/job4j/iterator/IteratorArray.java | simvip/isliusar | 357cda33c3d6a96e9627411468daa437d5b37fb1 | [
"Apache-2.0"
] | null | null | null | 20.257143 | 74 | 0.464034 | 996,441 | package ru.job4j.iterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Created by Ivan Sliusar on 12.09.2017.
* Red Line Soft corp.
*/
public class IteratorArray implements Iterable {
/**
* Array value.
*/
private int[][] testarray;
/**
* current index (coordinate x).
*/
private int x = 0;
/**
* current index (coordinate y).
*/
private int y = 0;
/**
* max index.
*/
private int maxlength;
/**
* Construct.
* @param testarray int[][]
*/
public IteratorArray(int[][] testarray) {
this.testarray = testarray;
this.maxlength = this.testarray.length;
}
/**
* Iterator.
*
* @return Iterator
*/
@Override
public Iterator iterator() {
return new Iterator() {
@Override
public boolean hasNext() {
return x < testarray.length && !(x > testarray[x].length);
}
@Override
public Object next() {
if (!hasNext()) {
throw new NoSuchElementException("no items");
}
Object o = testarray[x][y];
y++;
if (y >= testarray[x].length) {
x++;
y = 0;
}
return o;
}
};
}
}
|
923308a524e4ca751ef1e9fe608b63c8199dd166 | 813 | java | Java | mq-cloud/src/main/java/com/sohu/tv/mq/cloud/web/controller/admin/AdminViewController.java | AochongZhang/mqcloud | 34e833f4e65519c3e665e474379ec4c7622f891e | [
"Apache-2.0"
] | 605 | 2019-03-22T11:21:12.000Z | 2022-03-31T10:18:40.000Z | mq-cloud/src/main/java/com/sohu/tv/mq/cloud/web/controller/admin/AdminViewController.java | AochongZhang/mqcloud | 34e833f4e65519c3e665e474379ec4c7622f891e | [
"Apache-2.0"
] | 18 | 2019-03-29T05:19:13.000Z | 2022-03-30T11:57:47.000Z | mq-cloud/src/main/java/com/sohu/tv/mq/cloud/web/controller/admin/AdminViewController.java | AochongZhang/mqcloud | 34e833f4e65519c3e665e474379ec4c7622f891e | [
"Apache-2.0"
] | 172 | 2019-03-28T11:21:57.000Z | 2022-03-24T05:22:30.000Z | 21.394737 | 67 | 0.596556 | 996,442 | package com.sohu.tv.mq.cloud.web.controller.admin;
import java.util.Map;
import com.sohu.tv.mq.cloud.util.Result;
import com.sohu.tv.mq.cloud.web.controller.ViewController;
/**
* admin视图控制
*
* @Description:
* @author yongfeigao
* @date 2018年7月5日
*/
public abstract class AdminViewController extends ViewController {
/**
* 设置返回的模板
*
* @param map
* @param view
*/
protected void setView(Map<String, Object> map, String view) {
Result.setView(map, adminViewModule() + "/" + view);
//默认设置一个空数据
Result.setResult(map, (Object)null);
}
public String adminViewModule() {
return "admin/" + viewModule();
}
@Override
protected String view() {
return "adminTemplate";
}
}
|
92330908e4d36319a8d6d09f8469a657fd4a3ee5 | 1,743 | java | Java | core/make-runtime/solutions/jetbrains.mps.make/source_gen/jetbrains/mps/internal/make/cfg/GenerateFacetInitializer.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | core/make-runtime/solutions/jetbrains.mps.make/source_gen/jetbrains/mps/internal/make/cfg/GenerateFacetInitializer.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | core/make-runtime/solutions/jetbrains.mps.make/source_gen/jetbrains/mps/internal/make/cfg/GenerateFacetInitializer.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | 42.512195 | 218 | 0.777395 | 996,443 | package jetbrains.mps.internal.make.cfg;
/*Generated by MPS */
import jetbrains.mps.annotations.GeneratedClass;
import jetbrains.mps.make.script.PropertyPoolInitializer;
import jetbrains.mps.generator.GenerationOptions;
import jetbrains.mps.make.script.IPropertiesPool;
import jetbrains.mps.baseLanguage.tuples.runtime.Tuples;
import jetbrains.mps.make.facet.ITarget;
/**
* Single facility that knows which properties of Generate facet to initialize.
* Now takes all the values from MakeSession, but may get additional methods to set
* values explicitly (e.g. cleanMake for those longing for rebuild only).
* Perhaps, this it should be MakeSession's responsibility to set properties.
*/
@GeneratedClass(node = "r:dc013bd4-6bcf-44c3-9e08-a65e07c88df7(jetbrains.mps.internal.make.cfg)/9122198050634039886", model = "r:dc013bd4-6bcf-44c3-9e08-a65e07c88df7(jetbrains.mps.internal.make.cfg)")
public final class GenerateFacetInitializer implements PropertyPoolInitializer {
private GenerationOptions.OptionsBuilder myGenOptions;
public GenerateFacetInitializer() {
}
public GenerateFacetInitializer setGenerationOptions(GenerationOptions.OptionsBuilder optionsBuilder) {
myGenOptions = optionsBuilder;
return this;
}
@Override
public void populate(IPropertiesPool ppool) {
if (myGenOptions != null) {
// in fact, there are more than 2 properties, but Tuples._2 is superclass of Tuples._5, so I don't care
Tuples._2<Boolean, GenerationOptions.OptionsBuilder> params = (Tuples._2<Boolean, GenerationOptions.OptionsBuilder>) ppool.properties(new ITarget.Name("jetbrains.mps.lang.core.Generate.configure"), Object.class);
if (params != null) {
params._1(myGenOptions);
}
}
}
}
|
92330b46a1ff2fc2f19eadeb29c5e3a195f85918 | 15,549 | java | Java | detector-framework/src/main/java/org/lcsim/detector/tracker/silicon/SiStrips.java | omar-moreno/lcsim | ddd2abc441dcbc7b99779abf00e27ebbb5d38f0a | [
"BSD-3-Clause-LBNL"
] | 1 | 2018-10-30T17:37:41.000Z | 2018-10-30T17:37:41.000Z | detector-framework/src/main/java/org/lcsim/detector/tracker/silicon/SiStrips.java | omar-moreno/lcsim | ddd2abc441dcbc7b99779abf00e27ebbb5d38f0a | [
"BSD-3-Clause-LBNL"
] | 26 | 2017-06-28T16:42:04.000Z | 2021-07-22T16:06:59.000Z | detector-framework/src/main/java/org/lcsim/detector/tracker/silicon/SiStrips.java | omar-moreno/lcsim | ddd2abc441dcbc7b99779abf00e27ebbb5d38f0a | [
"BSD-3-Clause-LBNL"
] | 5 | 2017-06-27T14:36:26.000Z | 2020-12-12T22:52:13.000Z | 31.539554 | 155 | 0.612451 | 996,444 | package org.lcsim.detector.tracker.silicon;
/*
* SiStrips.java
*
* Created on July 22, 2005, 4:07 PM
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
//import static org.lcsim.units.clhep.SystemOfUnits.*;
import org.lcsim.detector.IDetectorElement;
import org.lcsim.detector.ITransform3D;
import org.lcsim.detector.Transform3D;
import hep.physics.vec.Hep3Vector;
import hep.physics.vec.BasicHep3Vector;
import hep.physics.vec.VecOp;
import java.util.ArrayList;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import org.lcsim.detector.solids.GeomOp2D;
import org.lcsim.detector.solids.GeomOp3D;
import org.lcsim.detector.solids.Line3D;
import org.lcsim.detector.solids.LineSegment3D;
import org.lcsim.detector.solids.Point3D;
import org.lcsim.detector.solids.Polygon3D;
/**
*
* @author tknelson
*/
public class SiStrips implements SiSensorElectrodes
{
// Fields
// Object definition
private ChargeCarrier _carrier; // charge carrier collected
protected int _nstrips; // number of strips
protected double _pitch; // sense pitch
private IDetectorElement _detector; // associated detector element
private ITransform3D _parent_to_local; // parent to local transform
private ITransform3D _local_to_global; // transformation to global coordinates
private ITransform3D _global_to_local; // transformation from global coordinates
private Polygon3D _geometry; // region in which strips are defined
private double _capacitance_intercept = 10.; // fixed capacitance independent of strip length
private double _capacitance_slope = 0.1; // capacitance per unit length of strip
// Cached for convenience
protected double _strip_offset;
public SiStrips(){
};
// Constructors
//=============
public SiStrips(ChargeCarrier carrier, double pitch, IDetectorElement detector, ITransform3D parent_to_local)
{
// System.out.println("Plane of polygon in sensor coordinates has... ");
// System.out.println(" normal: "+((SiSensor)detector).getBiasSurface(carrier).getNormal());
// System.out.println(" distance: "+((SiSensor)detector).getBiasSurface(carrier).getDistance());
setCarrier(carrier);
setPitch(pitch);
setGeometry(((SiSensor)detector).getBiasSurface(carrier).transformed(parent_to_local));
setStripNumbering();
setDetectorElement(detector);
setParentToLocal(parent_to_local);
setGlobalToLocal(Transform3D.multiply(parent_to_local,detector.getGeometry().getGlobalToLocal()));
setLocalToGlobal(getGlobalToLocal().inverse());
}
public SiStrips(ChargeCarrier carrier, double pitch, int nstrips, IDetectorElement detector, ITransform3D parent_to_local)
{
setCarrier(carrier);
setPitch(pitch);
setGeometry(((SiSensor)detector).getBiasSurface(carrier).transformed(parent_to_local));
setNStrips(nstrips);
setDetectorElement(detector);
setParentToLocal(parent_to_local);
setGlobalToLocal(Transform3D.multiply(parent_to_local,detector.getGeometry().getGlobalToLocal()));
setLocalToGlobal(getGlobalToLocal().inverse());
}
public SiStrips(ChargeCarrier carrier, double pitch, int nstrips, IDetectorElement detector, ITransform3D parent_to_local ,ITransform3D misalignment){
}
public SiStrips(ChargeCarrier carrier, double pitch, IDetectorElement detector, ITransform3D parent_to_local ,ITransform3D misalignment){
}
// SiSensorElectrodes interface
//=============================
// Mechanical properties
public int getNAxes()
{
return 1;
}
public IDetectorElement getDetectorElement()
{
return _detector;
}
public ITransform3D getParentToLocal()
{
return _parent_to_local;
}
public ITransform3D getLocalToGlobal()
{
return _local_to_global;
}
public ITransform3D getGlobalToLocal()
{
return _global_to_local;
}
public Polygon3D getGeometry()
{
return _geometry;
}
public Hep3Vector getMeasuredCoordinate(int axis)
{
if (axis == 0) return new BasicHep3Vector(1.0,0.0,0.0);
else return null;
}
public Hep3Vector getUnmeasuredCoordinate(int axis)
{
if (axis == 0) return new BasicHep3Vector(0.0,1.0,0.0);
else return null;
}
public int getNeighborCell(int cell, int ncells_0, int ncells_1)
{
int neighbor_cell = cell + ncells_0;
if (isValidCell(neighbor_cell)) return neighbor_cell;
else return -1;
}
public Set<Integer> getNearestNeighborCells(int cell)
{
Set<Integer> neighbors = new HashSet<Integer>();
for (int ineigh = -1 ; ineigh <= 1; ineigh=ineigh+2)
{
int neighbor_cell = getNeighborCell(cell,ineigh,0);
if (isValidCell(neighbor_cell)) neighbors.add(neighbor_cell);
}
return neighbors;
}
public boolean isValidCell(int cell)
{
return (cell >= 0 && cell < getNCells());
}
public int getNCells()
{
return _nstrips;
}
public int getNCells(int axis)
{
if (axis == 0)
{
return _nstrips;
}
else return 1;
}
public double getPitch(int axis)
{
if (axis == 0)
{
return _pitch;
}
else return 0;
}
public int getCellID(Hep3Vector position)
{
return (int)Math.round((position.x()+_strip_offset)/_pitch);
}
public int getRowNumber(Hep3Vector position)
{
return 0;
}
public int getColumnNumber(Hep3Vector position)
{
return getCellID(position);
}
public int getCellID(int row_number, int column_number)
{
return column_number;
}
public int getRowNumber(int cell_id)
{
return 0;
}
public int getColumnNumber(int cell_id)
{
return cell_id;
}
public Hep3Vector getPositionInCell(Hep3Vector position)
{
return VecOp.sub(position,getCellPosition(getCellID(position)));
}
public Hep3Vector getCellPosition(int strip_number)
{
//System.out.println("[ SiStrips ][ getCellPosition ]: strip #: " + strip_number);
//System.out.println("[ SiStrips ][ getCellPosition ]: Cell Position x: " + (strip_number*_pitch - _strip_offset));
return new BasicHep3Vector(strip_number*_pitch-_strip_offset,0.0,0.0);
}
// Electrical properties
/**
* Capacitance intercept parameter. Units are pF.
*
* Capacitance is calculated as:
* C = capacitance_intercept + strip_length * capacitance slope
*
* @param capacitance_intercept
*/
public void setCapacitanceIntercept(double capacitance_intercept) {
_capacitance_intercept = capacitance_intercept;
}
/**
* Capacitance per unit strip length. Units are pF / mm.
*
* @param capacitance_slope
*/
public void setCapacitanceSlope(double capacitance_slope) {
_capacitance_slope = capacitance_slope;
}
public ChargeCarrier getChargeCarrier()
{
return _carrier;
}
/**
* Capacitance for a particular cell. Units are pF.
*
* @param cell_id
* @return
*/
public double getCapacitance(int cell_id) // capacitance in pF
{
return _capacitance_intercept + _capacitance_slope*getStripLength(cell_id);
}
/**
* Nominal capacitance used for throwing random noise in the sensor.
* Calculated using middle strip. Units are pF.
*
* @return
*/
public double getCapacitance() {
return getCapacitance(getNCells(0) / 2);
}
public SortedMap<Integer,Integer> computeElectrodeData(ChargeDistribution distribution)
{
SortedMap<Integer,Integer> electrode_data = new TreeMap<Integer,Integer>();
//System.out.println("[ SiStrips ][ computeElectrodeData ]: Distribution mean: " + distribution.getMean());
int base_strip = getCellID(distribution.getMean());
//System.out.println("[ SiStrips ][ computeElectrodeData ]: Base strip: " + base_strip);
// put charge on strips in window 3-sigma strips on each side of base strip
int axis = 0;
int window_size = (int)Math.ceil(3.0*distribution.sigma1D(getMeasuredCoordinate(axis))/getPitch(axis));
//System.out.println("[ SiStrips ][ computeElectrodeData ]: Window size: " + window_size);
double integral_lower = distribution.getNormalization();
double integral_upper = distribution.getNormalization();
for (int istrip = base_strip-window_size; istrip <= base_strip+window_size; istrip++)
{
double cell_edge_upper = getCellPosition(istrip).x() + getPitch(axis)/2.0;
//System.out.println("cell_edge_upper: "+cell_edge_upper);
double integration_limit = cell_edge_upper; //cell_edge_upper-distribution.mean().x();
//System.out.println("integration_limit: "+integration_limit);
integral_upper = distribution.upperIntegral1D(getMeasuredCoordinate(axis),integration_limit);
//System.out.println("integral_upper: "+integral_upper);
if (integral_lower<integral_upper)
{
throw new RuntimeException("Error in integrating Gaussian charge distribution!");
}
int strip_charge = (int)Math.round(integral_lower-integral_upper);
//System.out.println("strip_charge: "+strip_charge);
if (strip_charge != 0)
{
electrode_data.put(istrip,strip_charge);
}
integral_lower = integral_upper;
}
return electrode_data;
}
// Strip specific methods
// length of strip
public double getStripLength(int cell_id)
{
//System.out.println("strip_length: "+getStrip(cell_id).getLength());
return getStrip(cell_id).getLength();
}
// center of strip
public Hep3Vector getStripCenter(int cell_id)
{
LineSegment3D strip = getStrip(cell_id);
return strip.getEndPoint(strip.getLength()/2);
}
// line segment for strip
public LineSegment3D getStrip(int cell_id)
{
Line3D strip_line = new Line3D(new Point3D(getCellPosition(cell_id)),getUnmeasuredCoordinate(0));
//System.out.println("strip_line start point: "+strip_line.getStartPoint());
//System.out.println("strip_line direction: "+strip_line.getDirection());
List<Point3D> intersections = new ArrayList<Point3D>();
// Get intersections between strip line and edges of electrode polygon
for (LineSegment3D edge : _geometry.getEdges())
{
//System.out.println("edge start point: "+edge.getStartPoint());
//System.out.println("edge end point: "+edge.getEndPoint());
if (GeomOp2D.intersects(strip_line,edge))
{
intersections.add(GeomOp3D.lineBetween(strip_line,edge).getStartPoint());
}
}
// Check for rare occurrence of duplicates (can happen at corners of polygon)
List<Point3D> strip_ends = new ArrayList<Point3D>(intersections);
if (intersections.size() > 2)
{
for (int ipoint1 = 0; ipoint1 < intersections.size(); ipoint1++)
{
Point3D point1 = intersections.get(ipoint1);
for (int ipoint2 = ipoint1+1; ipoint2 < intersections.size(); ipoint2++)
{
Point3D point2 = intersections.get(ipoint2);
if (GeomOp3D.intersects(point1,point2))
{
strip_ends.remove(point2);
if (strip_ends.size() == 2) break;
}
}
}
}
return new LineSegment3D(strip_ends.get(0),strip_ends.get(1));
}
// Private setters
//==================
public void setCarrier(ChargeCarrier carrier)
{
_carrier = carrier;
}
public void setGeometry(Polygon3D geometry)
{
//System.out.println("Plane of polygon has... ");
//System.out.println(" normal: "+geometry.getNormal());
//System.out.println(" distance: "+geometry.getDistance());
//System.out.println("Working plane has... ");
//System.out.println(" normal: "+GeomOp2D.PLANE.getNormal());
//System.out.println(" distance: "+GeomOp2D.PLANE.getDistance());
if (GeomOp3D.equals(geometry.getPlane(),GeomOp2D.PLANE))
{
_geometry = geometry;
}
else
{
throw new RuntimeException("Electrode geometry must be defined in x-y plane!!");
}
}
protected void setStripNumbering()
{
double xmin = Double.MAX_VALUE;
double xmax = Double.MIN_VALUE;
for (Point3D vertex : _geometry.getVertices())
{
xmin = Math.min(xmin,vertex.x());
xmax = Math.max(xmax,vertex.x());
}
//System.out.println("xmin: " + xmin);
//System.out.println("xmax: " + xmax);
//System.out.println("# strips: " + (int)Math.ceil((xmax-xmin)/getPitch(0)) ) ;
setNStrips( (int)Math.ceil((xmax-xmin)/getPitch(0)) ) ;
}
protected void setNStrips(int nstrips)
{
_nstrips = nstrips;
setStripOffset();
//System.out.println("Number of strips: " + _nstrips);
// _strip_offset = (_nstrips-1)*_pitch/2.;
}
protected void setStripOffset()
{
double xmin = Double.MAX_VALUE;
double xmax = Double.MIN_VALUE;
for (Point3D vertex : _geometry.getVertices())
{
xmin = Math.min(xmin,vertex.x());
xmax = Math.max(xmax,vertex.x());
}
double strips_center = (xmin+xmax)/2;
_strip_offset = ((_nstrips-1)*_pitch)/2 - strips_center;
//System.out.println("Strip offset: " + _strip_offset);
}
private void setPitch(double pitch)
{
_pitch = pitch;
}
private void setDetectorElement(IDetectorElement detector)
{
_detector = detector;
}
private void setParentToLocal(ITransform3D parent_to_local)
{
_parent_to_local = parent_to_local;
}
private void setLocalToGlobal(ITransform3D local_to_global)
{
_local_to_global = local_to_global;
}
private void setGlobalToLocal(ITransform3D global_to_local)
{
_global_to_local = global_to_local;
}
}
|
92330c7331d44752ebd5209473d00923885e5bcd | 2,809 | java | Java | component/objectstore/sql/sql-tests-common/src/main/java/uk/co/objectconnexions/expressiveobjects/objectstore/sql/common/Utils.java | objectconnexions/expressive-objects | a5ced6694cfb2daf24ba09c94cc4e1864384224c | [
"Apache-2.0"
] | null | null | null | component/objectstore/sql/sql-tests-common/src/main/java/uk/co/objectconnexions/expressiveobjects/objectstore/sql/common/Utils.java | objectconnexions/expressive-objects | a5ced6694cfb2daf24ba09c94cc4e1864384224c | [
"Apache-2.0"
] | null | null | null | component/objectstore/sql/sql-tests-common/src/main/java/uk/co/objectconnexions/expressiveobjects/objectstore/sql/common/Utils.java | objectconnexions/expressive-objects | a5ced6694cfb2daf24ba09c94cc4e1864384224c | [
"Apache-2.0"
] | null | null | null | 45.306452 | 130 | 0.749733 | 996,445 | /*
* 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 uk.co.objectconnexions.expressiveobjects.objectstore.sql.common;
import uk.co.objectconnexions.expressiveobjects.core.commons.config.ExpressiveObjectsConfiguration;
import uk.co.objectconnexions.expressiveobjects.core.objectstore.InMemoryPersistenceMechanismInstaller;
import uk.co.objectconnexions.expressiveobjects.core.runtime.installerregistry.installerapi.PersistenceMechanismInstallerAbstract;
import uk.co.objectconnexions.expressiveobjects.objectstore.sql.Sql;
import uk.co.objectconnexions.expressiveobjects.objectstore.sql.SqlObjectStore;
import uk.co.objectconnexions.expressiveobjects.objectstore.sql.SqlPersistorInstaller;
import uk.co.objectconnexions.expressiveobjects.objectstore.xml.XmlPersistenceMechanismInstaller;
public class Utils {
static PersistenceMechanismInstallerAbstract createPersistorInstaller(final ExpressiveObjectsConfiguration configuration) {
final String jdbcDriver = configuration.getString(SqlObjectStore.BASE_NAME + ".jdbc.driver");
if (jdbcDriver != null) {
return new SqlPersistorInstaller();
}
final String persistor = configuration.getString("expressive-objects.persistor");
if (persistor.equals(InMemoryPersistenceMechanismInstaller.NAME)) {
return new InMemoryPersistenceMechanismInstaller();
}
if (persistor.equals(XmlPersistenceMechanismInstaller.NAME)) {
return new XmlPersistenceMechanismInstaller();
}
if (persistor.equals(SqlPersistorInstaller.NAME)) {
return new SqlPersistorInstaller();
}
return new InMemoryPersistenceMechanismInstaller();
}
static String tableIdentifierFor(final String tableName) {
if (tableName.substring(0, 4).toUpperCase().equals("EXPRESSIVE_OBJECTS")) {
return Sql.tableIdentifier(tableName);
} else {
return Sql.tableIdentifier("expressive-objects_" + tableName);
}
}
}
|
92330cdd2a6cbb2e97cd99e1048154ddbc0b190d | 1,933 | java | Java | org.conqat.engine.core/external/commons-src/org/conqat/lib/commons/predicate/StartsWithOneOfPredicate.java | assessorgeneral/ConQAT | 2a462f23f22c22aa9d01a7a204453d1be670ba60 | [
"Apache-2.0"
] | 4 | 2016-06-26T01:13:39.000Z | 2022-03-04T16:42:35.000Z | org.conqat.engine.core/external/commons-src/org/conqat/lib/commons/predicate/StartsWithOneOfPredicate.java | assessorgeneral/ConQAT | 2a462f23f22c22aa9d01a7a204453d1be670ba60 | [
"Apache-2.0"
] | null | null | null | org.conqat.engine.core/external/commons-src/org/conqat/lib/commons/predicate/StartsWithOneOfPredicate.java | assessorgeneral/ConQAT | 2a462f23f22c22aa9d01a7a204453d1be670ba60 | [
"Apache-2.0"
] | 7 | 2015-04-01T03:50:54.000Z | 2021-11-11T05:19:48.000Z | 43.931818 | 78 | 0.498707 | 996,446 | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2011 The ConQAT Project |
| |
| Licensed under the Apache License, Version 2.0 (the "License"); |
| you may not use this file except in compliance with the License. |
| You may obtain a copy of the License at |
| |
| http://www.apache.org/licenses/LICENSE-2.0 |
| |
| Unless required by applicable law or agreed to in writing, software |
| distributed under the License is distributed on an "AS IS" BASIS, |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| See the License for the specific language governing permissions and |
| limitations under the License. |
+-------------------------------------------------------------------------*/
package org.conqat.lib.commons.predicate;
import org.conqat.lib.commons.string.StringUtils;
/**
* A predicate that selects strings that start with one of the given prefixes.
*
* @author $Author: kinnen $
* @version $Rev: 41751 $
* @ConQAT.Rating GREEN Hash: 50C248869B66FC7FF10E98558A99793E
*/
public class StartsWithOneOfPredicate implements IPredicate<String> {
/** The prefixes we check for. */
private final String[] prefixes;
/** Constructor. */
public StartsWithOneOfPredicate(String... prefixes) {
this.prefixes = prefixes.clone();
}
/** {@inheritDoc} */
@Override
public boolean isContained(String element) {
return StringUtils.startsWithOneOf(element, prefixes);
}
} |
92330d0c786f178d21d2d5fbf19e56807bd6068f | 322 | java | Java | src/main/java/io/whileaway/forgetcmd/util/ListUtils.java | ThisSeanZhang/ForgetCmd | 1037c2fd2a9b2db55955a4114c49a00d4430cc20 | [
"MIT"
] | 2 | 2020-01-20T09:22:21.000Z | 2020-04-26T08:05:53.000Z | src/main/java/io/whileaway/forgetcmd/util/ListUtils.java | ThisSeanZhang/ForgetCmd | 1037c2fd2a9b2db55955a4114c49a00d4430cc20 | [
"MIT"
] | 1 | 2020-06-28T16:45:40.000Z | 2020-06-28T16:45:40.000Z | src/main/java/io/whileaway/forgetcmd/util/ListUtils.java | ThisSeanZhang/ForgetCmd-Server | 1037c2fd2a9b2db55955a4114c49a00d4430cc20 | [
"MIT"
] | null | null | null | 20.125 | 54 | 0.689441 | 996,447 | package io.whileaway.forgetcmd.util;
import java.util.List;
import java.util.Objects;
public class ListUtils {
public static boolean isEmptyList(List list) {
return Objects.isNull(list) || list.isEmpty();
}
public static boolean notEmptyList(List list) {
return !isEmptyList(list);
}
}
|
92330d951b0eb133315bdd2a7b7e82f5e6fd6c6b | 6,215 | java | Java | org.hl7.fhir.utilities/src/main/java/org/hl7/fhir/utilities/xml/NamespaceContextMap.java | patrick-werner/org.hl7.fhir.core | f5c592fbadf9cdbf0c668b856b719b8716249277 | [
"Apache-2.0"
] | null | null | null | org.hl7.fhir.utilities/src/main/java/org/hl7/fhir/utilities/xml/NamespaceContextMap.java | patrick-werner/org.hl7.fhir.core | f5c592fbadf9cdbf0c668b856b719b8716249277 | [
"Apache-2.0"
] | null | null | null | org.hl7.fhir.utilities/src/main/java/org/hl7/fhir/utilities/xml/NamespaceContextMap.java | patrick-werner/org.hl7.fhir.core | f5c592fbadf9cdbf0c668b856b719b8716249277 | [
"Apache-2.0"
] | null | null | null | 32.883598 | 104 | 0.722124 | 996,448 | /*
Copyright (c) 2011+, HL7, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.hl7.fhir.utilities.xml;
/*-
* #%L
* org.hl7.fhir.utilities
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
// see http://illegalargumentexception.blogspot.com.au/2009/05/java-using-xpath-with-namespaces-and.html
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
/**
* An implementation of <a
* href="http://java.sun.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html">
* NamespaceContext </a>. Instances are immutable.
*
* @author McDowell
*/
public final class NamespaceContextMap implements NamespaceContext {
private final Map<String, String> prefixMap;
private final Map<String, Set<String>> nsMap;
/**
* Constructor that takes a map of XML prefix-namespaceURI values. A defensive
* copy is made of the map. An IllegalArgumentException will be thrown if the
* map attempts to remap the standard prefixes defined in the NamespaceContext
* contract.
*
* @param prefixMappings
* a map of prefix:namespaceURI values
*/
public NamespaceContextMap(
Map<String, String> prefixMappings) {
prefixMap = createPrefixMap(prefixMappings);
nsMap = createNamespaceMap(prefixMap);
}
/**
* Convenience constructor.
*
* @param mappingPairs
* pairs of prefix-namespaceURI values
*/
public NamespaceContextMap(String... mappingPairs) {
this(toMap(mappingPairs));
}
private static Map<String, String> toMap(
String... mappingPairs) {
Map<String, String> prefixMappings = new HashMap<String, String>(
mappingPairs.length / 2);
for (int i = 0; i < mappingPairs.length; i++) {
prefixMappings
.put(mappingPairs[i], mappingPairs[++i]);
}
return prefixMappings;
}
private Map<String, String> createPrefixMap(
Map<String, String> prefixMappings) {
Map<String, String> prefixMap = new HashMap<String, String>(
prefixMappings);
addConstant(prefixMap, XMLConstants.XML_NS_PREFIX,
XMLConstants.XML_NS_URI);
addConstant(prefixMap, XMLConstants.XMLNS_ATTRIBUTE,
XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
return Collections.unmodifiableMap(prefixMap);
}
private void addConstant(Map<String, String> prefixMap,
String prefix, String nsURI) {
String previous = prefixMap.put(prefix, nsURI);
if (previous != null && !previous.equals(nsURI)) {
throw new IllegalArgumentException(prefix + " -> "
+ previous + "; see NamespaceContext contract");
}
}
private Map<String, Set<String>> createNamespaceMap(
Map<String, String> prefixMap) {
Map<String, Set<String>> nsMap = new HashMap<String, Set<String>>();
for (Map.Entry<String, String> entry : prefixMap
.entrySet()) {
String nsURI = entry.getValue();
Set<String> prefixes = nsMap.get(nsURI);
if (prefixes == null) {
prefixes = new HashSet<String>();
nsMap.put(nsURI, prefixes);
}
prefixes.add(entry.getKey());
}
for (Map.Entry<String, Set<String>> entry : nsMap
.entrySet()) {
Set<String> readOnly = Collections
.unmodifiableSet(entry.getValue());
entry.setValue(readOnly);
}
return nsMap;
}
@Override
public String getNamespaceURI(String prefix) {
checkNotNull(prefix);
String nsURI = prefixMap.get(prefix);
return nsURI == null ? XMLConstants.NULL_NS_URI : nsURI;
}
@Override
public String getPrefix(String namespaceURI) {
checkNotNull(namespaceURI);
Set<String> set = nsMap.get(namespaceURI);
return set == null ? null : set.iterator().next();
}
@Override
public Iterator<String> getPrefixes(String namespaceURI) {
checkNotNull(namespaceURI);
Set<String> set = nsMap.get(namespaceURI);
return set.iterator();
}
private void checkNotNull(String value) {
if (value == null) {
throw new IllegalArgumentException("null");
}
}
/**
* @return an unmodifiable map of the mappings in the form prefix-namespaceURI
*/
public Map<String, String> getMap() {
return prefixMap;
}
}
|
92330e23374d1b93233f00d4a3e9f979127cf073 | 4,203 | java | Java | opendse-optimization/src/main/java/net/sf/opendse/optimization/io/SpecificationTransformerTypeBased.java | JoachimFalk/dse-opendse | 8501058956ee59b74db2cec7d43d1e09fa3257a1 | [
"MIT"
] | 8 | 2018-02-16T02:34:19.000Z | 2021-01-27T08:21:01.000Z | opendse-optimization/src/main/java/net/sf/opendse/optimization/io/SpecificationTransformerTypeBased.java | JoachimFalk/dse-opendse | 8501058956ee59b74db2cec7d43d1e09fa3257a1 | [
"MIT"
] | 18 | 2018-02-17T14:55:35.000Z | 2019-10-30T15:28:39.000Z | opendse-optimization/src/main/java/net/sf/opendse/optimization/io/SpecificationTransformerTypeBased.java | JoachimFalk/dse-opendse | 8501058956ee59b74db2cec7d43d1e09fa3257a1 | [
"MIT"
] | 7 | 2018-02-16T09:47:52.000Z | 2019-10-30T08:42:11.000Z | 33.094488 | 105 | 0.7271 | 996,449 | package net.sf.opendse.optimization.io;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections15.Transformer;
import net.sf.opendse.model.Architecture;
import net.sf.opendse.model.Attributes;
import net.sf.opendse.model.Link;
import net.sf.opendse.model.LinkTypes;
import net.sf.opendse.model.Mapping;
import net.sf.opendse.model.Mappings;
import net.sf.opendse.model.Resource;
import net.sf.opendse.model.ResourceTypes;
import net.sf.opendse.model.Specification;
import net.sf.opendse.model.SpecificationTypeBased;
import net.sf.opendse.model.Task;
/**
* Basic {@link Transformer} from a {@link SpecificationTypeBased} to a
* {@link Specification}. The default {@link Architecture} is constructed by
* connecting one {@link Resource} of each type in the {@link ResourceTypes} to
* an unlimited-capacity on-chip bus with {@link Link}s from the
* {@link LinkTypes}.
*
* @author Valentina Richthammer
*/
public class SpecificationTransformerTypeBased<T extends SpecificationTypeBased, S extends Specification>
implements Transformer<T, S> {
protected final String CONNECTOR = "_";
protected Map<Resource, List<Resource>> typeMap;
/* (non-Javadoc)
* @see org.apache.commons.collections15.Transformer#transform(java.lang.Object)
*/
@Override
public S transform(T typeBasedSpec) {
Architecture<Resource, Link> architecture = generateArchitecture(typeBasedSpec.getResourceTypes(),
typeBasedSpec.getLinkTypes());
Mappings<Task, Resource> archMappings = generateMappings(typeBasedSpec.getMappings(), architecture);
return (S) new Specification(typeBasedSpec.getApplication(), architecture, archMappings);
}
/**
* Creates a default architecture from {@link ResourceTypes} and
* {@link LinkTypes} by connecting one resource of each type to an on-chip
* bus with a link from the {@link LinkTypes}.
*
* @param resourceTypes
* the {@link ResourceTypes}
* @param linkTypes
* the {@link LinkTypes}
* @return the architecture
*/
protected Architecture<Resource, Link> generateArchitecture(ResourceTypes<Resource> resourceTypes,
LinkTypes<?> linkTypes) {
Architecture<Resource, Link> architecture = new Architecture<Resource, Link>();
Link linkType = linkTypes.values().iterator().next();
// on-chip bus
Resource bus = new Resource("bus");
for (Resource type : resourceTypes.values()) {
Resource instance = new Resource("r" + CONNECTOR + type.getId());
Attributes attributes = type.getAttributes();
for (String key : attributes.keySet()) {
instance.setAttribute(key, attributes.getAttribute(key));
}
instance.setType(type.getId());
Link link = new Link("l" + CONNECTOR + type.getId());
Attributes linkAttributes = linkType.getAttributes();
for (String key : linkAttributes.keySet()) {
link.setAttribute(key, linkAttributes.getAttribute(key));
}
architecture.addVertex(instance);
architecture.addEdge(link, instance, bus);
}
return architecture;
}
/**
* Create concrete {@link Mappings} from the type-based mappings in the
* {@link SpecificationTypeBased}.
*
* @param typeMappings
* the type-based mappings from the
* {@link SpecificationTypeBased}
* @param architecture
* the concrete architecture
* @return the mappings
*/
protected Mappings<Task, Resource> generateMappings(Mappings<Task, Resource> typeMappings,
Architecture<Resource, Link> architecture) {
Mappings<Task, Resource> mappings = new Mappings<Task, Resource>();
// generate concrete mappings from type-mappings
for (Mapping<Task, Resource> typeMapping : typeMappings) {
Task source = typeMapping.getSource();
Resource target = typeMapping.getTarget();
Resource instance = architecture.getVertex("r" + CONNECTOR + target.getId());
Mapping<Task, Resource> mapping = new Mapping<Task, Resource>(
"m" + source.getId() + CONNECTOR + instance.getId(), source, instance);
Attributes attributes = typeMapping.getAttributes();
for (String key : attributes.keySet()) {
mapping.setAttribute(key, attributes.getAttribute(key));
}
mappings.add(mapping);
}
return mappings;
}
}
|
92330f6db7058ad504bc559a78625d25b672de65 | 403 | java | Java | rts/src/main/java/eta/runtime/thunk/SelectorLUpd.java | mmisamore/eta | 43ffe2e17cf41d2e11df5e1fd1300e4ee39c1654 | [
"BSD-3-Clause"
] | null | null | null | rts/src/main/java/eta/runtime/thunk/SelectorLUpd.java | mmisamore/eta | 43ffe2e17cf41d2e11df5e1fd1300e4ee39c1654 | [
"BSD-3-Clause"
] | null | null | null | rts/src/main/java/eta/runtime/thunk/SelectorLUpd.java | mmisamore/eta | 43ffe2e17cf41d2e11df5e1fd1300e4ee39c1654 | [
"BSD-3-Clause"
] | null | null | null | 20.15 | 68 | 0.687345 | 996,450 | package eta.runtime.thunk;
import eta.runtime.stg.Closure;
import eta.runtime.stg.StgContext;
import eta.runtime.stg.DataCon;
public class SelectorLUpd extends SelectorUpd {
public SelectorLUpd(int i, Closure p) {
super(i, p);
}
@Override
public Closure selectEnter(StgContext context, DataCon result) {
context.L1 = result.getL(index);
return null;
}
}
|
923310d3619b67437f41fd77c680f70b15d3eea0 | 2,029 | java | Java | src/xml/model_factories/SimulationSettingsFactory.java | matthewfaw/cellsociety_team24 | d140954afeb63d65eebc51626c2ce665a2854cba | [
"MIT"
] | null | null | null | src/xml/model_factories/SimulationSettingsFactory.java | matthewfaw/cellsociety_team24 | d140954afeb63d65eebc51626c2ce665a2854cba | [
"MIT"
] | null | null | null | src/xml/model_factories/SimulationSettingsFactory.java | matthewfaw/cellsociety_team24 | d140954afeb63d65eebc51626c2ce665a2854cba | [
"MIT"
] | null | null | null | 34.389831 | 138 | 0.791523 | 996,451 | package xml.model_factories;
import models.settings.SimulationSettings;
import resources.ResourceBundleHandler;
import xml.XMLFactory;
/**
* A class to deal with creating simulation settings from XML
*
* This class will fail if the resource file does not exist and if an XML element cannot be found.
*
* This class depends on the ResourceBundleHandler class, and on the XML reader
*
* To instantiate SimulationSettingsFactory:
* SimulationSettingsFactory ssf = new SimulationSettingsFactory("/path/to/xml/folder/simulation_config/simulation_name_simulation.xml");
* To create SimulationSettings object:
* SimulationSettings s = ssf.createSimulationSettings();
*
* @author matthewfaw
*
*/
public class SimulationSettingsFactory extends XMLFactory {
private static final String RESOURCE_PATH = "resources/SimulationSettings";
private SimulationSettings fSimulationSettings;
private ResourceBundleHandler fResourceBundleHandler;
public SimulationSettingsFactory(String aXmlFileName)
{
super(aXmlFileName);
fResourceBundleHandler = new ResourceBundleHandler(RESOURCE_PATH);
}
/**
* Creates SimulationSettings object
* Errors if XML element cannot be found
* @return
*/
public SimulationSettings createSimulationSettings()
{
String name = super.getXmlReader().getTextValue(fResourceBundleHandler.getResource("SimulationName"));
String title = super.getXmlReader().getTextValue(fResourceBundleHandler.getResource("SimulationTitle"));
String author = super.getXmlReader().getTextValue(fResourceBundleHandler.getResource("SimulationAuthor"));
double speed = Double.parseDouble(super.getXmlReader().getTextValue(fResourceBundleHandler.getResource("SimulationSpeed")));
fSimulationSettings = new SimulationSettings(name, title, author, speed);
return fSimulationSettings;
}
// public static void main(String[] args)
// {
// SimulationSettingsFactory f = new SimulationSettingsFactory("simulation_config/test_simulation.xml");
// f.createSimulationSettings();
// }
}
|
9233114be439734ec53d02c5a84955e3a1a2156e | 1,287 | java | Java | dbsvc/src/main/test/com/emc/storageos/db/server/upgrade/impl/DbStepUpgradeTest.java | CoprHD/sds-controller | a575ec96928b1e9258313efe92c930bfe9d6753a | [
"Apache-2.0"
] | 91 | 2015-06-06T01:40:34.000Z | 2020-11-24T07:26:40.000Z | dbsvc/src/main/test/com/emc/storageos/db/server/upgrade/impl/DbStepUpgradeTest.java | CoprHD/sds-controller | a575ec96928b1e9258313efe92c930bfe9d6753a | [
"Apache-2.0"
] | 3 | 2015-07-14T18:47:53.000Z | 2015-07-14T18:50:16.000Z | dbsvc/src/main/test/com/emc/storageos/db/server/upgrade/impl/DbStepUpgradeTest.java | CoprHD/sds-controller | a575ec96928b1e9258313efe92c930bfe9d6753a | [
"Apache-2.0"
] | 71 | 2015-06-05T21:35:31.000Z | 2021-11-07T16:32:46.000Z | 33.868421 | 119 | 0.721057 | 996,452 | /*
* Copyright (c) 2008-2013 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.db.server.upgrade.impl;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.emc.storageos.db.server.upgrade.DbStepSkipUpgradeTestBase;
/**
* tests default/custom migration callbacks in step upgrade scenario
*/
public class DbStepUpgradeTest extends DbStepSkipUpgradeTestBase {
private static final Logger log = LoggerFactory.getLogger(DbStepUpgradeTest.class);
@Test
public void runStepUpgradeTest() throws Exception {
stopAll();
setupDB(initalVersion, initalVersion, "com.emc.storageos.db.server.upgrade.util.models.old");
prepareData1();
stopAll();
setupDB(initalVersion,firstUpgradeVersion, "com.emc.storageos.db.server.upgrade.util.models.updated");
// restart with same version
stopAll();
setupDB(firstUpgradeVersion, firstUpgradeVersion, "com.emc.storageos.db.server.upgrade.util.models.updated");
firstUpgradeVerifyResults();
prepareData2();
stopAll();
setupDB(firstUpgradeVersion, secondUpgradeVersion, "com.emc.storageos.db.server.upgrade.util.models.updated2");
secondUpgradeVerifyResults();
stop();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.