hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
b49f01880035604033311d0224a9918ac7fcdf87
| 2,708
|
package io.github.xuyao5.dkl.eskits.helper;
/**
* @author Thomas.XU(xuyao)
* @version 5/07/20 18:55
*/
public final class SnowflakeHelper {
/**
* 起始的时间戳
*/
private final static long START_STAMP = 1480166465631L;
/**
* 每一部分占用的位数
*/
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 5; //机器标识占用的位数
private final static long DATACENTER_BIT = 5;//数据中心占用的位数
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private final long datacenterId; //数据中心
private final long machineId; //机器标识
private long sequence = 0L; //序列号
private long lastStamp = -1L;//上一次时间戳
public SnowflakeHelper(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
public synchronized long nextId() {
long currStamp = System.currentTimeMillis();
if (currStamp < lastStamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStamp == lastStamp) {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
currStamp = getNextMill();
}
} else {
//不同毫秒内,序列号置为0
sequence = 0L;
}
lastStamp = currStamp;
return (currStamp - START_STAMP) << TIMESTAMP_LEFT //时间戳部分
| datacenterId << DATACENTER_LEFT //数据中心部分
| machineId << MACHINE_LEFT //机器标识部分
| sequence; //序列号部分
}
private long getNextMill() {
long mill = System.currentTimeMillis();
while (mill <= lastStamp) {
mill = System.currentTimeMillis();
}
return mill;
}
}
| 32.626506
| 119
| 0.601182
|
4c2c4677da86204994b171187607c819b10d244d
| 7,541
|
/**
* Copyright (C) 2011-2015 The XDocReport Team <xdocreport@googlegroups.com>
*
* All rights reserved.
*
* 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* SettingsDialog.java
*
* Created on 9 f�vr. 2012, 16:19:52
*/
package fr.opensagres.xdocreport.gui;
import java.io.File;
import javax.swing.JFileChooser;
/**
*
* @author pascalleclercq
*/
public class SettingsDialog extends javax.swing.JDialog {
/** Creates new form SettingsDialog */
public SettingsDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
fieldsXmlFolderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
JFileChooser fieldsXmlFolderChooser = new JFileChooser();
private File fieldsXmlFolder;
/** 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() {
fieldsXmlPanel = new javax.swing.JPanel();
fieldsXmlLbl = new javax.swing.JLabel();
fieldsXmlTxt = new javax.swing.JTextField();
fieldsXmlBrowseBtn = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
shellLbl = new javax.swing.JLabel();
shellTxt = new javax.swing.JTextField();
shellBrowseBtn = new javax.swing.JButton();
cancenBtn = new javax.swing.JButton();
okBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setBounds(new java.awt.Rectangle(0, 0, 300, 200));
getContentPane().setLayout(null);
fieldsXmlPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
fieldsXmlPanel.setPreferredSize(new java.awt.Dimension(300, 110));
fieldsXmlPanel.setLayout(null);
fieldsXmlLbl.setText("Directory (*.fields.xml)");
fieldsXmlLbl.setPreferredSize(new java.awt.Dimension(150, 16));
fieldsXmlPanel.add(fieldsXmlLbl);
fieldsXmlLbl.setBounds(10, 20, 150, 16);
fieldsXmlPanel.add(fieldsXmlTxt);
fieldsXmlTxt.setBounds(160, 10, 290, 28);
fieldsXmlBrowseBtn.setText("Browse...");
fieldsXmlBrowseBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fieldsXmlBrowseBtnActionPerformed(evt);
}
});
fieldsXmlPanel.add(fieldsXmlBrowseBtn);
fieldsXmlBrowseBtn.setBounds(460, 10, 100, 29);
getContentPane().add(fieldsXmlPanel);
fieldsXmlPanel.setBounds(0, 60, 560, 50);
jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED, null, java.awt.Color.white, null, null));
jPanel1.setPreferredSize(new java.awt.Dimension(300, 110));
jPanel1.setLayout(null);
shellLbl.setText("File (xdrtools.bat)");
shellLbl.setPreferredSize(new java.awt.Dimension(150, 16));
jPanel1.add(shellLbl);
shellLbl.setBounds(10, 20, 150, 16);
jPanel1.add(shellTxt);
shellTxt.setBounds(150, 10, 300, 28);
shellBrowseBtn.setText("Browse...");
shellBrowseBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
shellBrowseBtnActionPerformed(evt);
}
});
jPanel1.add(shellBrowseBtn);
shellBrowseBtn.setBounds(460, 10, 100, 29);
getContentPane().add(jPanel1);
jPanel1.setBounds(0, 0, 560, 60);
cancenBtn.setText("Cancel");
cancenBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancenBtnActionPerformed(evt);
}
});
getContentPane().add(cancenBtn);
cancenBtn.setBounds(460, 120, 86, 29);
okBtn.setText("Ok");
getContentPane().add(okBtn);
okBtn.setBounds(380, 120, 75, 29);
pack();
}// </editor-fold>//GEN-END:initComponents
private void fieldsXmlBrowseBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldsXmlBrowseBtnActionPerformed
int result = fieldsXmlFolderChooser.showOpenDialog(null);
System.out.println("result "+result);
fieldsXmlFolder=fieldsXmlFolderChooser.getSelectedFile();
fieldsXmlTxt.setText(fieldsXmlFolder.getPath());
}//GEN-LAST:event_fieldsXmlBrowseBtnActionPerformed
private void shellBrowseBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_shellBrowseBtnActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_shellBrowseBtnActionPerformed
private void cancenBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancenBtnActionPerformed
setVisible(false);
}//GEN-LAST:event_cancenBtnActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SettingsDialog dialog = new SettingsDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
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.JButton cancenBtn;
private javax.swing.JButton fieldsXmlBrowseBtn;
private javax.swing.JLabel fieldsXmlLbl;
private javax.swing.JPanel fieldsXmlPanel;
private javax.swing.JTextField fieldsXmlTxt;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton okBtn;
private javax.swing.JButton shellBrowseBtn;
private javax.swing.JLabel shellLbl;
private javax.swing.JTextField shellTxt;
// End of variables declaration//GEN-END:variables
}
| 39.072539
| 145
| 0.680679
|
c2a031711d99c2d3a52b73420ce4e0a57bc73eec
| 4,632
|
/*
* 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.google.api.server.spi.tools;
import static com.google.api.server.spi.tools.LocalClientLibGenerator.GENERATOR_EXECUTABLE;
import java.io.File;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import com.google.api.server.spi.IoUtil;
import com.google.api.server.spi.tools.testing.FakeClientLibGenerator;
public class LocalClientLibGeneratorTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
private LocalClientLibGenerator generator;
private String discoveryDoc;
@Before
public void init() throws Exception {
generator = new LocalClientLibGenerator();
discoveryDoc = IoUtil.readStream(FakeClientLibGenerator.class.getResourceAsStream("fake-discovery-doc-rest.json"));
}
@Test
public void testJavaCodeGeneration() throws Exception {
if (isTestIgnored()) {
return;
}
File destinationDir = tmpFolder.newFolder("destination");
generator.generateClientLib(discoveryDoc, "java", null, null, destinationDir);
File com = new File(destinationDir, "com");
Assert.assertTrue(com.isDirectory());
File google = new File(com, "google");
Assert.assertTrue(google.isDirectory());
File guestbook = new File(google, "guestbook");
Assert.assertTrue(guestbook.isDirectory());
File v1 = new File(guestbook, "v1");
Assert.assertTrue(guestbook.isDirectory());
File model = new File(v1, "model");
Assert.assertTrue(model.isDirectory());
File guestbookJava = new File(v1, "Guestbook.java");
Assert.assertTrue(guestbookJava.isFile());
File guestbookRequestJava = new File(v1, "GuestbookRequest.java");
Assert.assertTrue(guestbookRequestJava.isFile());
File guestbookRequestInitializerJava = new File(v1, "GuestbookRequestInitializer.java");
Assert.assertTrue(guestbookRequestInitializerJava.isFile());
File greetingJava = new File(model, "Greeting.java");
Assert.assertTrue(greetingJava.isFile());
}
@Test
public void testDestinationDirectoryCreation() throws Exception {
if (isTestIgnored()) {
return;
}
File destinationParent = tmpFolder.newFolder("destination");
File dir1 = new File(destinationParent, "d1");
File destinationDir = new File(dir1, "d2");
Assert.assertFalse(dir1.exists());
Assert.assertFalse(destinationDir.exists());
generator.generateClientLib(discoveryDoc, "java", null, null, destinationDir);
Assert.assertTrue(dir1.exists());
Assert.assertTrue(destinationDir.exists());
}
@Test
public void testInvalidDiscoveryFile_fails() throws Exception {
if (isTestIgnored()) {
return;
}
expectedException.expect(IOException.class);
discoveryDoc = IoUtil.readStream(FakeClientLibGenerator.class.getResourceAsStream("fake-api-config.json"));
File destinationDir = tmpFolder.newFolder("destination");
generator.generateClientLib(discoveryDoc, "java", null, null, destinationDir);
}
@Test
public void testDestinationIsFile_fails() throws Exception {
if (isTestIgnored()) {
return;
}
expectedException.expect(IOException.class);
File destinationFile = tmpFolder.newFile("destination");
generator.generateClientLib(discoveryDoc, "java", null, null, destinationFile);
}
@Test
public void testLanguageUnsupported() throws Exception {
if (isTestIgnored()) {
return;
}
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Unsupported language: python");
generator.generateClientLib(discoveryDoc, "python", null, null, tmpFolder.getRoot());
}
/**
* Ignore the test if the generator isn't installed.
*/
private boolean isTestIgnored() {
try {
Runtime.getRuntime().exec(GENERATOR_EXECUTABLE);
return false;
} catch (IOException e) {
return true;
}
}
}
| 33.085714
| 119
| 0.731434
|
5b2bb9a77142d6cc2be1acea250a4c93f3f0ef45
| 412
|
package com.surgical.decision3.panel;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Nattapon on 23/5/2560.
*/
public class UnityCommActivity extends AppCompatActivity
{
// @Override
// protected void onCreate(Bundle savedInstanceState)
// {
// super.onCreate( savedInstanceState );
// setContentView( com.surgical.decision.R.layout.activity_unitycomm );
// }
}
| 22.888889
| 78
| 0.713592
|
7e06db63dc597f66c386d8dc82910b68f4bde1a0
| 2,182
|
package com.github.wglanzer.annosave.impl.structure;
import com.github.wglanzer.annosave.api.*;
import com.github.wglanzer.annosave.impl.util.TypeFactory;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author W.Glanzer, 13.09.2017
*/
public class SAnnotationParameter implements IAnnotationParameter
{
private String name;
private SType type;
private Object value; //ignored in Json
private Object originalValue;
@Override
public String getName()
{
return name;
}
@NotNull
@Override
public IType getType()
{
return type;
}
@Override
public Object getValue()
{
if(value == null)
{
if (originalValue instanceof String && Class.class.equals(type.getInstance()))
{
value = TypeFactory.create(originalValue.toString()).getInstance();
}
else if ((originalValue instanceof Object[] && !(originalValue instanceof Class[])) &&
Class[].class.equals(type.getInstance()))
{
value = Arrays.stream((Object[]) originalValue)
.map(pObject -> TypeFactory.create(String.valueOf(pObject)).getInstance())
.toArray(Class[]::new);
}
else
value = originalValue;
}
return value;
}
public Object getOriginalValue()
{
return originalValue;
}
public void setName(String pName)
{
name = pName;
}
public void setType(SType pType)
{
type = pType;
}
public void setOriginalValue(Object pOriginalValue)
{
originalValue = pOriginalValue;
}
@Override
public boolean equals(Object pO)
{
if (this == pO) return true;
if (pO == null || getClass() != pO.getClass()) return false;
SAnnotationParameter that = (SAnnotationParameter) pO;
return Objects.equals(name, that.name) &&
Objects.equals(type, that.type) &&
(type.isArray() ?
Arrays.equals((Object[]) originalValue, (Object[]) that.originalValue) :
Objects.equals(originalValue, that.originalValue));
}
@Override
public int hashCode()
{
return Arrays.deepHashCode(new Object[]{type, name, type.isArray() ? (Object[]) originalValue : originalValue});
}
}
| 22.968421
| 116
| 0.653071
|
b2939e11a5923ab837de1815014e7a02281a6b9f
| 9,302
|
package sylvartore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class AI {
private int[] visited;
public AI() {
visited = new int[9];
}
public int[] getBestMove(GameState state, int[][] cardAttributes) {
int max = -5;
int bestMoveCardIndex = -1;
int bestMoveTileIndex = -1;
Arrays.fill(visited, 0);
int side = state.current;
for (Integer[] move : getAllMoves(state)) {
ArrayList<int[]> operations = getOperations(move[0], move[1], state, cardAttributes);
stateTransition(operations, state);
int utility = min(state, -5, 5, side, cardAttributes);
stateRollback(operations, state);
if (max == -5 || utility > max) {
max = utility;
bestMoveCardIndex = move[0];
bestMoveTileIndex = move[1];
}
}
return new int[] {max, bestMoveCardIndex, bestMoveTileIndex};
}
private ArrayList<int[]> getOperations(int cardIndex, int tileIndex, GameState state, int[][] cardAttributes) {
ArrayList<int[]> operations = new ArrayList<>();
operations.add(new int[]{0, cardIndex, tileIndex});
takeoverSettlement(cardIndex, tileIndex, state, cardAttributes, operations);
return operations;
}
private void takeoverSettlement(int cardIndex, int tileIndex, GameState state, int[][] cardAttributes, ArrayList<int[]> operations) {
// rulePlus(cardIndex, tileIndex, state, cardAttributes, operations);
ruleSame(cardIndex, tileIndex, state, cardAttributes, operations);
ruleBasic(cardIndex, tileIndex, state, cardAttributes, operations);
}
private void rulePlus(int cardIndex, int tileIndex, GameState state, int[][] cardAttributes, ArrayList<int[]> operations) {
HashMap<Integer, Integer[]> map = new HashMap<>();
Arrays.fill(visited, 0);
visited[tileIndex] = 1;
for (int direction = 0; direction < 4; direction++) {
int targetTileIndex = Get[direction][tileIndex];
if (targetTileIndex == -1) continue;
int targetCardIndex = state.tilesCard[targetTileIndex];
if (targetCardIndex == -1) continue;
int key = cardAttributes[cardIndex][direction] +
cardAttributes[targetCardIndex][Counter[direction]];
if (map.containsKey(key)) {
if (state.cardsOwner[targetCardIndex] != state.current) {
operations.add(new int[]{1, targetCardIndex, state.current});
combo(targetCardIndex, targetTileIndex, state, cardAttributes, operations);
}
Integer[] stored = map.get(key);
if (state.cardsOwner[stored[0]] != state.current) {
operations.add(new int[]{1, stored[0], state.current});
combo(stored[0], stored[1], state, cardAttributes, operations);
}
} else {
map.put(key, new Integer[]{targetCardIndex, targetTileIndex});
}
}
}
private void ruleSame(int cardIndex, int tileIndex, GameState state, int[][] cardAttributes, ArrayList<int[]> operations) {
ArrayList<int[]> list = new ArrayList<>();
Arrays.fill(visited, 0);
visited[tileIndex] = 1;
for (int direction = 0; direction < 4; direction++) {
int targetTileIndex = Get[direction][tileIndex];
if (targetTileIndex == -1) continue;
int targetCardIndex = state.tilesCard[targetTileIndex];
if (targetCardIndex == -1) continue;
if (cardAttributes[cardIndex][direction]
== cardAttributes[targetCardIndex][Counter[direction]]) {
list.add(new int[] {targetCardIndex, targetTileIndex, });
}
}
if(list.size() > 1) {
for(int[] indies : list ) {
if (state.cardsOwner[ indies[0]] != state.current) {
operations.add(new int[]{1, indies[0], state.current});
combo(indies[0], indies[1], state, cardAttributes, operations);
}
}
}
}
private void combo(int cardIndex, int tileIndex, GameState state, int[][] cardAttributes, ArrayList<int[]> operations) {
if (visited[tileIndex] == 1) return;
for (int direction = 0; direction < 4; direction++) {
int targetTileIndex = Get[direction][tileIndex];
if (targetTileIndex == -1) continue;
int targetCardIndex = state.tilesCard[targetTileIndex];
if (targetCardIndex == -1 || state.cardsOwner[targetCardIndex] == state.current) continue;
if (cardAttributes[cardIndex][direction] >
cardAttributes[targetCardIndex][Counter[direction]]) {
visited[tileIndex] = 1;
operations.add(new int[]{1, targetCardIndex, state.current});
combo(targetCardIndex, targetTileIndex, state, cardAttributes, operations);
}
}
}
private void ruleBasic(int cardIndex, int tileIndex, GameState state, int[][] cardAttributes, ArrayList<int[]> operations) {
for (int direction = 0; direction < 4; direction++) {
int targetTileIndex = Get[direction][tileIndex];
if (targetTileIndex == -1) continue;
int targetCardIndex = state.tilesCard[targetTileIndex];
if (targetCardIndex == -1 || state.cardsOwner[targetCardIndex] == state.current) continue;
if (cardAttributes[cardIndex][direction] >
cardAttributes[targetCardIndex][Counter[direction]]) {
operations.add(new int[]{1, targetCardIndex, state.current});
}
}
}
private void stateTransition(ArrayList<int[]> operations, GameState state) {
for (int[] operation : operations) {
if (operation[0] == 0) {
state.cardsTile[operation[1]] = operation[2];
state.tilesCard[operation[2]] = operation[1];
} else {
state.cardsOwner[operation[1]] = operation[2];
}
}
state.current = state.current == 1 ? 0 : 1;
}
private void stateRollback(ArrayList<int[]> operations, GameState state) {
for (int[] operation : operations) {
if (operation[0] == 0) {
state.cardsTile[operation[1]] = -1;
state.tilesCard[operation[2]] = -1;
} else {
state.cardsOwner[operation[1]] = operation[2] == 1 ? 0 : 1;
}
}
state.current = state.current == 1 ? 0 : 1;
}
private int min(GameState state, int alpha, int beta, int side, int[][] cardAttributes) {
if (terminateTest(state)) return evaluateScore(state, side);
int value = 5;
for (Integer[] move : getAllMoves(state)) {
ArrayList<int[]> operations = getOperations(move[0], move[1], state, cardAttributes);
stateTransition(operations, state);
int utility = max(state, alpha, beta, side, cardAttributes);
stateRollback(operations, state);
if (utility < value) value = utility;
if (utility <= alpha) return utility;
if (utility < beta) beta = utility;
}
return value;
}
private int max(GameState state, int alpha, int beta, int side, int[][] cardAttributes) {
if (terminateTest(state)) return evaluateScore(state, side);
int value = -5;
for (Integer[] move : getAllMoves(state)) {
ArrayList<int[]> operations = getOperations(move[0], move[1], state, cardAttributes);
stateTransition(operations, state);
int utility = min(state, alpha, beta, side, cardAttributes);
stateRollback(operations, state);
if (utility > value) value = utility;
if (utility >= beta) return utility;
if (utility > alpha) alpha = utility;
}
return value;
}
private ArrayList<Integer[]> getAllMoves(GameState state) {
ArrayList<Integer[]> res = new ArrayList<>();
for (int i = 0; i < 10; i++) {
if (state.cardsOwner[i] == state.current && state.cardsTile[i] == -1) {
for (int j = 0; j < 9; j++) {
if (state.tilesCard[j] == -1)
res.add(new Integer[]{i, j});
}
}
}
return res;
}
private boolean terminateTest(GameState state) {
for (int cardIndex : state.tilesCard) {
if (cardIndex == -1) return false;
}
return true;
}
private int evaluateScore(GameState state, int side) {
int score = -5;
for (int owner : state.cardsOwner) {
if (owner == side) score++;
}
return score;
}
public static final int[][] Get = new int[][]{
{-1, 0, 1, -1, 3, 4, -1, 6, 7},
{-1, -1, -1, 0, 1, 2, 3, 4, 5},
{1, 2, -1, 4, 5, -1, 7, 8, -1},
{3, 4, 5, 6, 7, 8, -1, -1, -1}};
public static final int[] Counter = new int[] {2, 3, 0, 1};
}
| 42.281818
| 138
| 0.563105
|
9fe4102565352c55fea6b7a7ca798eb9a4dbd30e
| 1,603
|
package org.interledger.codecs.ilp;
/*-
* ========================LICENSE_START=================================
* Interledger Core Codecs
* %%
* Copyright (C) 2017 - 2019 Hyperledger and its contributors
* %%
* 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.
* =========================LICENSE_END==================================
*/
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import org.interledger.core.InterledgerAddress;
import org.junit.Before;
import org.junit.Test;
/**
* Unit tests for {@link AsnInterledgerAddressCodec}.
*/
public class AsnInterledgerAddressCodecTest {
private static final String G_FOO = "g.foo";
private AsnInterledgerAddressCodec codec;
@Before
public void setUp() {
codec = new AsnInterledgerAddressCodec();
codec.setCharString(G_FOO);
}
@Test
public void decode() {
assertThat(codec.decode(), is(InterledgerAddress.of(G_FOO)));
}
@Test
public void encode() {
codec.encode(InterledgerAddress.of(G_FOO));
assertThat(codec.getCharString(), is(G_FOO));
}
}
| 28.625
| 75
| 0.67748
|
0091d02e4072dfda613510de56bc1dccdb6ddeb5
| 2,317
|
package seedu.weme.testutil;
import java.util.HashSet;
import java.util.Set;
import seedu.weme.model.meme.Description;
import seedu.weme.model.meme.Meme;
import seedu.weme.model.path.ImagePath;
import seedu.weme.model.tag.Tag;
import seedu.weme.model.util.SampleDataUtil;
/**
* A utility class to help with building Meme objects.
*/
public class MemeBuilder {
public static final String DEFAULT_DESCRIPTION = "Meme created for testing.";
public static final String DEFAULT_FILEPATH = "src/test/data/memes/test_meme.jpg";
private Description description;
private ImagePath filePath;
private Set<Tag> tags;
private boolean isArchived;
public MemeBuilder() {
filePath = new ImagePath(DEFAULT_FILEPATH);
description = new Description(DEFAULT_DESCRIPTION);
tags = new HashSet<>();
isArchived = false;
}
/**
* Initializes the MemeBuilder with the data of {@code memeToCopy}.
*/
public MemeBuilder(Meme memeToCopy) {
description = memeToCopy.getDescription();
filePath = memeToCopy.getImagePath();
tags = new HashSet<>(memeToCopy.getTags());
isArchived = false;
}
/**
* Parses the {@code tags} into a {@code Set<Tag>} and set it to the {@code Meme} that we are building.
*/
public MemeBuilder withTags(String... tags) {
this.tags = SampleDataUtil.getTagSet(tags);
return this;
}
/**
* Sets the {@code Description} of the {@code Meme} that we are building.
*
* @param description
*/
public MemeBuilder withDescription(String description) {
this.description = new Description(description);
return this;
}
/**
* Sets the {@code ImageUrl} of the {@code Meme} that we are building.
*
* @param filePath
*/
public MemeBuilder withFilePath(String filePath) {
this.filePath = new ImagePath(filePath);
return this;
}
/**
* Sets the {@code isArchived} of the {@code Meme} that we are building.
*
* @param isArchived
*/
public MemeBuilder withIsArchived(boolean isArchived) {
this.isArchived = isArchived;
return this;
}
public Meme build() {
return new Meme(filePath, description, tags, isArchived);
}
}
| 27.258824
| 107
| 0.648684
|
119e139adcfd7340aa5679fb5f914a724798b3cb
| 792
|
package de.tum.in.www1.jenkins.notifications.model;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import org.kohsuke.stapler.export.ExportedBean;
@ExportedBean(defaultVisibility = 4)
@XmlRootElement(name = "successInfo")
public class SuccessInfo {
private String message;
private String messageWithStackTrace;
private String type;
@XmlAttribute
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@XmlValue
public String getMessageWithStackTrace() {
return messageWithStackTrace;
}
@XmlAttribute
public String getType() {
return type;
}
}
| 20.842105
| 51
| 0.712121
|
707485c92bcd680828513fd08a1cb9e5a67d0b69
| 1,236
|
package org.batfish.representation.arista;
import java.util.List;
import java.util.Set;
import org.batfish.common.Warnings;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.routing_policy.expr.BooleanExpr;
import org.batfish.datamodel.routing_policy.expr.DestinationNetwork;
import org.batfish.datamodel.routing_policy.expr.Disjunction;
import org.batfish.datamodel.routing_policy.expr.MatchPrefixSet;
import org.batfish.datamodel.routing_policy.expr.NamedPrefixSet;
public class RouteMapMatchIpPrefixListLine extends RouteMapMatchLine {
private Set<String> _listNames;
public RouteMapMatchIpPrefixListLine(Set<String> names) {
_listNames = names;
}
public Set<String> getListNames() {
return _listNames;
}
@Override
public BooleanExpr toBooleanExpr(Configuration c, AristaConfiguration cc, Warnings w) {
Disjunction d = new Disjunction();
List<BooleanExpr> disjuncts = d.getDisjuncts();
for (String listName : _listNames) {
PrefixList list = cc.getPrefixLists().get(listName);
if (list != null) {
disjuncts.add(
new MatchPrefixSet(DestinationNetwork.instance(), new NamedPrefixSet(listName)));
}
}
return d.simplify();
}
}
| 31.692308
| 93
| 0.7589
|
11166c5f0096a5a75b21695ebdafcd387ebcc436
| 7,096
|
/**
* Copyright © 2013-2021 The OpenNTF Domino API Team
*
* 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.domino.graph2.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
public class DEdgeList implements org.openntf.domino.graph2.DEdgeList, Iterable<Edge> {
@SuppressWarnings("unused")
private static final long serialVersionUID = 1L;
protected final DVertex sourceVertex_;
protected List<Edge> delegate_;
protected boolean isUnique_;
protected String label_;
private DEdgeList(final DVertex source, final List<Edge> list) {
sourceVertex_ = source;
delegate_ = list;
}
public DEdgeList(final DVertex source) {
sourceVertex_ = source;
delegate_ = new ArrayList<Edge>();
}
/* (non-Javadoc)
* @see org.openntf.domino.graph2.impl.IEdgeList#atomic()
*/
@Override
public DEdgeList atomic() {
return this;
// return new DEdgeList(sourceVertex_, new AtomicTableImpl<Edge>(service()));
}
/* (non-Javadoc)
* @see org.openntf.domino.graph2.impl.IEdgeList#unmodifiable()
*/
@Override
public DEdgeList unmodifiable() {
return this;
// return new DEdgeList(sourceVertex_, new UnmodifiableTableImpl<Edge>(service()));
}
/* (non-Javadoc)
* @see org.openntf.domino.graph2.impl.IEdgeList#findEdge(com.tinkerpop.blueprints.Vertex)
*/
@Override
public Edge findEdge(final Vertex toVertex) {
Edge result = null;
Object toId = toVertex.getId();
Object fromId = sourceVertex_.getId();
if (this.size() > 0) {
for (Edge edge : this) {
if (edge instanceof DEdge) {
DEdge dedge = (DEdge) edge;
if (toId.equals(dedge.getOtherVertexId(sourceVertex_))) {
result = dedge;
break;
}
} else {
Vertex inVertex = edge.getVertex(Direction.IN);
if (fromId.equals(inVertex.getId())) {
if (toId.equals(edge.getVertex(Direction.OUT))) {
result = edge;
break;
}
} else if (toId.equals(inVertex.getId())) {
result = edge;
break;
}
}
}
} else {
// System.out.println("DEBUG: No edges defined in EdgeList");
}
return result;
}
/* (non-Javadoc)
* @see org.openntf.domino.graph2.impl.IEdgeList#applyFilter(java.lang.String, java.lang.Object)
*/
@Override
public DEdgeList applyFilter(final String key, final Object value) {
DEdgeList result = new DEdgeList(sourceVertex_);
if (this.size() > 0) {
for (Edge edge : this) {
if (edge instanceof DEdge) {
DEdge dedge = (DEdge) edge;
if (value.equals(dedge.getProperty(key))) {
result.add(edge);
}
}
}
}
return result;
}
/* (non-Javadoc)
* @see org.openntf.domino.graph2.impl.IEdgeList#toVertexList()
*/
@Override
public DVertexList toVertexList() {
// System.out.println("TEMP DEBUG Converting an edge list to a vertex list");
DVertexList result = new DVertexList(sourceVertex_);
if (this.size() > 0) {
for (Edge edge : this) {
if (edge instanceof DEdge) {
DEdge dedge = (DEdge) edge;
try {
DVertex vert = (DVertex) dedge.getOtherVertex(sourceVertex_);
result.add(vert);
} catch (Throwable t) {
t.printStackTrace();
}
} else {
System.out.println("TEMP DEBUG EdgeList didn't have a DEdge. It had a " + edge.getClass().getName()); //$NON-NLS-1$
}
}
} else {
// System.out.println("TEMP DEBUG EdgeList size is not greater than 0.");
}
return result;
}
@Override
public boolean add(final Edge e) {
if (!delegate_.contains(e)) {
// System.out.println("TEMP DEBUG Adding Edge id " + e.getId());
return delegate_.add(e);
} else {
// System.out.println("TEMP DEBUG Edge id " + e.getId() + " already in list");
return false;
}
}
@Override
public void add(final int index, final Edge element) {
delegate_.add(index, element);
}
@Override
public boolean addAll(final Collection<? extends Edge> c) {
return delegate_.addAll(c);
}
@Override
public boolean addAll(final int index, final Collection<? extends Edge> c) {
return delegate_.addAll(index, c);
}
@Override
public void clear() {
delegate_.clear();
}
@Override
public boolean contains(final Object o) {
return delegate_.contains(o);
}
@Override
public boolean containsAll(final Collection<?> c) {
return delegate_.containsAll(c);
}
@Override
public Edge get(final int index) {
return delegate_.get(index);
}
@Override
public int indexOf(final Object o) {
return delegate_.indexOf(o);
}
@Override
public boolean isEmpty() {
return delegate_.isEmpty();
}
@Override
public Iterator<Edge> iterator() {
return delegate_.iterator();
}
@Override
public int lastIndexOf(final Object o) {
return delegate_.lastIndexOf(o);
}
@Override
public ListIterator<Edge> listIterator() {
return delegate_.listIterator();
}
@Override
public ListIterator<Edge> listIterator(final int index) {
return delegate_.listIterator(index);
}
@Override
public Edge remove(final int index) {
return delegate_.remove(index);
}
@Override
public boolean remove(final Object o) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean removeAll(final Collection<?> c) {
return delegate_.removeAll(c);
}
@Override
public boolean retainAll(final Collection<?> c) {
return delegate_.retainAll(c);
}
@Override
public Edge set(final int index, final Edge element) {
return delegate_.set(index, element);
}
@Override
public int size() {
return delegate_.size();
}
@Override
public List<Edge> subList(final int fromIndex, final int toIndex) {
return new DEdgeList(sourceVertex_, delegate_.subList(fromIndex, toIndex));
}
@Override
public Object[] toArray() {
return delegate_.toArray();
}
@Override
public <T> T[] toArray(final T[] a) {
return delegate_.toArray(a);
}
@Override
public boolean isUnique() {
return isUnique_;
}
@Override
public void setUnique(final boolean isUnique) {
isUnique_ = isUnique;
}
@Override
public String getLabel() {
return label_;
}
@Override
public void setLabel(final String label) {
label_ = label;
}
}
| 24.638889
| 121
| 0.660513
|
f695152b36b1a4627c237288a348a9521d2c2328
| 12,660
|
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.sesame.marketdata.scenarios;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.analytics.ShiftType;
/**
* Perturbation that applies a shift to an FX rate.
* <p>
* Shifts can be absolute or relative. An absolute shift adds the shift amount to the rate. Relative shifts
* are defined in terms of how much to increase or decrease the rate by. e.g. a 10% shift multiplies the rate
* by 1.1, a -20% shift multiplies the rate by 0.8. So for relative shifts the shifted
* rate is {@code (rate x (1 + shiftAmount))}.
* <p>
* Inverse rates are handled correctly if the
* {@link CurrencyPairMatchDetails match details} indicate the matching rate was the inverse of the rate for which
* the filter was defined.
*/
@BeanDefinition
public final class FxRateShift implements Perturbation, ImmutableBean {
/** The amount of the shift. */
@PropertyDefinition
private final double _shiftAmount;
/** The type of shift. */
@PropertyDefinition(validate = "notNull")
private final ShiftType _shiftType;
/**
* Creates an absolute shift. The shift amount is added to the underlying FX rate.
*
* @param shiftAmount the amount added to the underlying FX rate
* @return a shift that adds the {@code shiftAmount} to the underlying FX rate
*/
public static FxRateShift absolute(double shiftAmount) {
return new FxRateShift(shiftAmount, ShiftType.ABSOLUTE);
}
/**
* Creates a relative shift that scales the underlying FX rate.
* <p>
* Relative shifts are defined in terms of how much to increase or decrease the rate by. e.g. a 10% shift (0.1)
* multiplies the rate by 1.1, a -20% shift (-0.2) multiplies the rate by 0.8. So for relative shifts the shifted
* rate is {@code (rate x (1 + shiftAmount))}.
*
* @param shiftAmount the amount to scale the rate by
* @return a shift that scales the underlying FX rate by the {@code shiftAmount}
*/
public static FxRateShift relative(double shiftAmount) {
return new FxRateShift(shiftAmount, ShiftType.RELATIVE);
}
@Override
public Object apply(Object marketData, MatchDetails matchDetails) {
double rate = (double) marketData;
CurrencyPairMatchDetails pairMatchDetails = (CurrencyPairMatchDetails) matchDetails;
if (pairMatchDetails.isInverse()) {
return 1 / _shiftType.applyShift(1 / rate, _shiftAmount);
} else {
return _shiftType.applyShift(rate, _shiftAmount);
}
}
@Override
public Class<Double> getMarketDataType() {
return Double.class;
}
@Override
public Class<? extends MatchDetails> getMatchDetailsType() {
return CurrencyPairMatchDetails.class;
}
@Override
public PerturbationTarget getTargetType() {
return PerturbationTarget.INPUT;
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code FxRateShift}.
* @return the meta-bean, not null
*/
public static FxRateShift.Meta meta() {
return FxRateShift.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(FxRateShift.Meta.INSTANCE);
}
/**
* Returns a builder used to create an instance of the bean.
* @return the builder, not null
*/
public static FxRateShift.Builder builder() {
return new FxRateShift.Builder();
}
private FxRateShift(
double shiftAmount,
ShiftType shiftType) {
JodaBeanUtils.notNull(shiftType, "shiftType");
this._shiftAmount = shiftAmount;
this._shiftType = shiftType;
}
@Override
public FxRateShift.Meta metaBean() {
return FxRateShift.Meta.INSTANCE;
}
@Override
public <R> Property<R> property(String propertyName) {
return metaBean().<R>metaProperty(propertyName).createProperty(this);
}
@Override
public Set<String> propertyNames() {
return metaBean().metaPropertyMap().keySet();
}
//-----------------------------------------------------------------------
/**
* Gets the amount of the shift.
* @return the value of the property
*/
public double getShiftAmount() {
return _shiftAmount;
}
//-----------------------------------------------------------------------
/**
* Gets the type of shift.
* @return the value of the property, not null
*/
public ShiftType getShiftType() {
return _shiftType;
}
//-----------------------------------------------------------------------
/**
* Returns a builder that allows this bean to be mutated.
* @return the mutable builder, not null
*/
public Builder toBuilder() {
return new Builder(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
FxRateShift other = (FxRateShift) obj;
return JodaBeanUtils.equal(getShiftAmount(), other.getShiftAmount()) &&
JodaBeanUtils.equal(getShiftType(), other.getShiftType());
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(getShiftAmount());
hash = hash * 31 + JodaBeanUtils.hashCode(getShiftType());
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(96);
buf.append("FxRateShift{");
buf.append("shiftAmount").append('=').append(getShiftAmount()).append(',').append(' ');
buf.append("shiftType").append('=').append(JodaBeanUtils.toString(getShiftType()));
buf.append('}');
return buf.toString();
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code FxRateShift}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code shiftAmount} property.
*/
private final MetaProperty<Double> _shiftAmount = DirectMetaProperty.ofImmutable(
this, "shiftAmount", FxRateShift.class, Double.TYPE);
/**
* The meta-property for the {@code shiftType} property.
*/
private final MetaProperty<ShiftType> _shiftType = DirectMetaProperty.ofImmutable(
this, "shiftType", FxRateShift.class, ShiftType.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"shiftAmount",
"shiftType");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -1043480710: // shiftAmount
return _shiftAmount;
case 893345500: // shiftType
return _shiftType;
}
return super.metaPropertyGet(propertyName);
}
@Override
public FxRateShift.Builder builder() {
return new FxRateShift.Builder();
}
@Override
public Class<? extends FxRateShift> beanType() {
return FxRateShift.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code shiftAmount} property.
* @return the meta-property, not null
*/
public MetaProperty<Double> shiftAmount() {
return _shiftAmount;
}
/**
* The meta-property for the {@code shiftType} property.
* @return the meta-property, not null
*/
public MetaProperty<ShiftType> shiftType() {
return _shiftType;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -1043480710: // shiftAmount
return ((FxRateShift) bean).getShiftAmount();
case 893345500: // shiftType
return ((FxRateShift) bean).getShiftType();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
//-----------------------------------------------------------------------
/**
* The bean-builder for {@code FxRateShift}.
*/
public static final class Builder extends DirectFieldsBeanBuilder<FxRateShift> {
private double _shiftAmount;
private ShiftType _shiftType;
/**
* Restricted constructor.
*/
private Builder() {
}
/**
* Restricted copy constructor.
* @param beanToCopy the bean to copy from, not null
*/
private Builder(FxRateShift beanToCopy) {
this._shiftAmount = beanToCopy.getShiftAmount();
this._shiftType = beanToCopy.getShiftType();
}
//-----------------------------------------------------------------------
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case -1043480710: // shiftAmount
return _shiftAmount;
case 893345500: // shiftType
return _shiftType;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case -1043480710: // shiftAmount
this._shiftAmount = (Double) newValue;
break;
case 893345500: // shiftType
this._shiftType = (ShiftType) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public Builder setString(String propertyName, String value) {
setString(meta().metaProperty(propertyName), value);
return this;
}
@Override
public Builder setString(MetaProperty<?> property, String value) {
super.setString(property, value);
return this;
}
@Override
public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
super.setAll(propertyValueMap);
return this;
}
@Override
public FxRateShift build() {
return new FxRateShift(
_shiftAmount,
_shiftType);
}
//-----------------------------------------------------------------------
/**
* Sets the {@code shiftAmount} property in the builder.
* @param shiftAmount the new value
* @return this, for chaining, not null
*/
public Builder shiftAmount(double shiftAmount) {
this._shiftAmount = shiftAmount;
return this;
}
/**
* Sets the {@code shiftType} property in the builder.
* @param shiftType the new value, not null
* @return this, for chaining, not null
*/
public Builder shiftType(ShiftType shiftType) {
JodaBeanUtils.notNull(shiftType, "shiftType");
this._shiftType = shiftType;
return this;
}
//-----------------------------------------------------------------------
@Override
public String toString() {
StringBuilder buf = new StringBuilder(96);
buf.append("FxRateShift.Builder{");
buf.append("shiftAmount").append('=').append(JodaBeanUtils.toString(_shiftAmount)).append(',').append(' ');
buf.append("shiftType").append('=').append(JodaBeanUtils.toString(_shiftType));
buf.append('}');
return buf.toString();
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| 29.858491
| 115
| 0.619668
|
316fa5f663ea44e9975497a1be4725a3f77f45d8
| 1,145
|
package com.javocode.autodeployer.deployment.domain.upload;
public class Application {
private String fullPathOfFile;
private String name;
private String ext;
private String dir;
public Application(String fullFilePath) {
this.fullPathOfFile = fullFilePath;
setUpFields();
}
public String getFullPathOfFile() {
return fullPathOfFile;
}
public String getName() {
return name;
}
public String getExt() {
return ext;
}
public String getDir() {
return dir;
}
private void setUpFields() {
String[] array = getFullPathOfFile().split("/");
String fullname = array[array.length - 1];
this.name = fullname.split("\\.")[0];
this.ext = "." + fullname.split("\\.")[1];
array[array.length - 1] = null;
this.dir = String.join("/", removeNullElements(array)) + "/";
}
private String[] removeNullElements(String[] arr) {
String[] nArr = new String[arr.length - 1];
for (int i = 0; i < nArr.length; i++) {
nArr[i] = arr[i];
}
return nArr;
}
}
| 24.361702
| 69
| 0.572926
|
abaabf1f49ed39c3972f29fa04a7597c6ca97046
| 2,736
|
package com.hfm.blocking;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.*;
/**
* @author hfm Email:hfming2016@163.com
* @version v 1.01
* @Description /**
* * 通道 channel 负责连接
* * java.io.channels.Channel 接口
* * |-- SelectableChannel 抽象类
* * |-- SocketChannel
* * |-- ServcrSocketChannel TCP
* * |-- DatagramChannel UDP
* *
* * |-- Pipe.SinkChannel
* * |-- Piep.SourceChannel
* @date 2020-05-05 21:21
*/
public class BlockingIOTest1 {
/**
* 客户端
*/
@Test
public void client() {
try (
// 1.获取通道
SocketChannel open = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8000));
// 建立本地文件的通道,将文件写出
FileInputStream fileInputStream = new FileInputStream("D:\\Code\\core-java\\nio\\Resources\\text.txt");
FileChannel fileChannel = fileInputStream.getChannel()
) {
// 2.创建缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (fileChannel.read(byteBuffer) != -1) {
// 缓冲区设置为读取状态
byteBuffer.flip();
// 通过网络 channeL 通道传递数据
open.write(byteBuffer);
byteBuffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 服务端
*/
@Test
public void service() {
try (
// 1.创建服务端通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 创建输出通道
FileChannel fileChannel = FileChannel.open(Paths.get("D:\\Code\\core-java\\nio\\Resources\\copy5.txt"), WRITE, READ, CREATE)
) {
// 2.绑定连接
serverSocketChannel.bind(new InetSocketAddress(8000));
// 3.获取客户端连接通道
SocketChannel accept = serverSocketChannel.accept();
// 4.创建缓冲区,用于存储数据
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (accept.read(byteBuffer) != -1) {
// 设置为读取数据模式
byteBuffer.flip();
// 将缓冲区的数据传入输出通道
fileChannel.write(byteBuffer);
byteBuffer.clear();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 31.448276
| 140
| 0.54057
|
716c1597140311979824aabfe25f47ca7fb31182
| 81
|
package xyz.dengjunbo.chapter2.controller;
public class CustomerEditServlet {
}
| 16.2
| 42
| 0.82716
|
52cfa20472a4c52f5d7d7a7f34f06a77cb8b1160
| 3,466
|
/*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.document;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URL;
import io.debezium.annotation.ThreadSafe;
/**
* Reads {@link Document} instances from a variety of input forms.
*
* @author Randall Hauch
*/
@ThreadSafe
public interface DocumentReader {
/**
* Get the default {@link DocumentReader} instance.
*
* @return the shared default reader instance; never null
*/
static DocumentReader defaultReader() {
return JacksonReader.DEFAULT_INSTANCE;
}
/**
* Get {@link DocumentReader} instance that returns fp numbers as text.
*
* @return the shared default reader instance; never null
*/
static DocumentReader floatNumbersAsTextReader() {
return JacksonReader.FLOAT_NUMBERS_AS_TEXT_INSTANCE;
}
/**
* Read a document from the supplied stream.
*
* @param jsonStream the input stream to be read; may not be null
* @return the document instance; never null
* @throws IOException if a document could not be read from the supplied stream
*/
Document read(InputStream jsonStream) throws IOException;
/**
* Read a document from the supplied {@link Reader}.
*
* @param jsonReader the reader to be read; may not be null
* @return the document instance; never null
* @throws IOException if a document could not be read from the supplied reader
*/
Document read(Reader jsonReader) throws IOException;
/**
* Read a document from the supplied JSON-formatted string.
*
* @param json the JSON string representation to be read; may not be null
* @return the document instance; never null
* @throws IOException if a document could not be read from the supplied string
*/
Document read(String json) throws IOException;
/**
* Read a document from the content at the given URL.
*
* @param jsonUrl the URL to the content that is to be read; may not be null
* @return the document instance; never null
* @throws IOException if a document could not be read from the supplied content
*/
default Document read(URL jsonUrl) throws IOException {
return read(jsonUrl.openStream());
}
/**
* Read a document from the supplied file.
*
* @param jsonFile the file to be read; may not be null
* @return the document instance; never null
* @throws IOException if a document could not be read from the supplied file
*/
default Document read(File jsonFile) throws IOException {
return read( new BufferedInputStream(new FileInputStream(jsonFile)) );
}
/**
* Read a document from the supplied bytes.
*
* @param rawBytes the UTF-8 bytes to be read; may not be null
* @return the document instance; never null
* @throws IOException if a document could not be read from the supplied bytes
*/
default Document read(byte[] rawBytes) throws IOException {
try (ByteArrayInputStream stream = new ByteArrayInputStream(rawBytes)) {
return DocumentReader.defaultReader().read(stream);
}
}
}
| 32.092593
| 114
| 0.684074
|
1949e124f4e6ca5934701ff3aa0207b4a6e76e83
| 4,462
|
package org.xtuml.bp.model.compare.providers.custom;
//=====================================================================
//
//File: $RCSfile: AssociationComparable.java,v $
//Version: $Revision: 1.2 $
//Modified: $Date: 2013/01/17 03:35:46 $
//
//(c) Copyright 2013-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// 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.
//=====================================================================
import java.util.UUID;
import org.xtuml.bp.core.ClassAsAssociatedOneSide_c;
import org.xtuml.bp.core.ClassAsAssociatedOtherSide_c;
import org.xtuml.bp.core.ClassAsSimpleFormalizer_c;
import org.xtuml.bp.core.ClassAsSimpleParticipant_c;
import org.xtuml.bp.core.Gd_c;
import org.xtuml.bp.core.common.NonRootModelElement;
import org.xtuml.bp.model.compare.providers.NonRootModelElementComparable;
public class AssociationSubtypeComparable extends NonRootModelElementComparable {
public AssociationSubtypeComparable(NonRootModelElement realElement) {
super(realElement, false);
}
@Override
public boolean treeItemEquals(Object other) {
if (!super.treeItemEquals(other)) {
if (other instanceof AssociationSubtypeComparable) {
AssociationSubtypeComparable assocComp = (AssociationSubtypeComparable) other;
NonRootModelElement otherAssociation = (NonRootModelElement) assocComp
.getRealElement();
NonRootModelElement thisAssociation = (NonRootModelElement) getRealElement();
UUID thisMsgId = getAssociationId(thisAssociation);
UUID otherMsgId = getAssociationId(otherAssociation);
UUID thisOirId = getObjectInAssociationId(thisAssociation);
UUID otherOirId = getObjectInAssociationId(otherAssociation);
return thisMsgId.equals(otherMsgId) && thisOirId.equals(otherOirId);
} else {
return false;
}
} else {
return true;
}
}
private UUID getObjectInAssociationId(NonRootModelElement association) {
UUID id = Gd_c.Null_unique_id();
if (association instanceof ClassAsSimpleParticipant_c) {
return ((ClassAsSimpleParticipant_c) association).getOir_id();
} else if (association instanceof ClassAsSimpleFormalizer_c) {
return ((ClassAsSimpleFormalizer_c) association).getOir_id();
} else if (association instanceof ClassAsAssociatedOneSide_c) {
return ((ClassAsAssociatedOneSide_c) association).getOir_id();
} else if (association instanceof ClassAsAssociatedOtherSide_c) {
return ((ClassAsAssociatedOtherSide_c) association).getOir_id();
}
return id;
}
private UUID getAssociationId(NonRootModelElement association) {
UUID id = Gd_c.Null_unique_id();
if (association instanceof ClassAsSimpleParticipant_c) {
return ((ClassAsSimpleParticipant_c) association).getRel_id();
} else if (association instanceof ClassAsSimpleFormalizer_c) {
return ((ClassAsSimpleFormalizer_c) association).getRel_id();
} else if (association instanceof ClassAsAssociatedOneSide_c) {
return ((ClassAsAssociatedOneSide_c) association).getRel_id();
} else if (association instanceof ClassAsAssociatedOtherSide_c) {
return ((ClassAsAssociatedOtherSide_c) association).getRel_id();
}
return id;
}
@Override
public boolean treeItemNameMatches(Object other) {
return true;
}
@Override
public boolean treeItemTypeEquals(Object other) {
return true;
}
@Override
public boolean treeItemValueEquals(Object other) {
return true;
}
/* (non-Javadoc)
* @see org.xtuml.bp.model.compare.providers.NonRootModelElementComparable#hashCode()
*/
@Override
public int hashCode() {
UUID associationId = getAssociationId((NonRootModelElement) getRealElement());
UUID objectId = getObjectInAssociationId((NonRootModelElement) getRealElement());
return associationId.hashCode() + objectId.hashCode();
}
}
| 38.8
| 87
| 0.715598
|
5663ed9ac46898c858d05b0540f802f1b19d797d
| 1,816
|
package org.springframework.lock;
public class DefaultLockInstance implements LockInstance {
private static final long serialVersionUID = -6163953506521564197L;
private final Object identifier;
private final String key;
public DefaultLockInstance(final String key, final Object identifier) {
super();
this.key = key;
this.identifier = identifier;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
DefaultLockInstance other = (DefaultLockInstance) obj;
if (identifier == null) {
if (other.identifier != null) {
return false;
}
} else if (!identifier.equals(other.identifier)) {
return false;
}
if (key == null) {
if (other.key != null) {
return false;
}
} else if (!key.equals(other.key)) {
return false;
}
return true;
}
@Override
public Object getIdentifier() {
return identifier;
}
@Override
public String getKey() {
return key;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result + (identifier == null ? 0
: identifier.hashCode());
result = prime
* result + (key == null ? 0
: key.hashCode());
return result;
}
@Override
public String toString() {
return new StringBuilder().append("DefaultLockInstance [").append(identifier).append("@").append(key).append("]")
.toString();
}
}
| 24.213333
| 119
| 0.534692
|
b75c596744c3f0745c830e2f1b826e9a52143f54
| 502
|
package pd_observer;
import java.util.ArrayList;
import java.util.List;
abstract public class Sujeto {
protected List<Observador> observadores = new ArrayList<>();
public void agrega(Observador observador) {
observadores.add(observador);
}
public void suprime(Observador observador){
observadores.remove(observador);
}
public void notifica(){
observadores.forEach(observador -> {
observador.actualiza();
});
}
}
| 20.916667
| 64
| 0.643426
|
1ccb73e891eda6638d058b96d276e63ad63e8713
| 973
|
package com.cute.xiaoy.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class UserDB extends SQLiteOpenHelper{
public UserDB(Context context) {
super(context, "UserDB.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table user(id integer primary key autoincrement,username varchar(100) not null,password varchar(100) not null," +
"sex varchar(10),age integer(3),createDate varchar(100),robotname varchar(100))");
db.execSQL("create table messageinfo(id integer primary key autoincrement," +
"user_id integer(10),msg varchar(500),name varchar(100),date varchar(20),type varchar(10))");
db.execSQL("alter table user add name varchar(100)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
}
}
| 32.433333
| 135
| 0.735868
|
c33f9a4aee4ade2964d71d7778734bb307d8b70f
| 1,653
|
package io.mateo.googleapisdemo.controller;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.drive.model.File;
import io.mateo.googleapisdemo.advice.GoogleApiClientExceptionHandler;
import io.mateo.googleapisdemo.service.GoogleDriveService;
import java.io.IOException;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/drive/files")
@RestController
public class GoogleDriveController {
private GoogleDriveService googleDriveService;
public GoogleDriveController(GoogleDriveService googleDriveService) {
this.googleDriveService = googleDriveService;
}
/**
* Retrieves a file's metadata by ID.
*
* @param fileId The ID of the file
* @return {@link File}
* @throws IOException when the Google API returned an error code; handled by {@link
* GoogleApiClientExceptionHandler#handleGoogleApiErrors(GoogleJsonResponseException)}.
*/
@GetMapping("/{fileId}")
public File getFileInfo(@PathVariable String fileId) throws IOException {
return googleDriveService.getFileMetaData(fileId);
}
/**
* Retrieves the raw file from Google Drive.
*
* @param fileId The ID of the file
* @return {@link File}
* @throws IOException when the Google API returned an error code; handled by {@link
* GoogleApiClientExceptionHandler#handleGoogleApiErrors(GoogleJsonResponseException)}.
*/
@GetMapping("/{fileId}/media")
@ResponseBody
public byte[] getFile(@PathVariable String fileId) throws IOException {
return googleDriveService.getFile(fileId);
}
}
| 35.934783
| 95
| 0.736237
|
de5664960f949203dc57335635a5a0bf27028831
| 4,260
|
package com.zj.musicplayer.view;
import java.awt.Dimension;
import java.awt.Toolkit;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.SWTResourceManager;
import com.zj.musicplayer.utils.ImageUtil;
import com.zj.musicplayer.utils.ReadAndWriteRegistery;
import com.zj.musicplayer.utils.StringUtil;
/**
*
* @description:设置界面
* @author ZJ
* @date 2020年5月3日 下午2:33:56
*/
public class SettingUi {
protected Shell shell;
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell(SWT.TITLE);
shell.setSize(525, 400);
shell.setImage(ImageUtil.scaleImage("src/images/title.png", 50, 50));
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
shell.setLocation((dimension.width - shell.getSize().x) / 2, (dimension.height - shell.getSize().y) / 2);
shell.setImage(ImageUtil.scaleImage("src/images/title.png", 50, 50));
shell.setBackgroundImage((ImageUtil.scaleImage("src/images/bk_login.jpg", 525, 400)));
shell.setText("ZJ-MusicPlayer");
Label label = new Label(shell, SWT.NONE);
label.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9, SWT.BOLD));
label.setBounds(24, 10, 76, 20);
label.setText("设置");
label.setBackground(SWTResourceManager.getColor(SWT.COLOR_TRANSPARENT));
Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9, SWT.NORMAL));
lblNewLabel.setBounds(25, 50, 100, 20);
lblNewLabel.setText("歌曲下载路径");
lblNewLabel.setBackground(SWTResourceManager.getColor(SWT.COLOR_TRANSPARENT));
Button btnNewButton = new Button(shell, SWT.NONE);
btnNewButton.setBounds(131, 45, 98, 30);
btnNewButton.setText("选择路径");
Label labelPath = new Label(shell, SWT.NONE);
labelPath.setBounds(259, 50, 238, 20);
labelPath.setBackground(SWTResourceManager.getColor(SWT.COLOR_TRANSPARENT));
ReadAndWriteRegistery registery = new ReadAndWriteRegistery();
Button buttonSave = new Button(shell, SWT.NONE);
buttonSave.setBounds(shell.getSize().x / 4, 290, shell.getSize().x / 5, 30);
buttonSave.setText("保存退出");
Button buttonExit = new Button(shell, SWT.NONE);
buttonExit.setBounds(shell.getSize().x / 2, 290, shell.getSize().x / 5, 30);
buttonExit.setText("退出");
String pathOld = registery.findInfo("DOWNLOAD_PATH");
if (StringUtil.checkNull(pathOld)) {
labelPath.setText(System.getProperty("user.dir"));
} else {
labelPath.setText(pathOld);
}
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
DirectoryDialog directoryDialog = new DirectoryDialog(shell, SWT.OPEN);
// 设置目录选择对话框的标题
directoryDialog.setText("下载路径选择");
// 设置文件目录选择对话框的提示信息
directoryDialog.setMessage("请选择你下载的歌曲想要保存的路径");
// 设置默认打开的文件目录
directoryDialog.setFilterPath(pathOld);
// 打开窗口,选择用户所选择的文件目录
final String path = directoryDialog.open();
if (!StringUtil.checkNull(path)) {
labelPath.setText(path);
}
}
});
buttonSave.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean flag = MessageDialog.openConfirm(shell, "退出", "确认保存修改并退出吗?");
System.out.println(flag);
if (flag) {
registery.writeInfo("DOWNLOAD_PATH", labelPath.getText().trim());
shell.dispose();
}
}
});
buttonExit.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.dispose();
}
});
}
}
| 30.647482
| 108
| 0.699531
|
c879ad0eee90dcbc21810040814aa442c11bb361
| 2,246
|
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Add extends AppCompatActivity {
TasksDatabaseManager db;
private EditText editName, editType, editLVL;
private Button btnAdd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
editName = (EditText) findViewById(R.id.editName);
editType = (EditText) findViewById(R.id.editType);
editLVL = (EditText) findViewById(R.id.editLvl);
Intent intent = getIntent();
String tablename = intent.getStringExtra("table");
btnAdd = (Button) findViewById(R.id.btnAdd);
db = new TasksDatabaseManager(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Pokemon newEntry = new Pokemon(editName.getText().toString(), editType.getText().toString(), editLVL.getText().toString());
if (editName.length() != 0 && editType.length() != 0 && editLVL.length() != 0 ) {
AddData(newEntry, tablename);
toastMessage("Pokemon succesfully inserted");
Intent refresh = new Intent(Add.this, allPokemon.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.
} else {
toastMessage("You must put something in the all text field!");
}
}
});
}
public void AddData(Pokemon pokemon, String tablename) {
db.open();
boolean insertData = db.addPokemon(pokemon, tablename);
db.close();
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
}
}
| 30.351351
| 139
| 0.619323
|
7f9b694d36d7e0bc82a71978932267b1f129f752
| 2,467
|
package com.marnixbarendregt.gamelib.main;
import org.joml.Matrix4f;
import org.joml.Vector3f;
/**
* Created by marnixbarendregt on 20/09/2017.
*/
public class Camera {
private final float FOV, NEAR, FAR;
private Matrix4f projectionMatrix;
private Matrix4f worldMatrix;
private Vector3f position;
private Vector3f rotation;
private boolean customMatrix = false;
public Camera(Window window, float pov, float near, float far) {
this.FOV = (float) Math.toRadians(pov);
this.NEAR = near;
this.FAR = far;
this.position = new Vector3f(0.0f, 0.0f, 0.0f);
this.rotation = new Vector3f(0.0f, 0.0f, 0.0f);
float aspectRatio = (float) window.getWidth() / window.getHeight();
this.projectionMatrix = new Matrix4f().perspective(FOV, aspectRatio, NEAR, FAR);
this.worldMatrix = new Matrix4f();
}
public Matrix4f getProjectionMatrix() {
return projectionMatrix;
}
public Matrix4f getWorldMatrix() {
if (!customMatrix) {
worldMatrix.identity();
worldMatrix.rotate((float) Math.toRadians(rotation.x), new Vector3f(1, 0, 0));
worldMatrix.rotate((float) Math.toRadians(rotation.y), new Vector3f(0, 1, 0));
worldMatrix.rotate((float) Math.toRadians(rotation.z), new Vector3f(0, 0, 1));
worldMatrix.translate(position.negate());
position.negate();
}
return worldMatrix;
}
// Position
public Vector3f getPosition() {
return position;
}
public void setPosition(Vector3f position) {
this.position = position;
}
public void increasePosition(Vector3f offset) {
this.position.add(offset);
}
// Rotation
public Vector3f getRotation() {
checkRotation();
return rotation;
}
public void setRotation(Vector3f rotation) {
this.rotation = rotation;
checkRotation();
}
public void increaseRotation(Vector3f rotationChange) {
this.rotation.add(rotationChange);
checkRotation();
}
public void checkRotation() {
rotation.x = rotation.x % 360;
rotation.y = rotation.y % 360;
rotation.z = rotation.z % 360;
}
public void setCustomMatrix(Matrix4f matrix) {
customMatrix = true;
this.worldMatrix = matrix;
}
public void disableCustomMatrix() {
customMatrix = false;
}
}
| 26.244681
| 90
| 0.625051
|
8ab8a9ff664df829428c16223a55de886ac0b9f6
| 1,979
|
package com.ngt.window;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
/**
* @author ngt
* @create 2021-01-28 20:57
*/
public class ProcessingTimeSlidingWindowDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.setInteger("rest.port", 8181);
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
// saprk,1
// scala,9
DataStreamSource<String> lines = env.socketTextStream("192.168.31.8", 8888);
SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = lines.map(data -> {
String[] split = data.split(",");
return Tuple2.of(split[0], Integer.valueOf(split[1]));
}).returns(Types.TUPLE(Types.STRING, Types.INT));
KeyedStream<Tuple2<String, Integer>, String> keyed = wordAndCount.keyBy(t -> t.f0);
WindowedStream<Tuple2<String, Integer>, String, TimeWindow> windowed =
keyed.window(SlidingProcessingTimeWindows.of(Time.seconds(30), Time.seconds(10)));
windowed.sum(1).print();
env.execute();
}
}
| 44.977273
| 106
| 0.746337
|
800ed9593ef77cd96699c86504e558d5d90077af
| 829
|
package org.apache.tomcat.util.buf;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.apache.tomcat.util.buf.UEncoder.SafeCharsSet;
/**
* Test cases for {@link UEncoder}.
*/
public class TestUEncoder {
@Test
public void testEncodeURLWithSlashInit() throws IOException {
UEncoder urlEncoder = new UEncoder(SafeCharsSet.WITH_SLASH);
String s = "a+b/c/d+e.class";
Assert.assertTrue(urlEncoder.encodeURL(s, 0, s.length()).equals(
"a%2bb/c/d%2be.class"));
Assert.assertTrue(urlEncoder.encodeURL(s, 2, s.length() - 2).equals(
"b/c/d%2be.cla"));
s = new String(new char[] { 0xD801, 0xDC01 });
Assert.assertTrue(urlEncoder.encodeURL(s, 0, s.length())
.equals("%f0%90%90%81"));
}
}
| 25.90625
| 76
| 0.628468
|
b13a7a0cf7f7f18b2d51b4302974d160cd670281
| 24,672
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|jcr
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|ByteArrayInputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|InputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|InputStreamReader
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Calendar
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|Node
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|PathNotFoundException
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|PropertyType
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|Repository
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|RepositoryException
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|Session
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|Value
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|ValueFactory
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|nodetype
operator|.
name|NodeType
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|retention
operator|.
name|RetentionPolicy
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jcr
operator|.
name|security
operator|.
name|Privilege
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Charsets
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|commons
operator|.
name|JcrUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|commons
operator|.
name|cnd
operator|.
name|CndImporter
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|commons
operator|.
name|cnd
operator|.
name|ParseException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|commons
operator|.
name|jackrabbit
operator|.
name|authorization
operator|.
name|AccessControlUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|security
operator|.
name|principal
operator|.
name|EveryonePrincipal
import|;
end_import
begin_class
specifier|public
class|class
name|TestContentLoader
block|{
comment|/** * The encoding of the test resources. */
specifier|private
specifier|static
specifier|final
name|String
name|ENCODING
init|=
literal|"UTF-8"
decl_stmt|;
specifier|public
name|void
name|loadTestContent
parameter_list|(
name|Session
name|session
parameter_list|)
throws|throws
name|RepositoryException
throws|,
name|IOException
throws|,
name|ParseException
block|{
name|session
operator|.
name|getWorkspace
argument_list|()
operator|.
name|getNamespaceRegistry
argument_list|()
operator|.
name|registerNamespace
argument_list|(
literal|"test"
argument_list|,
literal|"http://www.apache.org/jackrabbit/test"
argument_list|)
expr_stmt|;
name|registerTestNodeTypes
argument_list|(
name|session
argument_list|)
expr_stmt|;
name|Node
name|root
init|=
name|session
operator|.
name|getRootNode
argument_list|()
decl_stmt|;
name|Node
name|data
init|=
name|getOrAddNode
argument_list|(
name|root
argument_list|,
literal|"testdata"
argument_list|)
decl_stmt|;
name|addPropertyTestData
argument_list|(
name|getOrAddNode
argument_list|(
name|data
argument_list|,
literal|"property"
argument_list|)
argument_list|)
expr_stmt|;
name|addQueryTestData
argument_list|(
name|getOrAddNode
argument_list|(
name|data
argument_list|,
literal|"query"
argument_list|)
argument_list|)
expr_stmt|;
name|addNodeTestData
argument_list|(
name|getOrAddNode
argument_list|(
name|data
argument_list|,
literal|"node"
argument_list|)
argument_list|)
expr_stmt|;
if|if
condition|(
name|session
operator|.
name|getRepository
argument_list|()
operator|.
name|getDescriptorValue
argument_list|(
name|Repository
operator|.
name|OPTION_LIFECYCLE_SUPPORTED
argument_list|)
operator|.
name|getBoolean
argument_list|()
condition|)
block|{
name|addLifecycleTestData
argument_list|(
name|getOrAddNode
argument_list|(
name|data
argument_list|,
literal|"lifecycle"
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|addExportTestData
argument_list|(
name|getOrAddNode
argument_list|(
name|data
argument_list|,
literal|"docViewTest"
argument_list|)
argument_list|)
expr_stmt|;
if|if
condition|(
name|session
operator|.
name|getRepository
argument_list|()
operator|.
name|getDescriptorValue
argument_list|(
name|Repository
operator|.
name|OPTION_RETENTION_SUPPORTED
argument_list|)
operator|.
name|getBoolean
argument_list|()
condition|)
block|{
name|Node
name|conf
init|=
name|getOrAddNode
argument_list|(
name|session
operator|.
name|getRootNode
argument_list|()
argument_list|,
literal|"testconf"
argument_list|)
decl_stmt|;
name|addRetentionTestData
argument_list|(
name|getOrAddNode
argument_list|(
name|conf
argument_list|,
literal|"retentionTest"
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|AccessControlUtils
operator|.
name|addAccessControlEntry
argument_list|(
name|session
argument_list|,
literal|"/"
argument_list|,
name|EveryonePrincipal
operator|.
name|getInstance
argument_list|()
argument_list|,
operator|new
name|String
index|[]
block|{
name|Privilege
operator|.
name|JCR_READ
block|}
argument_list|,
literal|true
argument_list|)
expr_stmt|;
name|AccessControlUtils
operator|.
name|addAccessControlEntry
argument_list|(
name|session
argument_list|,
literal|"/jcr:system"
argument_list|,
name|EveryonePrincipal
operator|.
name|getInstance
argument_list|()
argument_list|,
operator|new
name|String
index|[]
block|{
name|Privilege
operator|.
name|JCR_READ
block|}
argument_list|,
literal|false
argument_list|)
expr_stmt|;
name|session
operator|.
name|save
argument_list|()
expr_stmt|;
block|}
specifier|private
specifier|static
name|void
name|registerTestNodeTypes
parameter_list|(
name|Session
name|session
parameter_list|)
throws|throws
name|RepositoryException
throws|,
name|ParseException
throws|,
name|IOException
block|{
name|InputStream
name|stream
init|=
name|TestContentLoader
operator|.
name|class
operator|.
name|getResourceAsStream
argument_list|(
literal|"test_nodetypes.cnd"
argument_list|)
decl_stmt|;
try|try
block|{
name|CndImporter
operator|.
name|registerNodeTypes
argument_list|(
operator|new
name|InputStreamReader
argument_list|(
name|stream
argument_list|,
name|Charsets
operator|.
name|UTF_8
argument_list|)
argument_list|,
name|session
argument_list|)
expr_stmt|;
block|}
finally|finally
block|{
name|stream
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
specifier|private
specifier|static
name|Node
name|getOrAddNode
parameter_list|(
name|Node
name|node
parameter_list|,
name|String
name|name
parameter_list|)
throws|throws
name|RepositoryException
block|{
try|try
block|{
return|return
name|node
operator|.
name|getNode
argument_list|(
name|name
argument_list|)
return|;
block|}
catch|catch
parameter_list|(
name|PathNotFoundException
name|e
parameter_list|)
block|{
return|return
name|node
operator|.
name|addNode
argument_list|(
name|name
argument_list|)
return|;
block|}
block|}
comment|/** * Creates a boolean, double, long, calendar and a path property at the * given node. */
specifier|private
specifier|static
name|void
name|addPropertyTestData
parameter_list|(
name|Node
name|node
parameter_list|)
throws|throws
name|RepositoryException
block|{
name|node
operator|.
name|setProperty
argument_list|(
literal|"boolean"
argument_list|,
literal|true
argument_list|)
expr_stmt|;
name|node
operator|.
name|setProperty
argument_list|(
literal|"double"
argument_list|,
name|Math
operator|.
name|PI
argument_list|)
expr_stmt|;
name|node
operator|.
name|setProperty
argument_list|(
literal|"long"
argument_list|,
literal|90834953485278298L
argument_list|)
expr_stmt|;
name|Calendar
name|c
init|=
name|Calendar
operator|.
name|getInstance
argument_list|()
decl_stmt|;
name|c
operator|.
name|set
argument_list|(
literal|2005
argument_list|,
literal|6
argument_list|,
literal|18
argument_list|,
literal|17
argument_list|,
literal|30
argument_list|)
expr_stmt|;
name|node
operator|.
name|setProperty
argument_list|(
literal|"calendar"
argument_list|,
name|c
argument_list|)
expr_stmt|;
name|ValueFactory
name|factory
init|=
name|node
operator|.
name|getSession
argument_list|()
operator|.
name|getValueFactory
argument_list|()
decl_stmt|;
name|node
operator|.
name|setProperty
argument_list|(
literal|"path"
argument_list|,
name|factory
operator|.
name|createValue
argument_list|(
literal|"/"
argument_list|,
name|PropertyType
operator|.
name|PATH
argument_list|)
argument_list|)
expr_stmt|;
name|node
operator|.
name|setProperty
argument_list|(
literal|"multi"
argument_list|,
operator|new
name|String
index|[]
block|{
literal|"one"
block|,
literal|"two"
block|,
literal|"three"
block|}
argument_list|)
expr_stmt|;
block|}
comment|/** * Creates a node with a RetentionPolicy */
specifier|private
name|void
name|addRetentionTestData
parameter_list|(
name|Node
name|node
parameter_list|)
throws|throws
name|RepositoryException
block|{
name|RetentionPolicy
name|rp
init|=
name|createRetentionPolicy
argument_list|(
literal|"testRetentionPolicy"
argument_list|,
name|node
operator|.
name|getSession
argument_list|()
argument_list|)
decl_stmt|;
name|node
operator|.
name|getSession
argument_list|()
operator|.
name|getRetentionManager
argument_list|()
operator|.
name|setRetentionPolicy
argument_list|(
name|node
operator|.
name|getPath
argument_list|()
argument_list|,
name|rp
argument_list|)
expr_stmt|;
block|}
specifier|private
name|RetentionPolicy
name|createRetentionPolicy
parameter_list|(
name|String
name|testRetentionPolicy
parameter_list|,
name|Session
name|session
parameter_list|)
block|{
throw|throw
operator|new
name|UnsupportedOperationException
argument_list|(
literal|"Retention Management not yet implemented"
argument_list|)
throw|;
block|}
comment|/** * Creates four nodes under the given node. Each node has a String property * named "prop1" with some content set. */
specifier|private
specifier|static
name|void
name|addQueryTestData
parameter_list|(
name|Node
name|node
parameter_list|)
throws|throws
name|RepositoryException
block|{
while|while
condition|(
name|node
operator|.
name|hasNode
argument_list|(
literal|"node1"
argument_list|)
condition|)
block|{
name|node
operator|.
name|getNode
argument_list|(
literal|"node1"
argument_list|)
operator|.
name|remove
argument_list|()
expr_stmt|;
block|}
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"node1"
argument_list|)
operator|.
name|setProperty
argument_list|(
literal|"prop1"
argument_list|,
literal|"You can have it good, cheap, or fast. Any two."
argument_list|)
expr_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"node1"
argument_list|)
operator|.
name|setProperty
argument_list|(
literal|"prop1"
argument_list|,
literal|"foo bar"
argument_list|)
expr_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"node1"
argument_list|)
operator|.
name|setProperty
argument_list|(
literal|"prop1"
argument_list|,
literal|"Hello world!"
argument_list|)
expr_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"node2"
argument_list|)
operator|.
name|setProperty
argument_list|(
literal|"prop1"
argument_list|,
literal|"Apache Jackrabbit"
argument_list|)
expr_stmt|;
block|}
comment|/** * Creates three nodes under the given node: one of type nt:resource and the * other nodes referencing it. */
specifier|private
specifier|static
name|void
name|addNodeTestData
parameter_list|(
name|Node
name|node
parameter_list|)
throws|throws
name|RepositoryException
throws|,
name|IOException
block|{
if|if
condition|(
name|node
operator|.
name|hasNode
argument_list|(
literal|"multiReference"
argument_list|)
condition|)
block|{
name|node
operator|.
name|getNode
argument_list|(
literal|"multiReference"
argument_list|)
operator|.
name|remove
argument_list|()
expr_stmt|;
block|}
if|if
condition|(
name|node
operator|.
name|hasNode
argument_list|(
literal|"resReference"
argument_list|)
condition|)
block|{
name|node
operator|.
name|getNode
argument_list|(
literal|"resReference"
argument_list|)
operator|.
name|remove
argument_list|()
expr_stmt|;
block|}
if|if
condition|(
name|node
operator|.
name|hasNode
argument_list|(
literal|"myResource"
argument_list|)
condition|)
block|{
name|node
operator|.
name|getNode
argument_list|(
literal|"myResource"
argument_list|)
operator|.
name|remove
argument_list|()
expr_stmt|;
block|}
name|Node
name|resource
init|=
name|node
operator|.
name|addNode
argument_list|(
literal|"myResource"
argument_list|,
literal|"nt:resource"
argument_list|)
decl_stmt|;
comment|// nt:resource not longer referenceable since JCR 2.0
name|resource
operator|.
name|addMixin
argument_list|(
literal|"mix:referenceable"
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:encoding"
argument_list|,
name|ENCODING
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:mimeType"
argument_list|,
literal|"text/plain"
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:data"
argument_list|,
literal|"Hello w\u00F6rld."
argument_list|,
name|PropertyType
operator|.
name|BINARY
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:lastModified"
argument_list|,
name|Calendar
operator|.
name|getInstance
argument_list|()
argument_list|)
expr_stmt|;
name|Node
name|resReference
init|=
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"reference"
argument_list|)
decl_stmt|;
name|resReference
operator|.
name|setProperty
argument_list|(
literal|"ref"
argument_list|,
name|resource
argument_list|)
expr_stmt|;
comment|// make this node itself referenceable
name|resReference
operator|.
name|addMixin
argument_list|(
literal|"mix:referenceable"
argument_list|)
expr_stmt|;
name|Node
name|multiReference
init|=
name|node
operator|.
name|addNode
argument_list|(
literal|"multiReference"
argument_list|)
decl_stmt|;
name|ValueFactory
name|factory
init|=
name|node
operator|.
name|getSession
argument_list|()
operator|.
name|getValueFactory
argument_list|()
decl_stmt|;
name|multiReference
operator|.
name|setProperty
argument_list|(
literal|"ref"
argument_list|,
operator|new
name|Value
index|[]
block|{
name|factory
operator|.
name|createValue
argument_list|(
name|resource
argument_list|)
block|,
name|factory
operator|.
name|createValue
argument_list|(
name|resReference
argument_list|)
block|}
argument_list|)
expr_stmt|;
comment|// NodeDefTest requires a test node with a mandatory child node
name|JcrUtils
operator|.
name|putFile
argument_list|(
name|node
argument_list|,
literal|"testFile"
argument_list|,
literal|"text/plain"
argument_list|,
operator|new
name|ByteArrayInputStream
argument_list|(
literal|"Hello, World!"
operator|.
name|getBytes
argument_list|(
literal|"UTF-8"
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
comment|/** * Creates a lifecycle policy node and another node with a lifecycle * referencing that policy. */
specifier|private
name|void
name|addLifecycleTestData
parameter_list|(
name|Node
name|node
parameter_list|)
throws|throws
name|RepositoryException
block|{
name|Node
name|policy
init|=
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"policy"
argument_list|)
decl_stmt|;
name|policy
operator|.
name|addMixin
argument_list|(
name|NodeType
operator|.
name|MIX_REFERENCEABLE
argument_list|)
expr_stmt|;
name|Node
name|transitions
init|=
name|getOrAddNode
argument_list|(
name|policy
argument_list|,
literal|"transitions"
argument_list|)
decl_stmt|;
name|Node
name|transition
init|=
name|getOrAddNode
argument_list|(
name|transitions
argument_list|,
literal|"identity"
argument_list|)
decl_stmt|;
name|transition
operator|.
name|setProperty
argument_list|(
literal|"from"
argument_list|,
literal|"identity"
argument_list|)
expr_stmt|;
name|transition
operator|.
name|setProperty
argument_list|(
literal|"to"
argument_list|,
literal|"identity"
argument_list|)
expr_stmt|;
name|Node
name|lifecycle
init|=
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"node"
argument_list|)
decl_stmt|;
name|assignLifecyclePolicy
argument_list|(
name|lifecycle
argument_list|,
name|policy
argument_list|,
literal|"identity"
argument_list|)
expr_stmt|;
block|}
specifier|private
name|void
name|assignLifecyclePolicy
parameter_list|(
name|Node
name|lifecycle
parameter_list|,
name|Node
name|policy
parameter_list|,
name|String
name|identity
parameter_list|)
block|{
throw|throw
operator|new
name|UnsupportedOperationException
argument_list|(
literal|"Lifecycle Management is not yet implemented"
argument_list|)
throw|;
block|}
specifier|private
specifier|static
name|void
name|addExportTestData
parameter_list|(
name|Node
name|node
parameter_list|)
throws|throws
name|RepositoryException
throws|,
name|IOException
block|{
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"invalidXmlName"
argument_list|)
operator|.
name|setProperty
argument_list|(
literal|"propName"
argument_list|,
literal|"some text"
argument_list|)
expr_stmt|;
comment|// three nodes which should be serialized as xml text in docView export
comment|// separated with spaces
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"jcr:xmltext"
argument_list|)
operator|.
name|setProperty
argument_list|(
literal|"jcr:xmlcharacters"
argument_list|,
literal|"A text without any special character."
argument_list|)
expr_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"some-element"
argument_list|)
expr_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"jcr:xmltext"
argument_list|)
operator|.
name|setProperty
argument_list|(
literal|"jcr:xmlcharacters"
argument_list|,
literal|" The entity reference characters:<, ', ,&,>, \" should"
operator|+
literal|" be escaped in xml export. "
argument_list|)
expr_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"some-element"
argument_list|)
expr_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"jcr:xmltext"
argument_list|)
operator|.
name|setProperty
argument_list|(
literal|"jcr:xmlcharacters"
argument_list|,
literal|"A text without any special character."
argument_list|)
expr_stmt|;
name|Node
name|big
init|=
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"bigNode"
argument_list|)
decl_stmt|;
name|big
operator|.
name|setProperty
argument_list|(
literal|"propName0"
argument_list|,
literal|"SGVsbG8gd8O2cmxkLg==;SGVsbG8gd8O2cmxkLg=="
operator|.
name|split
argument_list|(
literal|";"
argument_list|)
argument_list|,
name|PropertyType
operator|.
name|BINARY
argument_list|)
expr_stmt|;
name|big
operator|.
name|setProperty
argument_list|(
literal|"propName1"
argument_list|,
literal|"text 1"
argument_list|)
expr_stmt|;
name|big
operator|.
name|setProperty
argument_list|(
literal|"propName2"
argument_list|,
literal|"multival text 1;multival text 2;multival text 3"
operator|.
name|split
argument_list|(
literal|";"
argument_list|)
argument_list|)
expr_stmt|;
name|big
operator|.
name|setProperty
argument_list|(
literal|"propName3"
argument_list|,
literal|"text 1"
argument_list|)
expr_stmt|;
name|addExportValues
argument_list|(
name|node
argument_list|,
literal|"propName"
argument_list|)
expr_stmt|;
name|addExportValues
argument_list|(
name|node
argument_list|,
literal|"Prop<>prop"
argument_list|)
expr_stmt|;
block|}
comment|/** * create nodes with following properties binary& single binary& multival * notbinary& single notbinary& multival */
specifier|private
specifier|static
name|void
name|addExportValues
parameter_list|(
name|Node
name|node
parameter_list|,
name|String
name|name
parameter_list|)
throws|throws
name|RepositoryException
throws|,
name|IOException
block|{
name|String
name|prefix
init|=
literal|"valid"
decl_stmt|;
if|if
condition|(
name|name
operator|.
name|indexOf
argument_list|(
literal|'<'
argument_list|)
operator|!=
operator|-
literal|1
condition|)
block|{
name|prefix
operator|=
literal|"invalid"
expr_stmt|;
block|}
name|node
operator|=
name|getOrAddNode
argument_list|(
name|node
argument_list|,
name|prefix
operator|+
literal|"Names"
argument_list|)
expr_stmt|;
name|String
index|[]
name|texts
init|=
operator|new
name|String
index|[]
block|{
literal|"multival text 1"
block|,
literal|"multival text 2"
block|,
literal|"multival text 3"
block|}
decl_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
name|prefix
operator|+
literal|"MultiNoBin"
argument_list|)
operator|.
name|setProperty
argument_list|(
name|name
argument_list|,
name|texts
argument_list|)
expr_stmt|;
name|Node
name|resource
init|=
name|getOrAddNode
argument_list|(
name|node
argument_list|,
name|prefix
operator|+
literal|"MultiBin"
argument_list|)
decl_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:encoding"
argument_list|,
name|ENCODING
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:mimeType"
argument_list|,
literal|"text/plain"
argument_list|)
expr_stmt|;
name|String
index|[]
name|values
init|=
operator|new
name|String
index|[]
block|{
literal|"SGVsbG8gd8O2cmxkLg=="
block|,
literal|"SGVsbG8gd8O2cmxkLg=="
block|}
decl_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
name|name
argument_list|,
name|values
argument_list|,
name|PropertyType
operator|.
name|BINARY
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:lastModified"
argument_list|,
name|Calendar
operator|.
name|getInstance
argument_list|()
argument_list|)
expr_stmt|;
name|getOrAddNode
argument_list|(
name|node
argument_list|,
name|prefix
operator|+
literal|"NoBin"
argument_list|)
operator|.
name|setProperty
argument_list|(
name|name
argument_list|,
literal|"text 1"
argument_list|)
expr_stmt|;
name|resource
operator|=
name|getOrAddNode
argument_list|(
name|node
argument_list|,
literal|"invalidBin"
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:encoding"
argument_list|,
name|ENCODING
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:mimeType"
argument_list|,
literal|"text/plain"
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
name|name
argument_list|,
literal|"Hello w\u00F6rld."
argument_list|,
name|PropertyType
operator|.
name|BINARY
argument_list|)
expr_stmt|;
name|resource
operator|.
name|setProperty
argument_list|(
literal|"jcr:lastModified"
argument_list|,
name|Calendar
operator|.
name|getInstance
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
| 15.220234
| 810
| 0.800786
|
9c82611e319002982b4211ba6b805b69dd0787b6
| 917
|
package org.objectstyle.japp;
import java.util.Collection;
import java.util.Collections;
import org.apache.maven.artifact.Artifact;
class ArtifactMatchPattern {
private Collection<String> strings;
ArtifactMatchPattern(Collection<String> patterns) {
strings = (patterns != null) ? patterns : Collections.<String> emptyList();
}
boolean matchInclude(Artifact artifact) {
if (strings.isEmpty()) {
return true;
}
return match(artifact);
}
boolean matchExclude(Artifact artifact) {
if (strings.isEmpty()) {
return false;
}
return match(artifact);
}
private boolean match(Artifact artifact) {
String key = artifact.getId();
for (String pattern : strings) {
if (key.startsWith(pattern)) {
return true;
}
}
return false;
}
}
| 20.840909
| 83
| 0.59542
|
af34ad1c4551499881862106df9042a28f423c8f
| 11,716
|
/*
* Assurance
*
* Created by Mark Johnson
*
* Copyright (c) 2015 Digital Generalists, LLC.
*
*/
/*
* Copyright 2015 Digital Generalists, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.digitalgeneralists.assurance.ui.components;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Collection;
import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.digitalgeneralists.assurance.model.ModelUtils;
import com.digitalgeneralists.assurance.model.entities.FileReference;
import com.digitalgeneralists.assurance.model.entities.ScanMappingDefinition;
import com.digitalgeneralists.assurance.ui.components.dialogs.AssuranceDialogMode;
import com.digitalgeneralists.assurance.ui.components.dialogs.AssuranceDialogResult;
import com.digitalgeneralists.assurance.ui.components.dialogs.IDialogResponseHandler;
import com.digitalgeneralists.assurance.ui.factories.IDialogFactory;
@Component("ScanPathMappingPanel")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ScanPathMappingPanel extends AbstractDialogInputPanel implements IDialogResponseHandler, IListInputPanelDelegate<FileReference>
{
@Autowired
private IDialogFactory dialogFactory;
private static final long serialVersionUID = 1L;
private ScanMappingDefinition mappingDefinition;
protected final FilePickerTextField sourcePathPickerField = new FilePickerTextField("Source");
protected final FilePickerTextField targetPathPickerField = new FilePickerTextField("Target");
private ListInputPanel<FileReference> exclusionsPanel = null;
public void setMapping(ScanMappingDefinition mappingDefinition)
{
this.mappingDefinition = mappingDefinition;
this.initializeComponent();
}
protected void initializeComponent()
{
if (!this.initialized)
{
if (this.mappingDefinition == null)
{
this.mode = AssuranceDialogMode.ADD;
this.dialogTitle = "Add New Path Mapping";
this.mappingDefinition = new ScanMappingDefinition();
}
else
{
this.mode = AssuranceDialogMode.EDIT;
this.dialogTitle = "Edit Path Mapping";
}
GridBagLayout gridbag = new GridBagLayout();
this.setLayout(gridbag);
final JPanel scanPathsPanel = new JPanel();
scanPathsPanel.setLayout(new GridBagLayout());
Border pathsPanelBorder = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
pathsPanelBorder = BorderFactory.createTitledBorder(pathsPanelBorder, "Paths", TitledBorder.CENTER, TitledBorder.TOP);
GridBagConstraints scanPathsPanelConstraints = new GridBagConstraints();
scanPathsPanelConstraints.anchor = GridBagConstraints.NORTH;
scanPathsPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
scanPathsPanelConstraints.gridx = 0;
scanPathsPanelConstraints.gridy = 0;
scanPathsPanelConstraints.weightx = 1.0;
scanPathsPanelConstraints.weighty = 1.0;
scanPathsPanelConstraints.gridheight = 1;
scanPathsPanelConstraints.gridwidth = 2;
scanPathsPanelConstraints.insets = new Insets(5, 5, 5, 5);
scanPathsPanel.setBorder(pathsPanelBorder);
this.add(scanPathsPanel, scanPathsPanelConstraints);
GridBagConstraints sourcePathFieldConstraints = new GridBagConstraints();
sourcePathFieldConstraints.anchor = GridBagConstraints.NORTH;
sourcePathFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
sourcePathFieldConstraints.gridx = 0;
sourcePathFieldConstraints.gridy = 0;
sourcePathFieldConstraints.weightx = 1.0;
sourcePathFieldConstraints.weighty = 1.0;
sourcePathFieldConstraints.gridheight = 1;
sourcePathFieldConstraints.gridwidth = 1;
sourcePathFieldConstraints.insets = new Insets(0, 5, 5, 5);
GridBagConstraints targetPathFieldConstraints = new GridBagConstraints();
targetPathFieldConstraints.anchor = GridBagConstraints.NORTH;
targetPathFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
targetPathFieldConstraints.gridx = 0;
targetPathFieldConstraints.gridy = 1;
targetPathFieldConstraints.weightx = 1.0;
targetPathFieldConstraints.weighty = 1.0;
targetPathFieldConstraints.gridheight = 1;
targetPathFieldConstraints.gridwidth = 1;
targetPathFieldConstraints.insets = new Insets(5, 5, 5, 5);
scanPathsPanel.add(this.sourcePathPickerField, sourcePathFieldConstraints);
scanPathsPanel.add(this.targetPathPickerField, targetPathFieldConstraints);
if (mappingDefinition != null)
{
File source = mappingDefinition.getSource();
if (source != null)
{
this.sourcePathPickerField.setValue(source.getPath());
}
else
{
this.sourcePathPickerField.setValue("");
}
File target = mappingDefinition.getTarget();
if (target != null)
{
this.targetPathPickerField.setValue(target.getPath());
}
else
{
this.targetPathPickerField.setValue("");
}
}
Border existingExclusionsPanelBorder = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
existingExclusionsPanelBorder = BorderFactory.createTitledBorder(existingExclusionsPanelBorder, "Exclusions", TitledBorder.CENTER, TitledBorder.TOP);
GridBagConstraints existingExclusionsPanelConstraints = new GridBagConstraints();
existingExclusionsPanelConstraints.anchor = GridBagConstraints.WEST;
existingExclusionsPanelConstraints.fill = GridBagConstraints.BOTH;
existingExclusionsPanelConstraints.gridx = 0;
existingExclusionsPanelConstraints.gridy = 1;
existingExclusionsPanelConstraints.weightx = 1.0;
existingExclusionsPanelConstraints.weighty = 0.9;
existingExclusionsPanelConstraints.gridheight = 1;
existingExclusionsPanelConstraints.gridwidth = 2;
existingExclusionsPanelConstraints.insets = new Insets(0, 5, 0, 5);
JPanel existingExclusionsPanel = new JPanel();
GridBagLayout panelGridbag = new GridBagLayout();
existingExclusionsPanel.setLayout(panelGridbag);
existingExclusionsPanel.setBorder(existingExclusionsPanelBorder);
this.add(existingExclusionsPanel, existingExclusionsPanelConstraints);
GridBagConstraints existingExclusionsListConstraints = new GridBagConstraints();
existingExclusionsListConstraints.anchor = GridBagConstraints.WEST;
existingExclusionsListConstraints.fill = GridBagConstraints.BOTH;
existingExclusionsListConstraints.gridx = 0;
existingExclusionsListConstraints.gridy = 0;
existingExclusionsListConstraints.weightx = 1.0;
existingExclusionsListConstraints.weighty = 0.9;
existingExclusionsListConstraints.gridheight = 1;
existingExclusionsListConstraints.gridwidth = 2;
existingExclusionsListConstraints.insets = new Insets(5, 5, 5, 5);
this.mappingDefinition = (ScanMappingDefinition) ModelUtils.initializeEntity(this.mappingDefinition, ScanMappingDefinition.EXCLUSIONS_PROPERTY);
this.exclusionsPanel = new ListInputPanel<FileReference>(this.mappingDefinition, this);
existingExclusionsPanel.add(this.exclusionsPanel, existingExclusionsListConstraints);
this.initialized = true;
}
}
public void actionPerformed(ActionEvent e)
{
this.exclusionsPanel.actionPerformed(e);
}
private void displayExclusionDialog(FileReference selectedItem)
{
Window parent = SwingUtilities.getWindowAncestor(this.getParent());
JDialog exclusionDialog = this.dialogFactory.createExclusionDialogInstance(parent, ModalityType.APPLICATION_MODAL, this, selectedItem);
exclusionDialog.setVisible(true);
}
private void deleteExclusion(FileReference selectedItem)
{
if (selectedItem != null)
{
if (this.mappingDefinition.getUnmodifiableExclusions().size() > 0)
{
this.mappingDefinition.removeExclusion(selectedItem);
}
this.exclusionsPanel.loadData();
}
}
public Object getResultObject()
{
return this.mappingDefinition;
}
protected AssuranceDialogResult processImplementationInputOnConfirm()
{
this.mappingDefinition.setSource(new File(this.sourcePathPickerField.getValue()));
this.mappingDefinition.setTarget(new File(this.targetPathPickerField.getValue()));
return AssuranceDialogResult.CONFIRM;
}
public boolean validateFormState()
{
boolean result = true;
if (!this.sourcePathPickerField.validateFormState())
{
result = false;
}
if (!this.targetPathPickerField.validateFormState())
{
result = false;
}
// Exclusions are not required. The collection can be empty.
return result;
}
public void dialogClosed(AssuranceDialogResult result, Object resultObject)
{
if (result == AssuranceDialogResult.CONFIRM)
{
if ((resultObject != null) && (resultObject instanceof FileReference))
{
boolean bypass = false;
for (FileReference exclusion : this.mappingDefinition.getUnmodifiableExclusions())
{
if ((exclusion.getId() != null) && (exclusion.getId().equals(((FileReference)resultObject).getId())))
{
// NOTE: I worry I'm bypassing the point of Hibernate here.
// Only need this because the resultObject ends up as a dis-associated
// instance from the definition through the child property initialization
// process when values are loaded to the UI. Should identify a way
// to keep those in sync better. This is just a bridge patch to get
// over that challenge.
exclusion.mergeFileReference((FileReference)resultObject);
bypass = true;
break;
}
}
if (bypass != true)
{
if (!this.mappingDefinition.getUnmodifiableExclusions().contains(resultObject))
{
this.mappingDefinition.addExclusion((FileReference)resultObject);
}
}
}
this.exclusionsPanel.loadData();
this.validateFormState();
}
}
public Collection<FileReference> getListData()
{
return this.mappingDefinition.getUnmodifiableExclusions();
}
public String getInitializationPropertyName()
{
return ScanMappingDefinition.EXCLUSIONS_PROPERTY;
}
public boolean listRequiresRecord()
{
return false;
}
public String getPrimaryButtonAction()
{
return AssuranceActions.newExclusionAction;
}
public String getPrimaryButtonLabel()
{
return "New";
}
public void handlePrimaryButtonClick()
{
this.handlePrimaryButtonClick(null);
}
public void handlePrimaryButtonClick(FileReference item)
{
this.displayExclusionDialog(item);
}
public String getSecondaryButtonAction()
{
return AssuranceActions.deleteExclusionAction;
}
public String getSecondaryButtonLabel()
{
return "Delete";
}
public void handleSecondaryButtonClick()
{
this.handleSecondaryButtonClick(null);
}
public void handleSecondaryButtonClick(FileReference item)
{
this.deleteExclusion(item);
}
public void listValueChanged(boolean itemIsSelected)
{
}
}
| 32.544444
| 152
| 0.776033
|
a2f2930f43d6eb6ffcb2968661b39de3e0b0f292
| 803
|
package com.kkensu.www.imagepager.util;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
/**
* 서비스 실행을 쉽게 하기 위한 Builder 패턴
*/
@SuppressWarnings("unused")
public class ServiceBuilder<T extends Service> {
private final Context context;
private final Intent intent;
public ServiceBuilder(Context context, Class<T> clazz) {
this.context = context;
intent = new Intent(context, clazz);
}
public ServiceBuilder<T> arg(Bundle bundle) {
intent.putExtras(bundle);
return this;
}
public ServiceBuilder<T> arg(BundleBuilder builder) {
intent.putExtras(builder.build());
return this;
}
public void start() {
context.startService(intent);
}
}
| 22.305556
| 60
| 0.673724
|
4f4494b50bb5f7939a9b510c2298859660b4bf61
| 334
|
package com.loserico.lambda;
public class ActionLambda {
@FunctionalInterface
interface Action {
void run(String s);
}
public void action(Action action) {
action.run("Hello!");
}
public static void main(String[] args) {
new ActionLambda().action((String s) -> System.out.print("*" + s + "*"));
}
}
| 17.578947
| 76
| 0.628743
|
8d717acc553660cf9df6036a8fd64b56a25b2cbc
| 3,914
|
package com.chenbing.rapidm.util.menu;
import com.alibaba.fastjson.JSONObject;
import com.chenbing.rapidm.config.HttpUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class XYJFGWMenuManager {
private Log logger= LogFactory.getLog(this.getClass());
@Autowired
private HttpUtil httpUtil;
public static void main( String[] args ) {
}
public void createMenu(String token,String domain,String appid ){
String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
Menu menu = getProductMenuFor3_8(domain,appid);
httpUtil.postForObject(url,JSONObject.parseObject(JSONObject.toJSONString(menu)));
}
/**
*
* 3.8版本菜单
*
* @return
*/
public static Menu getProductMenuFor3_8(String domain ,String appid) {
// 第一按钮
ViewButton btn11 = new ViewButton();
btn11.setName( "在线顾问" );
btn11.setType( "view" );
btn11.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=http%3A%2F%2F"+domain+"%2Fwebsocket%2Findex.html&response_type=code&scope=snsapi_userinfo&state=10004#wechat_redirect");
// 第二按钮
ViewButton btn21 = new ViewButton();
btn21.setName( "找产品" );
btn21.setType( "click" );
btn21.setKey( "key_get_message3" );
ViewButton btn22 = new ViewButton();
btn22.setName( "✨定制贷款方案" );
btn22.setType( "view" );
btn22.setUrl(
"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=http%3a%2f%2f"+domain+"%2fxyguwen%2findex.html%3fsource%3dmenu%23%2fcustomize&response_type=code&scope=snsapi_userinfo&state=25073#wechat_redirect" );
ViewButton btn23 = new ViewButton();
btn23.setName( "评额度" );
btn23.setType( "click" );
btn23.setKey( "key_get_message2" );
ComplexButton mainBtn2 = new ComplexButton();
mainBtn2.setName( "我要" );
mainBtn2.setSub_button( new Button[] { btn21 , btn22 , btn23 } );
// 第三按钮
ViewButton btn31 = new ViewButton();
btn31.setName( "还款提醒" );
btn31.setType( "view" );
btn31.setUrl(
"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=http%3a%2f%2f"+domain+"%2fxyguwen%2findex.html%23%2fremind%3fsource%3dmenu&response_type=code&scope=snsapi_userinfo&state=10006#wechat_redirect " );
ViewButton btn32 = new ViewButton();
btn32.setName( "个人中心" );
btn32.setType( "view" );
btn32.setUrl(
"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=http%3a%2f%2f"+domain+"%2fxyguwen%2findex.html%23%2fpersonal%3fsource%3dmenu&response_type=code&scope=snsapi_userinfo&state=10005#wechat_redirect" );
ViewButton btn33 = new ViewButton();
btn33.setName( "贷款攻略" );
btn33.setType( "view" );
btn33.setUrl(
"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=http%3a%2f%2f"+domain+"%2fxyguwen%2findex.html%23%2flc%3fsource%3dmenu&response_type=code&scope=snsapi_userinfo&state=10002#wechat_redirect" );
ViewButton btn34 = new ViewButton();
btn34.setName( "投诉与反馈" );
btn34.setType( "view" );
btn34.setUrl(
"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=http%3a%2f%2f"+domain+"%2fxyguwen%2findex.html%23%2ffeedback%3fsource%3dmenu&response_type=code&scope=snsapi_userinfo&state=10003#wechat_redirect" );
ComplexButton mainBtn3 = new ComplexButton();
mainBtn3.setName( "我的" );
mainBtn3.setSub_button( new Button[] { btn31 , btn32 , btn33 , btn34 } );
/**
* 这是目前的菜单结构,每个一级菜单都有二级菜单项<br>
* 在某个一级菜单下没有二级菜单的情况,menu该如何定义呢?<br>
* 比如,第三个一级菜单项不是“更多体验”,而直接是“幽默笑话”,那么menu应该这样定义:<br>
* menu.setButton(new Button[] { mainBtn1, mainBtn2, btn33 });
*/
Menu menu = new Menu();
menu.setButton( new Button[] { btn11 , mainBtn2 , mainBtn3 } );
return menu;
}
}
| 36.579439
| 236
| 0.722534
|
ee1fb973f35f29c09923dad974938833c93da32e
| 2,385
|
package org.exiledkingcc.java.cfgs;
import org.exiledkingcc.java.cfgs.ann.ConfigItem;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public enum ConfigManager {
INSTANCE;
private String defaultSource = "cp://";
private HashMap<String, Object> configItems = new HashMap<>();
private ConfigSourceFactory sourceFactory = new ConfigSourceFactory();
private ConfigFormatFactory formatFactory = new ConfigFormatFactory();
public void registerDefaultSource(String path) {
this.defaultSource = path;
}
public <T> void registerConfig(String path, Class<T> clazz) {
ConfigItem configItem = clazz.getAnnotation(ConfigItem.class);
if (configItem == null) {
throw new IllegalArgumentException(
"Class " + clazz.getName() + " is NOT a ConfigItem");
}
ConfigSource configSource = this.sourceFactory.getSource(path);
if (configSource == null) {
throw new IllegalArgumentException(
"Can NOT create ConfigSource for " + path);
}
String configName = configItem.name();
if (this.configItems.containsKey(configName)) {
String clzName = this.configItems.get(configName).getClass().getName();
throw new IllegalArgumentException(
"Config " + configName + " has been registered with " + clzName);
}
ConfigFormat configFormat = this.formatFactory.getFormat(configName);
if (configFormat == null) {
throw new IllegalArgumentException(
"Can NOT create ConfigFormat for " + configName);
}
InputStream inputStream = configSource.getConfigData(configName);
Map<String, Object> kv = configFormat.parseConfig(inputStream);
T cfg = ConfigLoader.loadConfig(clazz, kv);
this.configItems.put(configName, cfg);
}
public void registerConfig(Class<?> clazz) {
this.registerConfig(this.defaultSource, clazz);
}
public <T> T getConfig(Class<T> clazz) {
ConfigItem configItem = clazz.getAnnotation(ConfigItem.class);
if (configItem == null) {
throw new IllegalArgumentException(
"Class " + clazz.getName() + " is NOT a ConfigItem");
}
return (T)this.configItems.get(configItem.name());
}
}
| 37.857143
| 85
| 0.642348
|
7a0ab2fdd11687f88419534abee5ff234b59a3f9
| 950
|
package com.hearthsim.card.classic.minion.rare;
import com.hearthsim.card.CharacterIndex;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.minion.MinionBattlecryInterface;
import com.hearthsim.event.effect.EffectCharacter;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.tree.HearthTreeNode;
public class TwilightDrake extends Minion implements MinionBattlecryInterface {
public TwilightDrake() {
super();
}
/**
* Battlecry: Gain +1 Health for each card in your hand.
*/
@Override
public EffectCharacter<Minion> getBattlecryEffect() {
return (PlayerSide targetSide,CharacterIndex minionPlacementIndex, HearthTreeNode boardState) -> {
this.addHealth((byte) boardState.data_.getCurrentPlayer().getHand().size());
this.addMaxHealth((byte) boardState.data_.getCurrentPlayer().getHand().size());
return boardState;
};
}
}
| 33.928571
| 106
| 0.725263
|
a0ea751216fa9da0d00c95576281f062714fd187
| 67,333
|
// BuildTreeTable.java
package mit.cadlab.dome3.gui.guiutils.treetable;
import com.sun.java.ObjectTreeTable;
import mit.cadlab.dome3.gui.guiutils.msg.OneButton1Msg;
import mit.cadlab.dome3.gui.guiutils.table.DomeTable;
import mit.cadlab.dome3.gui.guiutils.table.DomeTableObject;
import mit.cadlab.dome3.gui.guiutils.table.DomeTableObjectFactory;
import mit.cadlab.dome3.gui.guiutils.tree.DomeTree;
import mit.cadlab.dome3.gui.guiutils.tree.build.BuildTreeObjectFactory;
import mit.cadlab.dome3.gui.guiutils.treetable.Editors.*;
import mit.cadlab.dome3.gui.guiutils.treetable.Renderers.*;
import mit.cadlab.dome3.gui.mode.build.BuildMode;
import mit.cadlab.dome3.objectmodel.DomeObject;
import mit.cadlab.dome3.objectmodel.ModelObjectScope;
import mit.cadlab.dome3.objectmodel.dataobject.BooleanData;
import mit.cadlab.dome3.objectmodel.dataobject.interfaces.*;
import mit.cadlab.dome3.objectmodel.model.Model;
import mit.cadlab.dome3.objectmodel.model.dome.DomeModel;
import mit.cadlab.dome3.objectmodel.model.dome.DomeModelBuilder;
import mit.cadlab.dome3.objectmodel.model.tool.AnalysisTool;
import mit.cadlab.dome3.objectmodel.model.tool.optimization.build.OptimizationToolBuild;
import mit.cadlab.dome3.objectmodel.modelcomponent.mapping.plugin.PluginMappingManager;
import mit.cadlab.dome3.objectmodel.modelcomponent.mapping.tool.ToolMappingManager;
import mit.cadlab.dome3.objectmodel.modelobject.parameter.Parameter;
import mit.cadlab.dome3.objectmodel.modelobject.parameter.tool.optimization.ObjectiveParameter;
import mit.cadlab.dome3.objectmodel.modelobject.parameter.tool.optimization.OptimizationParameter;
import mit.cadlab.dome3.objectmodel.modelobject.parameter.tool.optimization.VariableParameter;
import mit.cadlab.dome3.objectmodel.modelobject.relation.Relation;
import mit.cadlab.dome3.objectmodel.modelobject.relation.equal.EqualRelation;
import mit.cadlab.dome3.objectmodel.modelobject.relation.iteration.IterationRelation;
import mit.cadlab.dome3.objectmodel.modelobject.relation.procedural.ProceduralRelation;
import mit.cadlab.dome3.objectmodel.modelobject.subscription.AbstractSubscription;
import mit.cadlab.dome3.objectmodel.project.IntegrationProject;
import mit.cadlab.dome3.objectmodel.project.info.*;
import mit.cadlab.dome3.objectmodel.toolinterface.optimization.build.OptimizationInterfaceBuild;
import mit.cadlab.dome3.objectmodel.util.mapping.MappingChangeEvent;
import mit.cadlab.dome3.objectmodel.util.mapping.MappingChangeListener;
import mit.cadlab.dome3.objectmodel.util.mapping.MappingNameChangeEvent;
import mit.cadlab.dome3.objectmodel.util.mapping.MappingNameChangeListener;
import mit.cadlab.dome3.plugin.PluginModel;
import mit.cadlab.dome3.plugin.PluginModelBuilder;
import mit.cadlab.dome3.swing.Templates;
import mit.cadlab.dome3.swing.table.AbstractTableObject;
import mit.cadlab.dome3.tool.optimization.qmoo.QMOOConfiguration;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collection;
public class BuildTreeTable extends ObjectTreeTable
{
protected int numberColumns = 3; // name, value, mapping
protected String[] columnNames = {"name", "value", "mapping"};
protected int[] columnWidths = {150, 150, 200};
protected static DomeTableObjectFactory tableObjectFactory = makeTableObjectFactory();
public BuildTreeTable(DomeTree tree)
{
super(new DomeObjectTreeTableModel(tree,
3,
new String[]{"name", "value", "mapping"},
tableObjectFactory));
DomeTable.customizeTable(this);
setInitialColumnWidths(columnWidths);
setDefaultRenderer(Object.class, new NothingRenderer());
}
public BuildTreeTable(DomeTree tree, int[] columnWidths)
{
super(new DomeObjectTreeTableModel(tree,
3,
new String[]{"name", "value", "mapping"},
tableObjectFactory));
DomeTable.customizeTable(this);
setInitialColumnWidths(columnWidths);
this.columnWidths = columnWidths;
setDefaultRenderer(Object.class, new NothingRenderer());
}
public BuildTreeTable(DomeTree tree, int noCols, String[] colNames, int[] colWidths)
{
super(new DomeObjectTreeTableModel(tree,
noCols,
colNames,
tableObjectFactory));
numberColumns = noCols;
columnNames = colNames;
DomeTable.customizeTable(this);
columnWidths = colWidths;
setInitialColumnWidths(columnWidths);
setDefaultRenderer(Object.class, new NothingRenderer());
}
// for optimization models
public BuildTreeTable(DomeTree tree, String qmooParameterType, int noCols, String[] colNames, int[] colWidths)
{
super(new DomeObjectTreeTableModel(tree,
noCols,
colNames,
BuildTreeTable.makeToolTableObjectFactory(qmooParameterType)));
numberColumns = noCols;
columnNames = colNames;
DomeTable.customizeTable(this);
columnWidths = colWidths;
setInitialColumnWidths(columnWidths);
setDefaultRenderer(Object.class, new NothingRenderer());
}
public BuildTreeTable(DomeTree tree, int noCols, String[] colNames, int[] colWidths, boolean isPluginModel)
{
super(new DomeObjectTreeTableModel(tree,
noCols,
colNames,
tableObjectFactory,
isPluginModel));
numberColumns = noCols;
columnNames = colNames;
DomeTable.customizeTable(this);
columnWidths = colWidths;
setInitialColumnWidths(columnWidths);
setDefaultRenderer(Object.class, new NothingRenderer());
}
public BuildTreeTable(DomeTree tree, int noCols, String[] colNames,
int[] colWidths, boolean defaultInterfaceCellExists,
boolean isModelView)
{
super(new DomeObjectTreeTableModel(tree,
noCols,
colNames,
tableObjectFactory,
defaultInterfaceCellExists,
isModelView));
numberColumns = noCols;
columnNames = colNames;
DomeTable.customizeTable(this);
columnWidths = colWidths;
setInitialColumnWidths(columnWidths);
setDefaultRenderer(Object.class, new NothingRenderer());
}
public BuildTreeTable(DomeTree tree, boolean isModelView)
{
super(new DomeObjectTreeTableModel(tree,
3,
new String[]{"name", "value", "mapping"},
tableObjectFactory,
false, //defaultInterfaceCellExists
isModelView));
DomeTable.customizeTable(this);
setInitialColumnWidths(columnWidths);
setDefaultRenderer(Object.class, new NothingRenderer());
}
protected static DomeTableObjectFactory makeTableObjectFactory()
{
DomeTableObjectFactory f = new DomeTableObjectFactory("BuildTreeTable.TableObjectFactory",
"mit.cadlab.dome3.swing.table.FillerTableObject");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.AbstractDomeObject",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$DefaultTableObject",
"mit.cadlab.dome3.objectmodel.DomeObject");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.parameter.AbstractParameter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$ParameterTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.parameter.Parameter");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelcomponent.filter.AbstractFilter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$UneditableTableObject",
"mit.cadlab.dome3.objectmodel.DomeObject");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelcomponent.filter.AbstractEventFilter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$UneditableTableObject",
"mit.cadlab.dome3.objectmodel.DomeObject");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.relation.equal.ConcreteEqualRelation",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$EqualRelationTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.relation.equal.EqualRelation");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.relation.iteration.ConditionIterationRelation",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$IterationRelationTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.relation.iteration.IterationRelation");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.relation.procedural.AbstractProceduralRelation",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$ProceduralRelationTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.relation.procedural.ProceduralRelation");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.project.info.BuildProjectResourceInfo",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$ProjectResourceInfoTableObject",
"mit.cadlab.dome3.objectmodel.project.info.ProjectResourceInfo");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.subscription.AbstractSubscription",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$SubscriptionTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.subscription.AbstractSubscription");
//to use folders in project resources
f.registerTableObjectInfo("mit.cadlab.dome3.gui.fileSystem.Folder",
"mit.cadlab.dome3.gui.fileSystem.FileSystemObjectTableObject",
"mit.cadlab.dome3.gui.fileSystem.FileSystemObject");
f.registerTableObjectInfo("mit.cadlab.dome3.gui.fileSystem.browse.BrowseDomeFile",
"mit.cadlab.dome3.gui.objectmodel.project.build.BrowseModelTableObject",
"mit.cadlab.dome3.gui.fileSystem.DomeFile");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.project.info.BuildProjectIntegrationModelInfo",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$ProjectIntegrationModelInfoTableObject",
"mit.cadlab.dome3.objectmodel.project.info.ProjectIntegrationModelInfo");
return f;
}
protected static DomeTableObjectFactory makeToolTableObjectFactory(String optimizationParameterType)
{
DomeTableObjectFactory f = new DomeTableObjectFactory("BuildTreeTable.TableObjectFactory",
"mit.cadlab.dome3.swing.table.FillerTableObject");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.AbstractDomeObject",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$DefaultTableObject",
"mit.cadlab.dome3.objectmodel.DomeObject");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelcomponent.filter.AbstractFilter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$UneditableTableObject",
"mit.cadlab.dome3.objectmodel.DomeObject");
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelcomponent.filter.AbstractEventFilter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$UneditableTableObject",
"mit.cadlab.dome3.objectmodel.DomeObject");
//to use folders in project resources
f.registerTableObjectInfo("mit.cadlab.dome3.gui.fileSystem.Folder",
"mit.cadlab.dome3.gui.fileSystem.FileSystemObjectTableObject",
"mit.cadlab.dome3.gui.fileSystem.FileSystemObject");
f.registerTableObjectInfo("mit.cadlab.dome3.gui.fileSystem.browse.BrowseDomeFile",
"mit.cadlab.dome3.gui.objectmodel.project.build.BrowseModelTableObject",
"mit.cadlab.dome3.gui.fileSystem.DomeFile");
if(optimizationParameterType.equals(QMOOConfiguration.MODEL_VARIABLE))
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.parameter.AbstractParameter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$ModelVariableOptimizationTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.parameter.Parameter");
else if(optimizationParameterType.equals(QMOOConfiguration.MODEL_OBJECTIVE))
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.parameter.AbstractParameter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$ModelObjectiveOptimizationTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.parameter.Parameter");
else if(optimizationParameterType.equals(QMOOConfiguration.INTERFACE_VARIABLE))
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.parameter.AbstractParameter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$InterfaceVariableOptimizationTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.parameter.Parameter");
else if(optimizationParameterType.equals(QMOOConfiguration.INTERFACE_OBJECTIVE))
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.parameter.AbstractParameter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$InterfaceObjectiveOptimizationTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.parameter.Parameter");
else if(optimizationParameterType.equals(OptimizationInterfaceBuild.QMOO_INTERFACE_BUILD_VIEW_PARAMETER))
f.registerTableObjectInfo("mit.cadlab.dome3.objectmodel.modelobject.parameter.AbstractParameter",
"mit.cadlab.dome3.gui.guiutils.treetable.BuildTreeTable$OptimizationParameterTableObject",
"mit.cadlab.dome3.objectmodel.modelobject.parameter.Parameter");
return f;
}
public static DomeTableObjectFactory getTableObjectFactory()
{
return tableObjectFactory;
}
public static class DefaultTableObject extends DomeTableObject
{
public DefaultTableObject(DomeObject obj, boolean isEditable)
{
super(obj, new boolean[]{isEditable, false, false}); // is name editable?
}
public DefaultTableObject(DomeObject obj)
{
this(obj, true); // is editable
}
public Object getDomeObject()
{
return object;
}
public void addTableTreeObjectListener(DomeObject obj)
{
BuildTreeObjectFactory.getTreeObject(obj).
addTreeObjectListener(new TableTreeObjectListener());
}
}
public static class UneditableTableObject extends DefaultTableObject
{
public UneditableTableObject(DomeObject obj)
{
super(obj, false); // not editable
}
}
public static class SubscriptionTableObject extends AbstractTableObject
{
public SubscriptionTableObject(AbstractSubscription obj)
{
super(obj, new boolean[]{false, false, false}); //nothing is editable
}
public Object getValueAt(int column)
{
if (column == 0) //name
return ((AbstractSubscription) object).getName();
else if (column == 1) { // value i.e. name of resource model
return ((AbstractSubscription) object).getResourceName();
}
return "";
}
}
public static class ProjectResourceInfoTableObject extends AbstractTableObject
{
public static final String NOTHING = "";
public ProjectResourceInfoTableObject(ProjectResourceInfo obj)
{
super(obj, new boolean[] {true, false, false}); //only name is editable
}
public Object getValueAt(int column)
{
if (column == 0) //name
return ((BuildProjectResourceInfo) object).getName();
else if (column == 1) { // value
return NOTHING;
}
else if (column == 2) { // location
return ((BuildProjectResourceInfo) object).getResourceHostName() +
":" + ((BuildProjectResourceInfo) object).getResourcePort();
}
return NOTHING;
}
public void setValueAt(Object value, int column)
{
if(column == 0) {
((BuildProjectResourceInfo) object).setName((String)value);
}
}
}
public static class ProjectIntegrationModelInfoTableObject extends AbstractTableObject
{
private DomeModelBuilder model;
private PropertyChangeListener resourceChangeListener = new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent event)
{
if(event.getPropertyName().equals(DomeModel.RESOURCE_SUBSCRIBED) ||
event.getPropertyName().equals(DomeModel.RESOURCE_UNSUBSCRIBED))
fireTableObjectChanged(2);
}
};
private PropertyChangeListener resourceNameChangeListener = new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent event)
{
if (event.getPropertyName().equals(ProjectResourceInfo.NAME)) {
fireTableObjectChanged(2);
}
}
};
public ProjectIntegrationModelInfoTableObject(ProjectIntegrationModelInfo obj)
{
super(obj, new boolean[]{true, false, false}); //only name is editable
model = (DomeModelBuilder) ((BuildProjectIntegrationModelInfo) object).getModel();
model.addPropertyChangeListener(resourceChangeListener);
model.addResourceNameChangeListener(resourceNameChangeListener);
}
public Object getValueAt(int column)
{
if (column == 0) //name
return ((BuildProjectIntegrationModelInfo) object).getName();
else if (column == 1) { // value
return ProjectResourceInfoTableObject.NOTHING;
} else if (column == 2) { // resources
Collection set = model.getResourcesSubscribed();
return getNames(set);
}
return ProjectResourceInfoTableObject.NOTHING;
}
public void setValueAt(Object value, int column)
{
if (column == 0) {
((ProjectIntegrationModelInfo) object).setName((String) value);
}
}
public static String getNames(Collection items)
{
if (items == null || items.size() == 0) return "";
Object[] objs = items.toArray();
if (objs.length == 1) {
return ((InfoInterface) objs[0]).getName();
}
if (objs.length == 2)
return ((InfoInterface) objs[0]).getName() +
" and " + ((InfoInterface) objs[1]).getName();
// 3 or more objects
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < objs.length - 1; ++i) {
sb.append(((InfoInterface) objs[i]).getName() + ", ");
}
sb.append("and " + ((InfoInterface) objs[objs.length - 1]).getName());
return sb.toString();
}
}
//add here for equal relation
public static class EqualRelationTableObject extends DefaultTableObject
{
public EqualRelationTableObject(EqualRelation rel)
{
super(rel.getDomeObject());
}
public Object getValueAt(int column)
{
if (column == 0)
return ((DomeObject) object).getName();
else if (column == 1) { // value
return ((EqualRelation) object).getBody();
}
return NOTHING;
}
}
public static class IterationRelationTableObject extends DefaultTableObject
{
public IterationRelationTableObject(IterationRelation rel)
{
super(rel.getDomeObject());
}
public Object getValueAt(int column)
{
if (column == 0)
return ((DomeObject) object).getName();
else if (column == 1) { // value
if(((IterationRelation) object).getBody().trim().equals("")&&((IterationRelation) object).getCondition().trim().equals(""))
return ((IterationRelation) object).getCondition()+((IterationRelation) object).getBody();
if(((IterationRelation) object).getIterationType().equals(IterationRelation.WHILE_LOOP)){
return "while "+((IterationRelation) object).getCondition()+" do "+((IterationRelation) object).getBody();
}
else if(((IterationRelation) object).getIterationType().equals(IterationRelation.DO_WHILE_LOOP)){
return "do "+((IterationRelation) object).getBody()+" while "+((IterationRelation) object).getCondition();
}
else if(((IterationRelation) object).getIterationType().equals(IterationRelation.Timestep_LOOP)){
return "timestep "+((IterationRelation) object).getCondition()+" repeat "+((IterationRelation) object).getBody();
}
}
return NOTHING;
}
}
public static class ProceduralRelationTableObject extends DefaultTableObject
{
public ProceduralRelationTableObject(ProceduralRelation rel)
{
super(rel.getDomeObject());
}
public Object getValueAt(int column)
{
if (column == 0)
return ((DomeObject) object).getName();
else if (column == 1) { // value
return ((ProceduralRelation) object).getBody();
}
return NOTHING;
}
}
public static class ParameterTableObject extends DomeTableObject
{
protected DefaultRenderer defaultRenderer = new DefaultRenderer();
protected DomeRealValueRenderer realRenderer = new DomeRealValueRenderer();
protected DomeIntegerValueRenderer integerRenderer = new DomeIntegerValueRenderer();
protected DomeStringValueRenderer stringRenderer = new DomeStringValueRenderer();
protected DomeVectorValueRenderer vectorRenderer = new DomeVectorValueRenderer();
protected DomeMatrixRenderer matrixRenderer = new DomeMatrixRenderer();
protected DomePreferenceRenderer preferenceRenderer = new DomePreferenceRenderer();
protected DomeEnumerationRenderer enumerationRenderer = new DomeEnumerationRenderer();
protected DomeFileValueRenderer fileRenderer = new DomeFileValueRenderer();
protected DomeListValueRenderer listRenderer = new DomeListValueRenderer();
protected Renderers.BooleanCheckBoxLeftRenderer checkBoxBooleanRenderer = new Renderers.BooleanCheckBoxLeftRenderer();
protected BooleanComboBoxEditor booleanEditor = new BooleanComboBoxEditor();
protected Editors.BooleanCheckBoxLeftEditor checkBoxBooleanEditor = new Editors.BooleanCheckBoxLeftEditor();
protected IntegerBuildEditor integerEditor = new IntegerBuildEditor();
protected RealBuildEditor realEditor = new RealBuildEditor();
protected StringBuildEditor stringEditor = new StringBuildEditor();
protected vectorBuildEditor vectorEditor = new vectorBuildEditor();
protected matrixBuildEditor matrixEditor = new matrixBuildEditor();
protected PreferenceBuildEditor preferenceEditor = new PreferenceBuildEditor();
protected EnumerationBuildEditor enumerationEditor = new EnumerationBuildEditor();
protected fileBuildEditor fileEditor = new fileBuildEditor();
protected listBuildEditor listEditor = new listBuildEditor();
protected DefaultCellEditor defaultCellEditor = new DefaultCellEditor(Templates.makeTextField(""));
protected MappingCellEditor mappingEditor = new MappingCellEditor(object);
protected static final String NOTHING = "";
/**
* sangmok: fix memory problem
* diagnosis: ParameterTableObject is not release properly. However, it is too hard to fix because there are so many instances which forget releasing this instance.
* temporary solution: even though ParameterTableObject is not released, editor instances in ParameterTableObject should be released because they contain references to Data Objects, which take up most of memory space.
* solution implemented by : invoke close() method, which removes the reference to data object of each editor, of every Editor instance. or just set each editor variable as null
*/
public void releaseDataObjectReferenceOfEditors() {
// integerEditor = null;
// realEditor = null;
// stringEditor = null;
// vectorEditor = null;
// matrixEditor = null;
// preferenceEditor = null;
// enumerationEditor = null;
// fileEditor = null;
// listEditor = null;
vectorEditor.clearDataObject();
matrixEditor.clearDataObject();
preferenceEditor.clearDataObject();
enumerationEditor.clearDataObject();
fileEditor.clearDataObject();
listEditor.clearDataObject();
}
protected PropertyChangeListener dataValueListener = new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
String property = e.getPropertyName();
if (property.equals("value") || property.equals("unit")) {
fireTableObjectChanged(1);
} else if (property.equals("size")) {//for vector and matrix
fireTableObjectChanged(1);
} else if (property.equals("filepath")) {//for file
fireTableObjectChanged(1);
} else if (property.equals(DomeEnumeration.LASTSELECTION)) {//for enumeration
fireTableObjectChanged(1);
}
}
};
protected MappingChangeListener mappingChangeListener = new MappingChangeListener()
{
public void mappingChanged(MappingChangeEvent event)
{
fireTableObjectChanged(2);
}
};
protected MappingNameChangeListener mappingNameChangeListener = new MappingNameChangeListener()
{
public void mappingNameChanged(MappingNameChangeEvent event)
{
fireTableObjectChanged(2);
}
};
public ParameterTableObject(Parameter obj)
{
super(obj, new boolean[]{true, true, true}); // name/value is editable
DataObject currentData = ((Parameter) object).getCurrentDataObject();
currentData.addPropertyChangeListener(dataValueListener);
((Parameter) object).addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
DataObject currentData = ((Parameter) object).getCurrentDataObject();
String property = e.getPropertyName();
if (property.equals(Parameter.DATATYPESELECTION)) {
DomeModel m = (DomeModel) ((Parameter) object).getModel();
DataObject oldObject = currentData;
m.getMappingManager().updateMappingListeners((Parameter) object, oldObject);
}
if (property.equals(Parameter.DATATYPESELECTION) ||
property.equals(Parameter.CURRENT_TYPE)) {
currentData.removePropertyChangeListener(dataValueListener);
currentData = ((Parameter) object).getCurrentDataObject();
currentData.addPropertyChangeListener(dataValueListener);
fireTableObjectChanged(1);
}
}
});
Model m = obj.getModel();
if (m != null) {
if (m instanceof Relation)
m = m.getModel();
if (m instanceof DomeModelBuilder && !(m instanceof PluginModelBuilder)) {
((DomeModel) m).getMappingManager().addMappingChangeListener(obj, mappingChangeListener);
((DomeModel) m).getMappingManager().addMappingNameChangeListener(obj, mappingNameChangeListener);
}
else if (m instanceof IntegrationProject) {
((IntegrationProject) m).getMappingManager().addMappingChangeListener(obj, mappingChangeListener);
((IntegrationProject) m).getMappingManager().addMappingNameChangeListener(obj, mappingNameChangeListener);
}
}
}
public void addTableTreeObjectListener(DomeObject obj)
{
BuildTreeObjectFactory.getTreeObject(obj).
addTreeObjectListener(new TableTreeObjectListener());
}
public Object getValueAt(int column)
{
if (column == 0)
return ((DomeObject) object).getName();
else if (column == 1)
{ // value
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeBoolean)
return ((DomeBoolean) data).getBooleanValue();
else if (data instanceof DomeReal)
return data;
//return ((DomeReal)data).getRealValue();
else if (data instanceof DomeInteger)
return data;
//return ((DomeInteger)data).getIntegerValue();
else if (data instanceof DomeString)
return data;
else if (data instanceof DomeVector)
return data;
else if (data instanceof DomeMatrix)
return data;
else if (data instanceof DomePreference)
return data;
else if (data instanceof DomeEnumeration)
return data;
else if (data instanceof DomeFile)
return data;
else if (data instanceof DomeList)
return data;
}
else if (column == 2)
{ // mapping
Parameter p = (Parameter) object;
Model m = p.getModel();
if (m instanceof PluginModel)
{
if (p.getScope() instanceof PluginModel)
{
PluginModelBuilder pmodel = (PluginModelBuilder) m;
PluginMappingManager pmgr = pmodel.getPluginMappingManager();
Object retObject = pmgr.getMappingObjectForParameter(p);
return retObject;
}
else
{
Collection c = ((DomeModel) m).getMappingManager().getMappingsForParameter(p);
if (c.isEmpty()) return NOTHING;
return getNames(c);
}
}
else
{
if (m instanceof Relation)
m = m.getModel();
if (m != null)
{
Collection c = null;
if (m instanceof DomeModel)
{
c = ((DomeModel) m).getMappingManager().getMappingsForParameter(p);
}
else
{
c = ((IntegrationProject) m).getMappingManager().getMappingsForParameter(p);
}
if (c.isEmpty()) return NOTHING;
return getNames(c);
}
else
{
return NOTHING;
}
}
}
return NOTHING;
}
public TableCellRenderer getRendererAt(int column)
{
if (column == 1) {
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeBoolean)
{
ModelObjectScope scope = ((Parameter) object).getModel();
if (scope.getModelObjectById(((Parameter) object).getId()) == null)
return checkBoxBooleanRenderer;
else
return defaultRenderer;
}
else if (data instanceof DomeReal)
return realRenderer;
else if (data instanceof DomeInteger)
return integerRenderer;
else if (data instanceof DomeString)
return stringRenderer;
else if (data instanceof DomeVector)
return vectorRenderer;
else if (data instanceof DomeMatrix)
return matrixRenderer;
else if (data instanceof DomePreference)
return preferenceRenderer;
else if (data instanceof DomeEnumeration)
return enumerationRenderer;
else if (data instanceof DomeFile)
return fileRenderer;
else if (data instanceof DomeList)
return listRenderer;
}
return null;
}
public TableCellEditor getEditorAt(int column)
{
if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeBoolean)
{
ModelObjectScope scope = ((Parameter)object).getModel();
if (scope.getModelObjectById(((Parameter)object).getId()) == null)
return checkBoxBooleanEditor;
else
return booleanEditor;
}
else if (data instanceof DomeReal)
return realEditor;
else if (data instanceof DomeInteger)
return integerEditor;
else if (data instanceof DomeString)
return stringEditor;
else if (data instanceof DomeVector)
return vectorEditor;
else if (data instanceof DomeMatrix)
return matrixEditor;
else if (data instanceof DomePreference)
return preferenceEditor;
else if (data instanceof DomeEnumeration)
return enumerationEditor;
else if (data instanceof DomeFile)
return fileEditor;
else if (data instanceof DomeList)
return listEditor;
}
else if (column == 2)
{
Object model = BuildMode.getCurrentModelFrame().getGui().getGuiObject();
if (model instanceof PluginModel)
{
defaultCellEditor.setClickCountToStart(1);
return defaultCellEditor;
}
else
{
return mappingEditor;
}
}
return null;
}
public void setValueAt(Object value, int column)
{
if (value == null) return;
if (column == 0) // name
((DomeObject) object).setName(value.toString());
else if (column == 1) {
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeBoolean)
((DomeBoolean) data).setBooleanValue((Boolean) value);
else if (data instanceof DomeReal)
((DomeReal) data).setRealValue((Double) value);
else if (data instanceof DomeInteger)
((DomeInteger) data).setIntegerValue((Integer) value);
else if (data instanceof DomeString)
((DomeString) data).setValue((String) value);
} else if (column == 2) {
Object model = BuildMode.getCurrentModelFrame().getGui().getGuiObject();
if (model instanceof PluginModel) {
PluginMappingManager pmgr = ((PluginModelBuilder) model).getPluginMappingManager();
pmgr.addMapping((Parameter) object, value);
}
}
}
public static String getNames(Collection items)
{
if (items == null || items.size() == 0) return "";
Object[] objs = items.toArray();
if (objs.length == 1) return ((DomeObject) objs[0]).getName();
if (objs.length == 2)
return ((DomeObject) objs[0]).getName() +
" and " + ((DomeObject) objs[1]).getName();
// 3 or more objects
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < objs.length - 1; ++i) {
sb.append(((DomeObject) objs[i]).getName() + ", ");
}
sb.append("and " + ((DomeObject) objs[objs.length - 1]).getName());
return sb.toString();
}
}
public static class VariableOptimizationTableObject extends DomeTableObject
{
protected DefaultRenderer _defaultRenderer = new DefaultRenderer();
protected DomeRealValueRenderer _realRenderer = new DomeRealValueRenderer();
protected DomeStringValueRenderer _stringRenderer = new DomeStringValueRenderer();
protected RealBuildEditor _realEditor = new RealBuildEditor();
protected StringBuildEditor _stringEditor = new StringBuildEditor();
protected DefaultCellEditor _defaultCellEditor = new DefaultCellEditor(Templates.makeTextField(""));
protected MappingCellEditor _mappingEditor = new MappingCellEditor(object);
protected DataObject _currentData;
protected static final String NOTHING = "";
protected VariableParameter _variableParameter;
protected static final int VALUE_COLUMN = 1;
protected static final int LOWER_LIMIT_COLUMN = 2;
protected static final int UPPER_LIMIT_COLUMN = 3;
protected boolean _hasLostFocus = false; // this is a fix for text messages showing up twice
protected PropertyChangeListener dataValueListener = new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
String property = e.getPropertyName();
if (property.equals("value") || property.equals("unit"))
{
fireTableObjectChanged(VALUE_COLUMN);
}
}
};
protected class ParameterPropertyListener implements PropertyChangeListener
{
private int _column;
public ParameterPropertyListener(int column)
{
this._column = column;
}
public void propertyChange(PropertyChangeEvent e)
{
String property = e.getPropertyName();
if(property.equals("value") || property.equals("unit"))
fireTableObjectChanged(this._column);
}
}
public VariableOptimizationTableObject(Parameter obj, boolean[] isEditable)
{
super(obj, isEditable); // make all columns editable
_currentData = ((Parameter) object).getCurrentDataObject();
_currentData.addPropertyChangeListener(dataValueListener);
((Parameter)object).addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
String property = e.getPropertyName();
if(property.equals(Parameter.DATATYPESELECTION))
{
DomeModel m = (DomeModel) ((Parameter)object).getModel();
DataObject oldObject = _currentData;
m.getMappingManager().updateMappingListeners((Parameter)object, oldObject);
}
if(property.equals(Parameter.DATATYPESELECTION) || property.equals(Parameter.CURRENT_TYPE))
{
_currentData.removePropertyChangeListener(dataValueListener);
_currentData = ((Parameter) object).getCurrentDataObject();
_currentData.addPropertyChangeListener(dataValueListener);
fireTableObjectChanged(VALUE_COLUMN);
}
}
});
}
public void addTableTreeObjectListener(DomeObject obj)
{
BuildTreeObjectFactory.getTreeObject(obj).
addTreeObjectListener(new TableTreeObjectListener());
}
public Object getValueAt(int column)
{
if (column == 0)
return ((DomeObject) object).getName();
else if (column == 1)
{ // value
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
return data;
}
else if (column == 2)
{
return this._variableParameter.getLowerLimit();
}
else if (column == 3)
{
return this._variableParameter.getUpperLimit();
}
return NOTHING;
}
protected String getNames(Collection items)
{
if (items == null || items.size() == 0) return "";
Object[] objs = items.toArray();
if (objs.length == 1) return ((DomeObject) objs[0]).getName();
if (objs.length == 2)
return ((DomeObject) objs[0]).getName() +
" and " + ((DomeObject) objs[1]).getName();
// 3 or more objects
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < objs.length - 1; ++i) {
sb.append(((DomeObject) objs[i]).getName() + ", ");
}
sb.append("and " + ((DomeObject) objs[objs.length - 1]).getName());
return sb.toString();
}
public TableCellRenderer getRendererAt(int column)
{
if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
return this._realRenderer;
}
else if (column == 2)
return this._realRenderer;
else if (column == 3)
return this._realRenderer;
return null;
}
public TableCellEditor getEditorAt(int column)
{
if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
return this._realEditor;
}
else if (column == 2)
return this._realEditor;
else if (column == 3)
return this._realEditor;
return null;
}
public void setValueAt(Object value, int column)
{
if (value == null) return;
if (column == 0) // name
((DomeObject) object).setName(value.toString());
else if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
((DomeReal) data).setRealValue((Double) value);
}
else if (column == 2)
{
if (_variableParameter.isValidLowerLimit((Double)value))
_variableParameter.setLowerLimit((Double)value);
else
{
if (!_hasLostFocus)
{
// UGLY hack to prevent the dialog box from showing up twice when the gui is out of focus
_hasLostFocus = true;
OneButton1Msg.showWarning(null, "Build Mode Warning", "Lower limit of parameter '" + _variableParameter.getParameter().getName()
+ "' must be less than the parameter value.", "OK", OneButton1Msg.DEFAULT_SIZE);
_hasLostFocus = false;
}
}
}
else if (column == 3)
{
if (_variableParameter.isValidUpperLimit((Double)value))
_variableParameter.setUpperLimit((Double)value);
else
{
if (!_hasLostFocus)
{
// UGLY hack to prevent the dialog box from showing up twice when the gui is out of focus
_hasLostFocus = true;
OneButton1Msg.showWarning(null, "Build Mode Warning", "Upper limit of parameter '" + _variableParameter.getParameter().getName()
+ "' must be greater than the parameter value.", "OK", OneButton1Msg.DEFAULT_SIZE);
_hasLostFocus = false;
}
}
}
}
}
public static class ModelVariableOptimizationTableObject extends VariableOptimizationTableObject
{
public static final int MAPPING_COLUMN = 4;
protected MappingChangeListener mappingChangeListener = new MappingChangeListener()
{
public void mappingChanged(MappingChangeEvent event)
{
fireTableObjectChanged(MAPPING_COLUMN);
}
};
protected MappingNameChangeListener mappingNameChangeListener = new MappingNameChangeListener()
{
public void mappingNameChanged(MappingNameChangeEvent event)
{
fireTableObjectChanged(MAPPING_COLUMN);
}
};
public ModelVariableOptimizationTableObject(Parameter obj)
{
super(obj, new boolean[]{true, true, true, true, true});
Model m = obj.getModel();
if (m != null)
{
_variableParameter = (VariableParameter) ((OptimizationToolBuild) m).getOptimizationToolVariableParameterMap().get(obj);
_variableParameter.getUpperLimit().addPropertyChangeListener(new ParameterPropertyListener(UPPER_LIMIT_COLUMN));
_variableParameter.getLowerLimit().addPropertyChangeListener(new ParameterPropertyListener(LOWER_LIMIT_COLUMN));
((OptimizationToolBuild) m).getMappingManager().addMappingChangeListener(obj, mappingChangeListener);
((OptimizationToolBuild) m).getMappingManager().addMappingNameChangeListener(obj, mappingNameChangeListener);
}
}
public Object getValueAt(int column)
{
if(column == 4)
{
Collection c = ((AnalysisTool)((Parameter)this.object).getModel()).getMappingManager().getMappingsForParameter((Parameter)this.object);
if (c.isEmpty()) return NOTHING;
return getNames(c);
}
else
return super.getValueAt(column);
}
}
public static class InterfaceVariableOptimizationTableObject extends VariableOptimizationTableObject
{
protected Renderers.BooleanCheckBoxRenderer _booleanRenderer = new Renderers.BooleanCheckBoxRenderer();
protected Editors.BooleanCheckBoxEditor _booleanEditor = new Editors.BooleanCheckBoxEditor();
private static final int ACTIVE_COLUMN = 4;
private static final int MAPPING_COLUMN = 5;
protected MappingChangeListener mappingChangeListener = new MappingChangeListener()
{
public void mappingChanged(MappingChangeEvent event)
{
fireTableObjectChanged(MAPPING_COLUMN);
}
};
protected MappingNameChangeListener mappingNameChangeListener = new MappingNameChangeListener()
{
public void mappingNameChanged(MappingNameChangeEvent event)
{
fireTableObjectChanged(MAPPING_COLUMN);
}
};
public InterfaceVariableOptimizationTableObject(Parameter obj)
{
super(obj, new boolean[]{true, true, true, true, true, true}); // make all columns editable
Model m = obj.getModel();
if (m != null)
{
OptimizationInterfaceBuild i = (OptimizationInterfaceBuild) obj.getScope();
_variableParameter = (VariableParameter) i.getInterfaceVariableMap().get(obj);
this._variableParameter.getUpperLimit().addPropertyChangeListener(new ParameterPropertyListener(UPPER_LIMIT_COLUMN));
this._variableParameter.getLowerLimit().addPropertyChangeListener(new ParameterPropertyListener(LOWER_LIMIT_COLUMN));
this._variableParameter.getIsActive().addPropertyChangeListener(new ParameterPropertyListener(ACTIVE_COLUMN));
((OptimizationToolBuild)m).getMappingManager().addMappingChangeListener(obj, mappingChangeListener);
((OptimizationToolBuild) m).getMappingManager().addMappingNameChangeListener(obj, mappingNameChangeListener);
}
}
public Object getValueAt(int column)
{
if(column == 4)
{
return this._variableParameter.getIsActiveForEditor();
}
else if (column == 5)
{
Collection c = ((AnalysisTool)((Parameter)this.object).getModel()).getMappingManager().getMappingsForParameter((Parameter)this.object);
if (c.isEmpty()) return NOTHING;
return getNames(c);
}
else
return super.getValueAt(column);
}
public TableCellRenderer getRendererAt(int column)
{
if (column == 4)
return this._booleanRenderer;
else
return super.getRendererAt(column);
}
public TableCellEditor getEditorAt(int column)
{
if (column == 4)
return this._booleanEditor;
else
return super.getEditorAt(column);
}
public void setValueAt(Object value, int column)
{
if (value == null) return;
if (column == 4)
{
this._variableParameter.setIsActive(new BooleanData((Boolean)value));
}
else
super.setValueAt(value,column);
}
}
public static class ObjectiveOptimizationTableObject extends DomeTableObject
{
protected DefaultRenderer _defaultRenderer = new DefaultRenderer();
protected DomeRealValueRenderer _realRenderer = new DomeRealValueRenderer();
protected DomeStringValueRenderer _stringRenderer = new DomeStringValueRenderer();
protected DomeEnumerationRenderer _enumerationRenderer = new DomeEnumerationRenderer();
protected RealBuildEditor _realEditor = new RealBuildEditor();
protected StringBuildEditor _stringEditor = new StringBuildEditor();
protected EnumerationBuildEditor _enumerationEditor = new EnumerationBuildEditor();
protected DefaultCellEditor _defaultCellEditor = new DefaultCellEditor(Templates.makeTextField(""));
protected MappingCellEditor _mappingEditor = new MappingCellEditor(object);
protected DataObject _currentData;
protected ObjectiveParameter _objectiveParameter;
protected static final String NOTHING = "";
protected static final int VALUE_COLUMN = 1;
protected class ParameterPropertyListener implements PropertyChangeListener
{
private int _column;
public ParameterPropertyListener(int column)
{
this._column = column;
}
public void propertyChange(PropertyChangeEvent e)
{
String property = e.getPropertyName();
if (property.equals("value") || property.equals("unit"))
fireTableObjectChanged(this._column);
}
}
public ObjectiveOptimizationTableObject(Parameter obj, boolean[] isEditable)
{
super(obj, isEditable);
this._currentData = ((Parameter) object).getCurrentDataObject();
this._currentData.addPropertyChangeListener(new ParameterPropertyListener(VALUE_COLUMN));
}
public void addTableTreeObjectListener(DomeObject obj)
{
BuildTreeObjectFactory.getTreeObject(obj).
addTreeObjectListener(new TableTreeObjectListener());
}
public Object getValueAt(int column)
{
if (column == 0)
return ((DomeObject) object).getName();
else if (column == 1)
{ // value
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
return data;
}
else if (column == 2)
{
return this._objectiveParameter.getIsMaxOrMin();
}
return NOTHING;
}
protected String getNames(Collection items)
{
if (items == null || items.size() == 0) return "";
Object[] objs = items.toArray();
if (objs.length == 1) return ((DomeObject) objs[0]).getName();
if (objs.length == 2)
return ((DomeObject) objs[0]).getName() +
" and " + ((DomeObject) objs[1]).getName();
// 3 or more objects
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < objs.length - 1; ++i)
{
sb.append(((DomeObject) objs[i]).getName() + ", ");
}
sb.append("and " + ((DomeObject) objs[objs.length - 1]).getName());
return sb.toString();
}
public TableCellRenderer getRendererAt(int column)
{
if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
return this._realRenderer;
}
else if (column == 2)
return this._enumerationRenderer;
return null;
}
public TableCellEditor getEditorAt(int column)
{
if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
return this._realEditor;
}
else if (column == 2)
return this._enumerationEditor;
return null;
}
public void setValueAt(Object value, int column)
{
if (value == null) return;
if (column == 0) // name
((DomeObject) object).setName(value.toString());
else if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
((DomeReal) data).setRealValue((Double) value);
}
else if (column == 2)
{
this._objectiveParameter.setIsMaxOrMin(((DomeEnumeration)value).getLastSelection());
}
}
}
public static class ModelObjectiveOptimizationTableObject extends ObjectiveOptimizationTableObject
{
private static final int MAPPING_COLUMN = 3;
protected MappingChangeListener mappingChangeListener = new MappingChangeListener()
{
public void mappingChanged(MappingChangeEvent event)
{
fireTableObjectChanged(MAPPING_COLUMN);
}
};
protected MappingNameChangeListener mappingNameChangeListener = new MappingNameChangeListener()
{
public void mappingNameChanged(MappingNameChangeEvent event)
{
fireTableObjectChanged(MAPPING_COLUMN);
}
};
public ModelObjectiveOptimizationTableObject(Parameter obj)
{
super(obj, new boolean[]{true, true, true, true});
Model m = obj.getModel();
if (m != null)
{
_objectiveParameter = (ObjectiveParameter) ((OptimizationToolBuild) m).getOptimizationToolObjectiveParameterMap().get(obj);
((OptimizationToolBuild) m).getMappingManager().addMappingChangeListener(obj, mappingChangeListener);
((OptimizationToolBuild) m).getMappingManager().addMappingNameChangeListener(obj, mappingNameChangeListener);
}
}
public Object getValueAt(int column)
{
if (column == MAPPING_COLUMN)
{
Collection c = ((AnalysisTool)((Parameter)this.object).getModel()).getMappingManager().getMappingsForParameter((Parameter)this.object);
if(c.isEmpty())
return NOTHING;
return getNames(c);
}
else
return super.getValueAt(column);
}
}
public static class InterfaceObjectiveOptimizationTableObject extends ObjectiveOptimizationTableObject
{
protected Renderers.BooleanCheckBoxRenderer _booleanRenderer = new Renderers.BooleanCheckBoxRenderer();
protected Editors.BooleanCheckBoxEditor _booleanEditor = new Editors.BooleanCheckBoxEditor();
private static final int ACTIVE_COLUMN = 3;
private static final int MAPPING_COLUMN = 4;
protected MappingChangeListener mappingChangeListener = new MappingChangeListener()
{
public void mappingChanged(MappingChangeEvent event)
{
fireTableObjectChanged(MAPPING_COLUMN);
}
};
protected MappingNameChangeListener mappingNameChangeListener = new MappingNameChangeListener()
{
public void mappingNameChanged(MappingNameChangeEvent event)
{
fireTableObjectChanged(MAPPING_COLUMN);
}
};
public InterfaceObjectiveOptimizationTableObject(Parameter obj)
{
super(obj, new boolean[]{true, true, true, true, true}); // make all columns editable
Model m = obj.getModel();
if (m != null)
{
OptimizationInterfaceBuild i = (OptimizationInterfaceBuild) obj.getScope();
_objectiveParameter = (ObjectiveParameter) i.getInterfaceObjectiveMap().get(obj);
_objectiveParameter.getIsActive().addPropertyChangeListener(new ParameterPropertyListener(ACTIVE_COLUMN));
((OptimizationToolBuild) m).getMappingManager().addMappingChangeListener(obj, mappingChangeListener);
((OptimizationToolBuild) m).getMappingManager().addMappingNameChangeListener(obj, mappingNameChangeListener);
}
}
public Object getValueAt(int column)
{
if (column == 3)
{
return this._objectiveParameter.getIsActiveForEditor();
}
else if (column == 4)
{
Collection c = ((AnalysisTool)((Parameter)this.object).getModel()).getMappingManager().getMappingsForParameter((Parameter)this.object);
if(c.isEmpty())
return NOTHING;
return getNames(c);
}
else
return super.getValueAt(column);
}
public TableCellRenderer getRendererAt(int column)
{
if (column == 3)
return this._booleanRenderer;
else
return super.getRendererAt(column);
}
public TableCellEditor getEditorAt(int column)
{
if (column == 3)
return this._booleanEditor;
else if (column == 4)
{
this._defaultCellEditor.setClickCountToStart(1);
return this._defaultCellEditor;
}
else
return super.getEditorAt(column);
}
public void setValueAt(Object value, int column)
{
if (column == 3)
{
this._objectiveParameter.setIsActive(new BooleanData((Boolean) value));
}
else if (column == 4)
{
Object model = BuildMode.getCurrentModelFrame().getGui().getGuiObject();
ToolMappingManager tmgr = ((OptimizationToolBuild) model).getToolMappingManager();
tmgr.addMapping((Parameter) object, value);
}
else
super.setValueAt(value, column);
}
}
public static class OptimizationParameterTableObject extends DomeTableObject
{
protected DefaultRenderer _defaultRenderer = new DefaultRenderer();
protected DomeRealValueRenderer _realRenderer = new DomeRealValueRenderer();
protected DomeStringValueRenderer _stringRenderer = new DomeStringValueRenderer();
protected DomeEnumerationRenderer _enumerationRenderer = new DomeEnumerationRenderer();
protected Renderers.BooleanCheckBoxRenderer _booleanRenderer = new Renderers.BooleanCheckBoxRenderer();
protected Editors.BooleanCheckBoxEditor _booleanEditor = new Editors.BooleanCheckBoxEditor();
protected RealBuildEditor _realEditor = new RealBuildEditor();
protected StringBuildEditor _stringEditor = new StringBuildEditor();
protected EnumerationBuildEditor _enumerationEditor = new EnumerationBuildEditor();
protected DefaultCellEditor _defaultCellEditor = new DefaultCellEditor(Templates.makeTextField(""));
protected MappingCellEditor _mappingEditor = new MappingCellEditor(object);
protected DataObject _currentData;
private OptimizationParameter _optimizationParameter;
protected static final String NOTHING = "";
private static final int VALUE_COLUMN = 1;
private static final int ACTIVE_COLUMN = 2;
protected class QMOOListener implements PropertyChangeListener
{
private int _column;
public QMOOListener(int column)
{
this._column = column;
}
public void propertyChange(PropertyChangeEvent e)
{
String property = e.getPropertyName();
if (property.equals("value") || property.equals("unit"))
fireTableObjectChanged(this._column);
}
}
protected MappingChangeListener mappingChangeListener = new MappingChangeListener()
{
public void mappingChanged(MappingChangeEvent event)
{
fireTableObjectChanged(3);
}
};
protected MappingNameChangeListener mappingNameChangeListener = new MappingNameChangeListener()
{
public void mappingNameChanged(MappingNameChangeEvent event)
{
fireTableObjectChanged(3);
}
};
public OptimizationParameterTableObject(Parameter obj)
{
super(obj, new boolean[]{true, true, true, true}); // make all columns editable
this._currentData = ((Parameter) object).getCurrentDataObject();
this._currentData.addPropertyChangeListener(new QMOOListener(VALUE_COLUMN));
ModelObjectScope scope = obj.getScope();
if (scope instanceof OptimizationInterfaceBuild)
{
if (((OptimizationInterfaceBuild) scope).getInterfaceOptimizationMap().containsKey(object))
{
_optimizationParameter = (OptimizationParameter) ((OptimizationInterfaceBuild) scope).getInterfaceOptimizationMap().get(object);
}
else
OneButton1Msg.showWarning(null, "build interface error", "parameter not found", "OK", new Dimension(150, 75));
}
Model m = obj.getModel();
if (m != null)
{
_optimizationParameter.getIsActive().addPropertyChangeListener(new QMOOListener(ACTIVE_COLUMN));
((OptimizationToolBuild) m).getMappingManager().addMappingChangeListener(obj, mappingChangeListener);
((OptimizationToolBuild) m).getMappingManager().addMappingNameChangeListener(obj, mappingNameChangeListener);
}
}
public void addTableTreeObjectListener(DomeObject obj)
{
BuildTreeObjectFactory.getTreeObject(obj).
addTreeObjectListener(new TableTreeObjectListener());
}
public Object getValueAt(int column)
{
if (column == 0)
return ((DomeObject) object).getName();
else if (column == 1)
{ // value
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
return data;
}
else if (column == 2)
{
return _optimizationParameter.getIsActiveForEditor();
}
else if (column == 3)
{
Collection c = ((AnalysisTool) ((Parameter) this.object).getModel()).getMappingManager().getMappingsForParameter((Parameter) this.object);
if (c.isEmpty()) return NOTHING;
return getNames(c);
}
return NOTHING;
}
protected String getNames(Collection items)
{
if (items == null || items.size() == 0) return "";
Object[] objs = items.toArray();
if (objs.length == 1) return ((DomeObject) objs[0]).getName();
if (objs.length == 2)
return ((DomeObject) objs[0]).getName() +
" and " + ((DomeObject) objs[1]).getName();
// 3 or more objects
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < objs.length - 1; ++i)
{
sb.append(((DomeObject) objs[i]).getName() + ", ");
}
sb.append("and " + ((DomeObject) objs[objs.length - 1]).getName());
return sb.toString();
}
public TableCellRenderer getRendererAt(int column)
{
if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeBoolean)
return this._defaultRenderer;
else if (data instanceof DomeReal)
return this._realRenderer;
else if (data instanceof DomeString)
return this._stringRenderer;
}
else if (column == 2)
return this._booleanRenderer;
return null;
}
public TableCellEditor getEditorAt(int column)
{
if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeBoolean)
return this._booleanEditor;
else if (data instanceof DomeReal)
return this._realEditor;
else if (data instanceof DomeString)
return this._stringEditor;
}
else if (column == 2)
return this._booleanEditor;
else if (column == 3)
{
this._defaultCellEditor.setClickCountToStart(1);
return this._defaultCellEditor;
}
return null;
}
public void setValueAt(Object value, int column)
{
if (value == null) return;
if (column == 0) // name
((DomeObject) object).setName(value.toString());
else if (column == 1)
{
DataObject data = ((Parameter) object).getCurrentDataObject();
if (data instanceof DomeReal)
((DomeReal) data).setRealValue((Double) value);
}
else if (column == 2)
{
_optimizationParameter.setIsActive(new BooleanData((Boolean) value));
}
else if (column == 3)
{
Object model = BuildMode.getCurrentModelFrame().getGui().getGuiObject();
ToolMappingManager tmgr = ((OptimizationToolBuild) model).getToolMappingManager();
tmgr.addMapping((Parameter) object, value);
}
}
}
}
| 41.66646
| 226
| 0.622666
|
9b83e0af3e493f61a030bb1966d530b86bfd7557
| 237
|
package com.fnl.caesar.sso.dao;
import com.fnl.caesar.sso.model.UserInfo;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author dengcheng
*/
public interface UserInfoDao extends JpaRepository<UserInfo,Long> {
}
| 21.545455
| 67
| 0.78481
|
8f055f66906538ebc239246daca81cc8d0aef6cd
| 248
|
package com.java.tech.delegate;
/**
* created by Jason on 2020/2/23
*/
public class SimpleExecutor extends BaseExecutor {
@Override
public String query(String request) {
return "Simple Executor is executing:" + request;
}
}
| 19.076923
| 57
| 0.681452
|
e30fdaa6cc496036bbbc70bc0cfcdbf8e185ed98
| 6,724
|
package ch.rweiss.terminal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import ch.rweiss.check.Check;
public class StyledText
{
public static final StyledText EMPTY = new StyledText("");
private final List<Part> parts;
public StyledText(String text)
{
this(text, null);
}
public StyledText(String text, Style style)
{
Check.parameter("text").withValue(text).isNotNull();
parts = Arrays.asList(new Part(text, style));
}
private StyledText(List<Part> parts)
{
Check.parameter("parts").withValue(parts).isNotNull();
Check.parameter("parts.size()").withValue(parts.size()).isGreaterOrEqualTo(1);
this.parts = Collections.unmodifiableList(parts);
}
public StyledText append(String text)
{
return append(new StyledText(text, lastPart().style));
}
public StyledText append(String text, Style style)
{
return append(new StyledText(text, style));
}
public StyledText append(StyledText text)
{
Check.parameter("text").withValue(text).isNotNull();
List<Part> mergedParts = new ArrayList<>();
Part lastPart = lastPart();
Part firstPart = text.firstPart();
if (Objects.equals(lastPart.style, firstPart.style))
{
mergedParts.addAll(parts.subList(0, parts.size()-1));
Part mergedPart = new Part(lastPart.text + firstPart.text, lastPart.style);
mergedParts.add(mergedPart);
mergedParts.addAll(text.parts.subList(1, text.parts.size()));
}
else
{
mergedParts.addAll(parts);
mergedParts.addAll(text.parts);
}
return new StyledText(mergedParts);
}
public StyledText appendLeft(String text)
{
if (length() == 0)
{
return new StyledText(text, firstPart().style());
}
return new StyledText(text, firstPart().style()).append(this);
}
public StyledText sub(int startPos, int length)
{
Check.parameter("startPos").withValue(startPos).isGreaterOrEqualTo(0).isLessThan(length());
Check.parameter("length").withValue(length).isGreaterOrEqualTo(0);
if (startPos == 0 && length >= length())
{
return this;
}
List<Part> subParts = new ArrayList<>();
int partStartPos = 0;
int totalLength = 0;
int endPos = startPos + length;
for (Part part : parts)
{
int partLength = part.length();
int partEndPos = partStartPos+partLength;
if (partStartPos <= startPos && partEndPos > startPos)
{
Part startPart = part.subtext(startPos-partStartPos, length);
totalLength = startPart.length();
subParts.add(startPart);
}
else if (partStartPos > startPos && partEndPos < endPos)
{
subParts.add(part);
totalLength = part.length();
}
else if (partStartPos > startPos && partEndPos >= endPos)
{
Part endPart = part.subtext(0, partLength - (partEndPos- endPos));
subParts.add(endPart);
totalLength = endPart.length();
}
if (totalLength >= length && subParts.size() > 0)
{
break;
}
partStartPos += part.length();
}
return new StyledText(subParts);
}
public StyledText left(int length)
{
return sub(0, length);
}
public StyledText right(int length)
{
int startPos = length()-length;
startPos = Math.max(0, startPos);
startPos = Math.min(length()-1, startPos);
return sub(startPos, length);
}
public int length()
{
return parts
.stream()
.mapToInt(part -> part.text.length())
.sum();
}
public int indexOf(int startPos, char character)
{
Check.parameter("startPos").withValue(startPos).isPositive().isLessThan(length());
for (int pos = startPos; pos < length(); pos++)
{
if (charAt(pos) == character)
{
return pos;
}
}
return -1;
}
private char charAt(int pos)
{
Check.parameter("pos").withValue(pos).isPositive().isLessThan(length());
int startPos = 0;
for (Part part : parts)
{
if (pos >= startPos && pos < startPos + part.length())
{
return part.text().charAt(pos-startPos);
}
startPos += part.length();
}
throw new IllegalStateException("There is a bug in the code");
}
private Part firstPart()
{
return parts.get(0);
}
private Part lastPart()
{
return parts.get(parts.size()-1);
}
List<Part> parts()
{
return parts;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (obj.getClass() != StyledText.class)
{
return false;
}
StyledText other = (StyledText) obj;
return parts.equals(other.parts);
}
@Override
public int hashCode()
{
return parts.hashCode();
}
@Override
public String toString()
{
return parts
.stream()
.map(part -> part.toString())
.collect(Collectors.joining());
}
static final class Part
{
private final String text;
private final Style style;
private Part(String text, Style style)
{
this.text = text;
this.style = style;
}
public Part subtext(int startPos, int length)
{
if (startPos == 0 && length > length())
{
return this;
}
if (startPos + length > length())
{
length = length()-startPos;
}
int endPos = startPos+length;
return new Part(text.substring(startPos, endPos), style);
}
public int length()
{
return text.length();
}
String text()
{
return text;
}
Style style()
{
return style;
}
@Override
public String toString()
{
return text;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (obj.getClass() != Part.class)
{
return false;
}
Part other = (Part) obj;
return Objects.equals(text, other.text) &&
Objects.equals(style, other.style);
}
@Override
public int hashCode()
{
return Objects.hash(text, style);
}
}
}
| 23.186207
| 96
| 0.565586
|
87110c73c5fde892ffd5e4cee44e22b202099bf3
| 4,970
|
package quickdocs.storage;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import quickdocs.commons.exceptions.IllegalValueException;
import quickdocs.model.patient.Address;
import quickdocs.model.patient.Contact;
import quickdocs.model.patient.Dob;
import quickdocs.model.patient.Email;
import quickdocs.model.patient.Gender;
import quickdocs.model.patient.Name;
import quickdocs.model.patient.Nric;
import quickdocs.model.patient.Patient;
import quickdocs.model.tag.Tag;
import quickdocs.testutil.Assert;
public class JsonAdaptedPatientTest {
private static final String INVALID_NAME = "R@chel";
private static final String INVALID_NRIC = "S1234567X";
private static final String INVALID_EMAIL = "Rachel@gmail";
private static final String INVALID_ADDRESS = "@@@@@";
private static final String INVALID_CONTACT = "888899999";
private static final String INVALID_GENDER = "N";
private static final String INVALID_DOB = "31-02-1999";
private static final String INVALID_TAG = "D|4b3t35";
private static final String VALID_NAME = "Rachel";
private static final String VALID_NRIC = "S1234567J";
private static final String VALID_EMAIL = "Rachel@gmail.com";
private static final String VALID_ADDRESS = "4 admiralty Road";
private static final String VALID_CONTACT = "88888888";
private static final String VALID_GENDER = "F";
private static final String VALID_DOB = "2000-02-29";
private static final List<JsonAdaptedTag> VALID_TAG = new ArrayList<>(
Arrays.asList(new JsonAdaptedTag("Diabetes")));
private static final Patient EXPECTED = new Patient(
new Name(VALID_NAME),
new Nric(VALID_NRIC),
new Email(VALID_EMAIL),
new Address(VALID_ADDRESS),
new Contact(VALID_CONTACT),
new Gender(VALID_GENDER),
new Dob(VALID_DOB),
new ArrayList<Tag>(Arrays.asList(new Tag("Diabetes")))
);
@Test
public void toModelType_validPatientDetails_returnsPatient() throws Exception {
JsonAdaptedPatient patient = new JsonAdaptedPatient(VALID_NAME, VALID_NRIC, VALID_EMAIL,
VALID_ADDRESS, VALID_CONTACT, VALID_GENDER, VALID_DOB, VALID_TAG);
assertEquals(EXPECTED, patient.toModelType());
}
@Test
public void toModelType_invalidPatientdetails() {
// Name testing
JsonAdaptedPatient patient = new JsonAdaptedPatient(INVALID_NAME, VALID_NRIC, VALID_EMAIL,
VALID_ADDRESS, VALID_CONTACT, VALID_GENDER, VALID_DOB, VALID_TAG);
Assert.assertThrows(IllegalArgumentException.class, Name.NAME_CONSTRAINTS, patient::toModelType);
// NRIC testing
patient = new JsonAdaptedPatient(VALID_NAME, INVALID_NRIC, VALID_EMAIL,
VALID_ADDRESS, VALID_CONTACT, VALID_GENDER, VALID_DOB, VALID_TAG);
Assert.assertThrows(IllegalArgumentException.class, Nric.NRIC_CONSTRAINTS, patient::toModelType);
// Email testing
patient = new JsonAdaptedPatient(VALID_NAME, VALID_NRIC, INVALID_EMAIL,
VALID_ADDRESS, VALID_CONTACT, VALID_GENDER, VALID_DOB, VALID_TAG);
Assert.assertThrows(IllegalArgumentException.class, Email.EMAIL_CONSTRAINTS, patient::toModelType);
// address testing
patient = new JsonAdaptedPatient(VALID_NAME, VALID_NRIC, VALID_EMAIL,
INVALID_ADDRESS, VALID_CONTACT, VALID_GENDER, VALID_DOB, VALID_TAG);
Assert.assertThrows(IllegalArgumentException.class, Address.ADDRESS_CONSTRAINTS, patient::toModelType);
// contact testing
patient = new JsonAdaptedPatient(VALID_NAME, VALID_NRIC, VALID_EMAIL,
VALID_ADDRESS, INVALID_CONTACT, VALID_GENDER, VALID_DOB, VALID_TAG);
Assert.assertThrows(IllegalArgumentException.class, Contact.CONTACT_CONSTRAINTS, patient::toModelType);
// gender testing
patient = new JsonAdaptedPatient(VALID_NAME, VALID_NRIC, VALID_EMAIL,
VALID_ADDRESS, VALID_CONTACT, INVALID_GENDER, VALID_DOB, VALID_TAG);
Assert.assertThrows(IllegalArgumentException.class, Gender.GENDER_CONSTRAINTS, patient::toModelType);
// date of birth testing
patient = new JsonAdaptedPatient(VALID_NAME, VALID_NRIC, VALID_EMAIL,
VALID_ADDRESS, VALID_CONTACT, VALID_GENDER, INVALID_DOB, VALID_TAG);
Assert.assertThrows(IllegalArgumentException.class, Dob.DOB_CONSTRAINTS, patient::toModelType);
// invalid tags
List<JsonAdaptedTag> invalidTags = new ArrayList<>();
invalidTags.add(new JsonAdaptedTag(INVALID_TAG));
patient = new JsonAdaptedPatient(VALID_NAME, VALID_NRIC, VALID_EMAIL,
VALID_ADDRESS, VALID_CONTACT, VALID_GENDER, VALID_DOB, invalidTags);
Assert.assertThrows(IllegalValueException.class, patient::toModelType);
}
}
| 45.59633
| 111
| 0.726559
|
26e931d2fd19e4a3df85af500f4c1fbbf0b41c67
| 6,949
|
package back_end;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.function.Consumer;
import Grids.Grid;
import Grids.HexagonalGrids.*;
import Grids.RectangleGrids.*;
import Grids.TriangularGrid.*;
import utilities.GridLocation;
/**
* Abstract class that captures the concept of a simulation.
* Contains the Grid of cells, and updates the cell when the API updateCells() is called.
*
*
* @author Yuxiang He
*@author Ashka Stephen
*@author Juan Philippe
*/
public abstract class Simulation
{
private Grid myCellGrid;
private Grid myGroundGrid;
/**
* update the grid based on the cells' current state
* @return the updated myGrid
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchMethodException
*/
public abstract Grid updateGrid();
/**
* creates a Grid object filled with the cell types specified by cellArray
* @param cellArray
* @return
*/
public Grid createCellGrid(Cell[][] cellArray)
{
Constructor<? extends Grid> constructor = null;
try {
constructor = myCellGrid.getClass().getConstructor(Cell[][].class);
} catch (NoSuchMethodException | SecurityException e) {
throw new Error("No such constructor");
}
try {
return constructor.newInstance(cellArray);
} catch (Exception e) {
throw new Error("No such constructor");
}
}
/**
* Creates a copy of a Cell[][] array, with each cell in the returned array also a copy of the corresponding original one.
* Used for updateGrid in sub-classes. Since the new, updated grid needs information about its current state,
* the array copied by this method provides a 'snapshot' of the previous-iteration state while the myGrid is being updated.
* @param oldArray
* @return copiedArray a copy of old array
* @throws Error when there is no such constructor found for the cell. Not possible in our current code.
*/
protected Cell[][] deepCopyCellArray(Cell[][] oldArray){
int numRows = oldArray.length;
int numCols = oldArray[0].length;
Cell[][] copiedArray = new Cell[numRows][numCols];
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
Constructor<? extends Cell> constructor = null;
try {
constructor = oldArray[row][col].getClass().getConstructor(oldArray[row][col].getClass());
} catch (NoSuchMethodException | SecurityException e) {
throw new Error("No available constructor");
}
try {
Cell oldLocation = oldArray[row][col];
copiedArray[row][col] = constructor.newInstance(oldLocation);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new Error("No available constructor");
}
}
}
return copiedArray;
}
/**
* generates a GridLocation such that myGrid.getCellAt(GridLocation) is empty for putting a new cell
* AND GridLocation is not its current position
* simulates a cell moving to somewhere else
* @return GridLocation specifies a new empty location in myGrid
*/
protected abstract GridLocation findEmptySpot(Grid grid, int currentRow, int currentCol);
/**
* getter method
* @return Grid containing cell info
*/
public Grid getCellGrid(){
return myCellGrid;
}
/**
* getter method
* @return Grid containing ground info
*/
public Grid getGroundGrid(){
return myGroundGrid;
}
/**
* setter method for myCellGrid
*/
protected void setCellGrid(Grid grid){
myCellGrid=grid;
}
/**
* setter method for myGroundGrid
*/
protected void setGroundGrid(Grid groundGrid){
myGroundGrid = groundGrid;
}
/**
* creates a new grid with the defined configuration (whose origin lies in simulation builder) in terms of bounds, shapes and celltype
* @param gridBoundsType
* @param shapeType
* @param cellArray
*/
protected void makeGrid(String gridBoundsType, String shapeType, Cell[][] cellArray)
{
if (gridBoundsType.equals("Toroidal") && shapeType.equals("Rectangular"))
setCellGrid(new RectangleToroidalGrid(cellArray));
else if (gridBoundsType.equals("Finite") && shapeType.equals("Rectangular"))
setCellGrid(new RectangleFiniteGrid(cellArray));
else if (gridBoundsType.equals("Infinite") && shapeType.equals("Rectangular"))
setCellGrid(new RectangleInfiniteGrid(cellArray));
else if (gridBoundsType.equals("Toroidal") && shapeType.equals("Triangular"))
setCellGrid(new TriangularToroidalGrid(cellArray));
else if (gridBoundsType.equals("Finite") && shapeType.equals("Triangular"))
setCellGrid(new TriangularFiniteGrid(cellArray));
else if (gridBoundsType.equals("Toroidal") && shapeType.equals("Hexagonal"))
setCellGrid(new HexToroidalGrid(cellArray));
else if (gridBoundsType.equals("Finite") && shapeType.equals("Hexagonal"))
setCellGrid(new HexFiniteGrid(cellArray));
else
throw new Error("Incorrect Grid Type");
}
/**
* setter method. Sets sim's myInfo to newInfo
* @param newInfo
*/
public abstract void setSimInfo(SimulationInfo newInfo);
/**
* getter method. Sets sim's myInfo to newInfo
* @param newInfo
*/
public abstract SimulationInfo getSimInfo();
/**
*
* @return number of rows in myCellGrid
*/
public int getNumRows(){
return myCellGrid.getNumRows();
}
/**
*
* @return number of rows in myGroundGrid
* used for ground and regular grid
*/
public int getNumRowsGround(){
return myGroundGrid.getNumRows();
}
/**
* @return number of columns in myCellGrid
*/
public int getNumCols(){
return myCellGrid.getNumCols();
}
/**
* @return number of columns in myGroundGrid
*/
public int getNumColsGround(){
return myGroundGrid.getNumCols();
}
/**
* sets whether there are lines surrounding the cells
* @param linesOn
*/
public void setLines(boolean linesOn)
{
myCellGrid.setLines(linesOn);
}
/**
* returns a list of names of the parameters specific to the simulation
* @return
*/
public abstract Collection<String> getParameterList();
/**
* gets the method to change a particular parameter based on the names of the parameters given in getParameterlist
* used in the sliders
* @param x
* @return
*/
public abstract Consumer<Number> getChangeMethod(String x);
/**
* gets the lower bound of a slider based on a particular parameter in the sim
* @param x
* @return
*/
public abstract double getSliderLowerBound(String x);
/**
* gets the upper bound of a slider based on a particular parameter in the sim
* @param x
* @return
*/
public abstract double getSliderUpperBound(String x);
/**
* gets the current value of a given parameter to initialize the slider with
* @param x
* @return
*/
public abstract double getCurrentValue(String x);
}
| 28.133603
| 136
| 0.714203
|
8aae1e698f97f9342ddc8f26a70744010f14a2db
| 1,112
|
package entity;
import javax.persistence.*;
/**
* Created by ymcvalu on 2017/5/6.
*/
@Entity
@Table(name="clerk_client")
public class Clerk_Client {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
private int clerk; //clerk外键
private int client; //client外键
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getClerk() {
return clerk;
}
public void setClerk(int clerk) {
this.clerk = clerk;
}
public int getClient() {
return client;
}
public void setClient(int client) {
this.client = client;
}
@Override
public boolean equals(Object a){
if(a==null)
return false;
if(a instanceof Clerk_Client)
return id==((Clerk_Client)a).id;
else
return false;
}
@Override
public int hashCode() {
int result=17;
result=result*31+id;
result=result*31+id*id;
result=result*31+id*id*id;
return result;
}
}
| 16.848485
| 55
| 0.563849
|
2adcb533fd7d32be03c06d3185eab02b0cfade90
| 334
|
package com.sai.Multithreading;
/*
Cannot start the same thread twice
*/
public class Example4 extends Thread{
public void run() {
System.out.println("Running");
}
public static void main(String[] args) {
Example4 thread1 = new Example4();
thread1.start();
thread1.start();
}
}
| 18.555556
| 44
| 0.610778
|
7f0286635d449a3a872a4e5aa1e56cad636ad179
| 3,620
|
package com.wayne.gestureverify.view;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.wayne.gestureverify.GestureCallback;
import com.wayne.gestureverify.R;
import com.wayne.gestureverify.model.GesturePoint;
import com.wayne.gestureverify.utils.MobileInfo;
import java.util.ArrayList;
import java.util.List;
public class VerifyContentView extends ViewGroup {
private static final int HORIZONTAL_POINTS_COUNT = 3;
private static final int HORIZONTAL_POINT_GAP_NUM = HORIZONTAL_POINTS_COUNT * 2;
private static final int VERTICAL_POINTS_COUNT = 3;
private static final int VERTICAL_POINT_GAP_NUM = VERTICAL_POINTS_COUNT * 2;
private static final int TOTAL_POINTS_COUNT = HORIZONTAL_POINTS_COUNT * VERTICAL_POINT_GAP_NUM;
private int mPointLength;
private Context mContext;
private boolean isVerify;
private DrawLineView mDrawLineView;
private List<GesturePoint> mPointList;
public VerifyContentView(Context cxt, boolean isVerify, String password, GestureCallback callback) {
super(cxt);
mContext = cxt;
this.isVerify = isVerify;
mPointLength = MobileInfo.getScreenMetrics(mContext).widthPixels / HORIZONTAL_POINTS_COUNT;
initChildList();
mDrawLineView = new DrawLineView(mContext, mPointList, isVerify, password, callback);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < getChildCount(); i++) {
int row = i / 3;
int column = i % 3;
View v = getChildAt(i);
v.layout(column * mPointLength + mPointLength / HORIZONTAL_POINT_GAP_NUM,
row * mPointLength + mPointLength / VERTICAL_POINT_GAP_NUM,
(column + 1) * mPointLength - mPointLength / HORIZONTAL_POINT_GAP_NUM,
(row + 1) * mPointLength - mPointLength / VERTICAL_POINT_GAP_NUM);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
}
}
private void initChildList() {
mPointList = new ArrayList<>();
for (int i = 0; i < TOTAL_POINTS_COUNT; i++) {
ImageView image = new ImageView(mContext);
image.setBackgroundResource(R.mipmap.gesture_node_normal);
addView(image);
invalidate();
int row = i / 3;
int column = i % 3;
int left = column * mPointLength + mPointLength / HORIZONTAL_POINT_GAP_NUM;
int top = row * mPointLength + mPointLength / VERTICAL_POINT_GAP_NUM;
int right = (column + 1) * mPointLength - mPointLength / HORIZONTAL_POINT_GAP_NUM;
int bottom = (row + 1) * mPointLength - mPointLength / VERTICAL_POINT_GAP_NUM;
GesturePoint p = new GesturePoint(left, top, right, bottom, i + 1, image);
mPointList.add(p);
}
}
public void setParentView(ViewGroup parent) {
int with = MobileInfo.getScreenMetrics(mContext).widthPixels;
LayoutParams params = new LayoutParams(with, with);
setLayoutParams(params);
parent.addView(this);
mDrawLineView.setLayoutParams(params);
parent.addView(mDrawLineView);
}
public void clearDrawLineView(long delayMillis) {
mDrawLineView.cleanDrawLineView(delayMillis);
}
}
| 39.347826
| 104
| 0.673757
|
c710d885fca962c7f8b8bafdd2e5b4f0156ec9a2
| 1,673
|
package student.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import student.bean.LoginDetail;
import student.bean.StudentDetail;
import student.service.DaoService;
/**
* Servlet implementation class Login
*/
@WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
HttpSession session=request.getSession(false);
// System.out.println("Session"+session);
try{
LoginDetail ld=(LoginDetail) session.getAttribute("ld");
//out.println(ld.getPassword());
DaoService daos=new DaoService();
StudentDetail sd=new StudentDetail();
sd=daos.loginUser(ld);
if(sd.getEmail()!=null){
session.setAttribute("sd",sd);
response.sendRedirect("view/user/profile.jsp");
}
else{
String message="Either your Userid or your password is incorrect";
request.setAttribute("message",message);
response.sendRedirect("view/user/login.jsp?message="+message);
}
}
catch(Exception ex){
response.sendRedirect("view/user/login.jsp?message="+"Exception occured in on server");
}
}
}
| 24.970149
| 121
| 0.696952
|
921fffefbe581acfe5744f6c50e9804060c84a33
| 2,795
|
package net.mcft.copy.betterstorage.inventory;
import net.mcft.copy.betterstorage.tile.entity.TileEntityContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
/** An inventory that is connected to a TileEntityInventoy. */
public class InventoryTileEntity extends InventoryBetterStorage {
public final TileEntityContainer mainTileEntity;
public final TileEntityContainer[] tileEntities;
public final IInventory inventory;
public final int columns, rows;
public InventoryTileEntity(TileEntityContainer mainTileEntity, TileEntityContainer[] tileEntities, IInventory inventory) {
this.mainTileEntity = mainTileEntity;
this.tileEntities = tileEntities;
this.inventory = inventory;
columns = mainTileEntity.getColumns();
rows = inventory.getSizeInventory() / columns;
}
public InventoryTileEntity(TileEntityContainer mainTileEntity, TileEntityContainer... tileEntities) {
this(mainTileEntity, tileEntities, new InventoryStacks(getAllContents(tileEntities)));
}
public InventoryTileEntity(TileEntityContainer tileEntity, IInventory inventory) {
this(tileEntity, new TileEntityContainer[]{ tileEntity }, inventory);
}
public InventoryTileEntity(TileEntityContainer tileEntity) {
this(tileEntity, new InventoryStacks(tileEntity.contents));
}
private static ItemStack[][] getAllContents(TileEntityContainer... tileEntities) {
ItemStack[][] allContents = new ItemStack[tileEntities.length][];
for (int i = 0; i < tileEntities.length; i++)
allContents[i] = tileEntities[i].contents;
return allContents;
}
@Override
public String getInventoryName() { return mainTileEntity.getContainerTitle(); }
@Override
public boolean hasCustomInventoryName() { return !mainTileEntity.shouldLocalizeTitle(); }
@Override
public int getSizeInventory() { return inventory.getSizeInventory(); }
@Override
public ItemStack getStackInSlot(int slot) { return inventory.getStackInSlot(slot); }
@Override
public void setInventorySlotContents(int slot, ItemStack stack) {
inventory.setInventorySlotContents(slot, stack);
markDirty();
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
return inventory.isItemValidForSlot(slot, stack);
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
for (TileEntityContainer tileEntity : tileEntities)
if (!tileEntity.canPlayerUseContainer(player))
return false;
return true;
}
@Override
public void openInventory() { mainTileEntity.onContainerOpened(); }
@Override
public void closeInventory() { mainTileEntity.onContainerClosed(); }
@Override
public void markDirty() {
inventory.markDirty();
for (TileEntityContainer te : tileEntities)
te.markDirtySuper();
}
}
| 34.9375
| 123
| 0.786047
|
982951432032cd7274ae2bdfd9ce085696c60ce7
| 19,098
|
package org.apache.turbine.om.security;
/*
* 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.
*/
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpSessionBindingEvent;
import org.apache.fulcrum.security.model.turbine.entity.TurbineUser;
import org.apache.fulcrum.security.model.turbine.entity.TurbineUserGroupRole;
import org.apache.fulcrum.security.util.DataBackendException;
import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.services.security.SecurityService;
import org.apache.turbine.util.ObjectUtils;
/**
* This is the Default user implementation. It is a wrapper around
* a TurbineUser object
*
* @author <a href="mailto:tv@apache.org">Thomas Vandahl</a>
* @version $Id: TorqueUser.java 1199856 2011-11-09 17:06:04Z tv $
*/
public class DefaultUserImpl implements User
{
/** Serial version */
private static final long serialVersionUID = -1866504873085624111L;
/** The date on which the user last accessed the application. */
private Date lastAccessDate = null;
/** This is data that will survive a servlet engine restart. */
private Map<String, Object> permStorage = null;
/** This is data that will not survive a servlet engine restart. */
private Map<String, Object> tempStorage = null;
/** The Fulcrum user instance to delegate to */
private TurbineUser userDelegate = null;
/**
* Constructor
*
* @param user the user object to wrap
*/
public DefaultUserImpl(TurbineUser user)
{
super();
setUserDelegate( user );
setCreateDate(new Date());
tempStorage = new HashMap<>(10);
setHasLoggedIn(Boolean.FALSE);
}
/**
* Implement this method if you wish to be notified when the User
* has been Bound to the session.
*
* @param hsbe Indication of value/session binding.
*/
@Override
public void valueBound(HttpSessionBindingEvent hsbe)
{
// Currently we have no need for this method.
}
/**
* Implement this method if you wish to be notified when the User
* has been Unbound from the session.
*
* @param hsbe Indication of value/session unbinding.
*/
@Override
public void valueUnbound(HttpSessionBindingEvent hsbe)
{
try
{
if (hasLoggedIn())
{
SecurityService securityService =
(SecurityService)TurbineServices.getInstance()
.getService(SecurityService.SERVICE_NAME);
securityService.saveOnSessionUnbind(this);
}
}
catch (Exception e)
{
//Log.error("TorqueUser.valueUnbound(): " + e.getMessage(), e);
// To prevent messages being lost in case the logging system
// goes away before sessions get unbound on servlet container
// shutdown, print the stacktrace to the container's console.
e.printStackTrace(System.out);
}
}
/**
* Get the Name of the SecurityEntity.
*
* @return The Name of the SecurityEntity.
*/
@Override
public String getName()
{
return userDelegate.getName();
}
/**
* Sets the Name of the SecurityEntity.
*
* @param name
* Name of the SecurityEntity.
*/
@Override
public void setName(String name)
{
userDelegate.setName(name);
}
/**
* Get the Id of the SecurityEntity.
*
* @return The Id of the SecurityEntity.
*/
@Override
public Object getId()
{
return userDelegate.getId();
}
/**
* Sets the Id of the SecurityEntity.
*
* @param id
* The new Id of the SecurityEntity
*/
@Override
public void setId(Object id)
{
userDelegate.setId(id);
}
/**
* Returns the user's password. This method should not be used by
* the application directly, because it's meaning depends upon
* the implementation of UserManager that manages this particular
* user object. Some implementations will use this attribute for
* storing a password encrypted in some way, other will not use
* it at all, when user entered password is presented to some external
* authority (like NT domain controller) to validate it.
* See also {@link org.apache.turbine.services.security.UserManager#authenticate(User,String)}.
*
* @return A String with the password for the user.
*/
@Override
public String getPassword()
{
return userDelegate.getPassword();
}
/**
* Set password. Application should not use this method
* directly, see {@link #getPassword()}.
* See also {@link org.apache.turbine.services.security.UserManager#changePassword(User,String,String)}.
*
* @param password The new password.
*/
@Override
public void setPassword(String password)
{
userDelegate.setPassword(password);
}
/**
* Returns the first name for this user.
*
* @return A String with the user's first name.
*/
@Override
public String getFirstName()
{
return userDelegate.getFirstName();
}
/**
* Sets the first name for this user.
*
* @param firstName User's first name.
*/
@Override
public void setFirstName(String firstName)
{
userDelegate.setFirstName(firstName);
}
/**
* Returns the last name for this user.
*
* @return A String with the user's last name.
*/
@Override
public String getLastName()
{
return userDelegate.getLastName();
}
/**
* Sets the last name for this user.
*
* @param lastName User's last name.
*/
@Override
public void setLastName(String lastName)
{
userDelegate.setLastName(lastName);
}
/**
* Returns the email address for this user.
*
* @return A String with the user's email address.
*/
@Override
public String getEmail()
{
return userDelegate.getEmail();
}
/**
* Sets the email address.
*
* @param address The email address.
*/
@Override
public void setEmail(String address)
{
userDelegate.setEmail(address);
}
/**
* Returns the value of the objectdata for this user.
* Objectdata is a storage area used
* to store the permanent storage table from the User
* object.
*
* @return The bytes in the objectdata for this user
*/
@Override
public byte[] getObjectdata()
{
return userDelegate.getObjectdata();
}
/**
* Sets the value of the objectdata for the user
*
* @param objectdata The new permanent storage for the user
*/
@Override
public void setObjectdata(byte[] objectdata)
{
userDelegate.setObjectdata(objectdata);
}
/**
* Get the User/Group/Role set associated with this entity
*
* @return a set of User/Group/Role relations
* @throws DataBackendException if there was an error accessing the data
* backend.
*/
@Override
public <T extends TurbineUserGroupRole> Set<T> getUserGroupRoleSet() throws DataBackendException
{
return userDelegate.getUserGroupRoleSet();
}
/**
* Set the User/Group/Role set associated with this entity
*
* @param userGroupRoleSet
* a set of User/Group/Role relations
*/
@Override
public <T extends TurbineUserGroupRole> void setUserGroupRoleSet(Set<T> userGroupRoleSet)
{
userDelegate.setUserGroupRoleSet(userGroupRoleSet);
}
/**
* Add a User/Group/Role relation to this entity
*
* @param userGroupRole
* a User/Group/Role relation to add
* @throws DataBackendException if there was an error accessing the data
* backend.
*/
@Override
public void addUserGroupRole(TurbineUserGroupRole userGroupRole) throws DataBackendException
{
userDelegate.addUserGroupRole(userGroupRole);
}
/**
* Remove a User/Group/Role relation from this entity
*
* @param userGroupRole
* a User/Group/Role relation to remove
* @throws DataBackendException if there was an error accessing the data
* backend.
*/
@Override
public void removeUserGroupRole(TurbineUserGroupRole userGroupRole) throws DataBackendException
{
userDelegate.removeUserGroupRole(userGroupRole);
}
/**
* Gets the access counter for a user from perm storage.
*
* @return The access counter for the user.
*/
@Override
public int getAccessCounter()
{
try
{
return ((Integer) getPerm(User.ACCESS_COUNTER)).intValue();
}
catch (Exception e)
{
return 0;
}
}
/**
* Gets the access counter for a user during a session.
*
* @return The access counter for the user for the session.
*/
@Override
public int getAccessCounterForSession()
{
try
{
return ((Integer) getTemp(User.SESSION_ACCESS_COUNTER)).intValue();
}
catch (Exception e)
{
return 0;
}
}
/**
* Increments the permanent hit counter for the user.
*/
@Override
public void incrementAccessCounter()
{
// Ugh. Race city, here I come...
setAccessCounter(getAccessCounter() + 1);
}
/**
* Increments the session hit counter for the user.
*/
@Override
public void incrementAccessCounterForSession()
{
setAccessCounterForSession(getAccessCounterForSession() + 1);
}
/**
* Sets the access counter for a user, saved in perm storage.
*
* @param cnt The new count.
*/
@Override
public void setAccessCounter(int cnt)
{
setPerm(User.ACCESS_COUNTER, Integer.valueOf(cnt));
}
/**
* Sets the session access counter for a user, saved in temp
* storage.
*
* @param cnt The new count.
*/
@Override
public void setAccessCounterForSession(int cnt)
{
setTemp(User.SESSION_ACCESS_COUNTER, Integer.valueOf(cnt));
}
/**
* Gets the last access date for this User. This is the last time
* that the user object was referenced.
*
* @return A Java Date with the last access date for the user.
*/
@Override
public Date getLastAccessDate()
{
if (lastAccessDate == null)
{
setLastAccessDate();
}
return Date.from( lastAccessDate.toInstant()); //immutable
}
/**
* Sets the last access date for this User. This is the last time
* that the user object was referenced.
*/
@Override
public void setLastAccessDate()
{
lastAccessDate = new Date();
}
/**
* Returns the permanent storage. This is implemented
* as a Map
*
* @return A Map.
*/
@Override
public synchronized Map<String, Object> getPermStorage()
{
if (permStorage == null)
{
byte [] objectdata = getObjectdata();
if (objectdata != null)
{
permStorage = ObjectUtils.deserialize(objectdata);
}
if (permStorage == null)
{
permStorage = new HashMap<>();
}
}
return permStorage;
}
/**
* This should only be used in the case where we want to make the
* data persistent.
*
* @param permStorage A Map.
*/
@Override
public void setPermStorage(Map<String, Object> permStorage)
{
if (permStorage != null)
{
this.permStorage = permStorage;
}
}
/**
* Returns the temporary storage. This is implemented
* as a Map
*
* @return A Map.
*/
@Override
public Map<String, Object> getTempStorage()
{
if (tempStorage == null)
{
tempStorage = new HashMap<>();
}
return tempStorage;
}
/**
* This should only be used in the case where we want to save the
* data to the database.
*
* @param tempStorage A Map.
*/
@Override
public void setTempStorage(Map<String, Object> tempStorage)
{
if (tempStorage != null)
{
this.tempStorage = tempStorage;
}
}
/**
* Get an object from permanent storage.
*
* @param name The object's name.
* @return An Object with the given name.
*/
@Override
public Object getPerm(String name)
{
return getPermStorage().get(name);
}
/**
* Get an object from permanent storage; return default if value
* is null.
*
* @param name The object's name.
* @param def A default value to return.
* @return An Object with the given name.
*/
@Override
public Object getPerm(String name, Object def)
{
try
{
Object val = getPermStorage().get(name);
return (val == null ? def : val);
}
catch (Exception e)
{
return def;
}
}
/**
* Put an object into permanent storage.
*
* @param name The object's name.
* @param value The object.
*/
@Override
public void setPerm(String name, Object value)
{
getPermStorage().put(name, value);
}
/**
* Get an object from temporary storage.
*
* @param name The object's name.
* @return An Object with the given name.
*/
@Override
public Object getTemp(String name)
{
return getTempStorage().get(name);
}
/**
* Get an object from temporary storage; return default if value
* is null.
*
* @param name The object's name.
* @param def A default value to return.
* @return An Object with the given name.
*/
@Override
public Object getTemp(String name, Object def)
{
Object val;
try
{
val = getTempStorage().get(name);
if (val == null)
{
val = def;
}
}
catch (Exception e)
{
val = def;
}
return val;
}
/**
* Put an object into temporary storage.
*
* @param name The object's name.
* @param value The object.
*/
@Override
public void setTemp(String name, Object value)
{
getTempStorage().put(name, value);
}
/**
* Remove an object from temporary storage and return the object.
*
* @param name The name of the object to remove.
* @return An Object.
*/
@Override
public Object removeTemp(String name)
{
return getTempStorage().remove(name);
}
/**
* Returns the confirm value of the user
*
* @return The confirm value of the user
*/
@Override
public String getConfirmed()
{
return (String) getPerm(User.CONFIRM_VALUE);
}
/**
* Sets the new confirm value of the user
*
* @param confirm The new confirm value of the user
*/
@Override
public void setConfirmed(String confirm)
{
setPerm(User.CONFIRM_VALUE, confirm);
}
/**
* Returns the creation date of the user
*
* @return The creation date of the user
*/
@Override
public Date getCreateDate()
{
return (Date)getPerm(CREATE_DATE, new Date());
}
/**
* Sets the new creation date of the user
*
* @param createDate The new creation date of the user
*/
@Override
public void setCreateDate(Date createDate)
{
setPerm(CREATE_DATE, createDate);
}
/**
* Returns the date of the last login of the user
*
* @return The date of the last login of the user
*/
@Override
public Date getLastLogin()
{
return (Date) getPerm(User.LAST_LOGIN);
}
/**
* Sets the new date of the last login of the user
*
* @param lastLogin The new the date of the last login of the user
*/
@Override
public void setLastLogin(Date lastLogin)
{
setPerm(User.LAST_LOGIN, lastLogin);
}
/**
* The user is considered logged in if they have not timed out.
*
* @return Whether the user has logged in.
*/
@Override
public boolean hasLoggedIn()
{
Boolean loggedIn = (Boolean) getTemp(User.HAS_LOGGED_IN);
return loggedIn != null && loggedIn.booleanValue();
}
/**
* This sets whether or not someone has logged in. hasLoggedIn()
* returns this value.
*
* @param value Whether someone has logged in or not.
*/
@Override
public void setHasLoggedIn(Boolean value)
{
setTemp(User.HAS_LOGGED_IN, value);
}
/**
* This method reports whether or not the user has been confirmed
* in the system by checking the User.CONFIRM_VALUE
* column in the users record to see if it is equal to
* User.CONFIRM_DATA.
*
* @return True if the user has been confirmed.
*/
@Override
public boolean isConfirmed()
{
String value = getConfirmed();
return value != null && value.equals(User.CONFIRM_DATA);
}
/**
* Updates the last login date in the database.
*
* @throws Exception A generic exception.
*/
@Override
public void updateLastLogin()
throws Exception
{
setLastLogin(new Date());
}
/* (non-Javadoc)
* @see org.apache.turbine.om.security.UserDelegate#getUserDelegate()
*/
@Override
public TurbineUser getUserDelegate()
{
return userDelegate;
}
/* (non-Javadoc)
* @see org.apache.turbine.om.security.UserDelegate#setUserDelegate(org.apache.fulcrum.security.model.turbine.entity.TurbineUser)
*/
@Override
public void setUserDelegate(TurbineUser userDelegate)
{
this.userDelegate = userDelegate;
}
}
| 25.162055
| 130
| 0.598911
|
7a584a3fba0fb0a5e1d155375b37c22f8def5a01
| 6,111
|
package technion.prime.eclipse.actions;
import java.io.File;
import java.util.Collection;
import java.util.LinkedList;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import technion.prime.utils.JavaFileUtils;
public class CodeSearchDialog extends TitleAreaDialog {
private static final String INVALID_FOLDER_STRING = "<invalid folder>";
private static final String UPDATING_STRING = "<updating...>";
private static final String EMPTY_FOLDER_STRING = "<no matching files found>";
private Text folderText;
private Text typeFilterText;
private List fileList;
private Text queryText;
private String folder;
private String typeFilter;
private String[] files;
private String[] items;
private String query;
private Thread updatingThread;
public CodeSearchDialog(Shell parentShell) {
super(parentShell);
setShellStyle(getShellStyle() | SWT.RESIZE);
}
public CodeSearchDialog withFolder(String s) {
this.folderText.setText(s);
return this;
}
public CodeSearchDialog withTypeFilter(String s) {
typeFilterText.setText(s);
return this;
}
public CodeSearchDialog withQuery(String s) {
queryText.setText(s);
return this;
}
public String getFolder() {
return folder;
}
public String getTypeFilter() {
return typeFilter;
}
public String[] getFiles() {
return files;
}
public String getQuery() {
return query;
}
@Override
public void create() {
super.create();
setTitle("Prime - code search");
}
@Override
protected Control createDialogArea(Composite parent) {
Composite c = createDialogAreaComposite(parent);
createTypeFilterField(c);
createFolderField(c);
createFileList(c);
createQueryField(c);
return c;
}
private void createQueryField(Composite c) {
String tooltip = "Code search query";
Label l = new Label(c, SWT.NONE);
l.setText("Query:");
l.setToolTipText(tooltip);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalSpan = 2;
gridData.verticalSpan = 5;
queryText = new Text(c, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI);
queryText.setLayoutData(gridData);
queryText.setToolTipText(tooltip);
}
private Composite createDialogAreaComposite(Composite parent) {
Composite c = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = 10;
layout.marginWidth = 10;
layout.verticalSpacing = 10;
layout.horizontalSpacing = 10;
layout.numColumns = 3;
c.setLayout(layout);
c.setLayoutData(new GridData(GridData.FILL_BOTH));
c.setFont(parent.getFont());
c.setSize(800, 600);
return c;
}
private void createTypeFilterField(Composite c) {
String tooltip = "Which types to include in the analysis";
Label l = new Label(c, SWT.NONE);
l.setText("Type filter (regex):");
l.setToolTipText(tooltip);
typeFilterText = new Text(c, SWT.BORDER);
typeFilterText.setToolTipText(tooltip);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
typeFilterText.setLayoutData(gridData);
}
private void createFolderField(Composite c) {
String tooltip = "Folder in which to search (recursively) for files to run";
Label l = new Label(c, SWT.NONE);
l.setText("Folder:");
l.setToolTipText(tooltip);
folderText = new Text(c, SWT.BORDER);
folderText.setToolTipText(tooltip);
folderText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
folderText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateList();
}
});
Button b = new Button(c, SWT.NONE);
b.setText("Browse...");
b.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
String path = new DirectoryDialog(CodeSearchDialog.this.getShell()).open();
if (path == null) return;
folderText.setText(path);
//updateList();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
});
}
private void updateList() {
if (updatingThread != null) {
updatingThread.interrupt();
}
fileList.removeAll();
final String path = folderText.getText();
if (new File(path).isDirectory() == false) {
fileList.add(INVALID_FOLDER_STRING);
return;
}
fileList.add(UPDATING_STRING);
updatingThread = new Thread() {
@Override
public void run() {
try {
Collection<String> fileList = new LinkedList<String>(JavaFileUtils.getCachedFilesInFolder(path, true));
if (Thread.interrupted()) return;
items = fileList.toArray(new String[fileList.size()]);
} catch (Exception e) {
return;
}
updateDone();
}
};
updatingThread.start();
}
private void updateDone() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (items.length == 0) {
fileList.removeAll();
fileList.add(EMPTY_FOLDER_STRING);
} else {
fileList.setItems(items);
}
}
});
}
private void createFileList(Composite c) {
fileList = new List(c, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 3;
fileList.setLayoutData(gridData);
}
@Override
protected void okPressed() {
files = fileList.getSelection();
folder = folderText.getText();
typeFilter = typeFilterText.getText();
query = queryText.getText();
super.okPressed();
}
}
| 26.004255
| 108
| 0.719686
|
b8fe7ee73386e7c671ab9a3f800fff4199a4c379
| 4,051
|
/*
* This file is part of creative, licensed under the MIT license
*
* Copyright (c) 2021-2022 Unnamed Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package team.unnamed.creative.server;
import com.sun.net.httpserver.HttpExchange;
import org.jetbrains.annotations.Nullable;
import team.unnamed.creative.ResourcePack;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* Responsible for handling resource-pack requests made by
* Minecraft clients, using this we are able to detect some
* information such as the expected pack format, the requester
* player uuid, username and client version
*/
@FunctionalInterface
public interface ResourcePackRequestHandler {
/**
* Handles a resource pack request, the resulting resource
* pack is written to {@link HttpExchange#getResponseBody()}
*
* <p>An "application/zip" Content-Type header should be set
* when returning a resource-pack, {@link HttpExchange#getResponseHeaders()}</p>
*
* @param request The resource pack request
* @param exchange The HTTP exchange
* @see HttpExchange
*/
void onRequest(ResourcePackRequest request, HttpExchange exchange) throws IOException;
/**
* Handles an unhandled exception when invoking
* {@link ResourcePackRequestHandler#onRequest}
*
* @param e The caught exception
*/
default void onException(Exception e) {
System.err.println("Exception caught when serving a resource-pack");
e.printStackTrace();
}
/**
* Called when an invalid request is made, by default,
* a simple message is sent
*
* @param exchange The http exchange
* @see HttpExchange
*/
default void onInvalidRequest(HttpExchange exchange) throws IOException {
byte[] response = "Please use a Minecraft client".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(400, response.length);
exchange.getResponseBody().write(response);
}
static ResourcePackRequestHandler of(ResourcePack pack, boolean validOnly) {
return new ResourcePackRequestHandler() {
@Override
public void onRequest(@Nullable ResourcePackRequest request, HttpExchange exchange) throws IOException {
if (request != null || !validOnly) {
byte[] data = pack.bytes();
exchange.getResponseHeaders().set("Content-Type", "application/zip");
exchange.sendResponseHeaders(200, data.length);
exchange.getResponseBody().write(data);
} else {
ResourcePackRequestHandler.super.onInvalidRequest(exchange);
}
}
@Override
public void onInvalidRequest(HttpExchange exchange) throws IOException {
onRequest(null, exchange);
}
};
}
static ResourcePackRequestHandler of(ResourcePack pack) {
return of(pack, false);
}
}
| 38.216981
| 116
| 0.690694
|
718e22f3dd34add32ce81ebdee52c967fcec4f9e
| 9,650
|
package com.chequer.axboot.core.config;
import ch.qos.logback.classic.Level;
import com.chequer.axboot.core.code.AXBootTypes;
import com.chequer.axboot.core.context.AppContextManager;
import com.chequer.axboot.core.mybatis.typehandler.*;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.TypeHandler;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.*;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import java.util.Properties;
@Data
@ConfigurationProperties(prefix = "axboot", ignoreInvalidFields = true)
@NoArgsConstructor
public class AXBootContextConfig implements ApplicationContextAware {
private static AXBootContextConfig instance;
private DataSourceConfig dataSource;
private Logging log;
private Application application = new Application();
private Modeler modeler;
@Getter(AccessLevel.NONE)
private String serverName;
private String basePackageName;
private String controllerPackageName;
private String domainPackageName;
private static ApplicationContext applicationContext;
public static synchronized AXBootContextConfig getInstance() {
if (instance == null) {
instance = AppContextManager.getBean("axBootContextConfig", AXBootContextConfig.class);
}
return instance;
}
public String getServerName() {
return System.getProperty("server.name", "localhost");
}
public DataSourceConfig getDataSourceConfig() {
return dataSource;
}
public Logging getLoggingConfig() {
if (log == null) {
log = new Logging();
}
return log;
}
public Modeler getModelerConfig() {
if (modeler == null) {
modeler = new Modeler();
}
return modeler;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public TypeHandler<?>[] getMyBatisTypeHandlers() {
return new TypeHandler<?>[]{
new InstantTypeHandler(),
new LocalDateTimeTypeHandler(),
new LocalDateTypeHandler(),
new LocalTimeTypeHandler(),
new OffsetDateTimeTypeHandler(),
new ZonedDateTimeTypeHandler()
};
}
@Data
public static class Application {
public Application() {
this.name = "AXBOOT";
}
private String name;
}
@Data
public static class Logging {
private Level level;
private Slack slack;
private Jandi jandi;
private Database database;
private String adminUrl;
@Data
public static class Slack {
private boolean enabled = false;
private String webHookUrl = "";
private String channel = "";
}
@Data
public static class Jandi {
private boolean enable = false;
private String webHookUrl = "";
}
@Data
public static class Database {
private boolean enabled = false;
private String level = "ERROR";
}
}
@Data
public static class Modeler {
private boolean output = false;
@Getter(AccessLevel.NONE)
private String outputDir;
public String getOutputDir() {
if (outputDir == null) {
return System.getProperty("user.home") + "/Desktop/output/";
}
return outputDir;
}
}
@Data
public static class DataSourceConfig {
@Getter(AccessLevel.NONE)
private String databaseType;
private String username;
private String password;
private String url;
private String driverClassName;
private int initialSize = 5;
private int maxTotal = 10;
private int maxWaitMillis = 3000;
private boolean sqlOutput = true;
private long slowQueryThreshold = 5000;
private long timeBetweenEvictionRunsMillis = 300000;
private boolean testOnBorrow = false;
private boolean testOnReturn = false;
private boolean testWhileIdle = true;
private long defaultQueryTimeout = 30000;
@Getter(AccessLevel.NONE)
private String validationQuery;
private HibernateConfig hibernate;
public String getValidationQuery() {
String _driverClassName = driverClassName.toLowerCase();
if (_driverClassName.contains("mysql") ||
_driverClassName.contains("mariadb") ||
_driverClassName.contains("microsft") ||
_driverClassName.contains("sqlserver")) {
return "SELECT 1";
}
if (_driverClassName.contains("oracle")) {
return "SELECT 1 FROM DUAL";
}
if (_driverClassName.contains("postgres") || _driverClassName.contains("pg")) {
return "";
}
return "SELECT 1";
}
public DataSourceConfig() {
}
public HibernateConfig getHibernateConfig() {
if (hibernate == null) {
hibernate = new HibernateConfig();
}
return hibernate;
}
@Data
public static class HibernateConfig {
private String databaseType;
private boolean l2Cache = false;
private boolean queryCache = false;
private String dialect;
private String hbm2ddlAuto = "none";
public HibernateJpaVendorAdapter getHibernateJpaVendorAdapter() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
switch (databaseType.toLowerCase()) {
case AXBootTypes.DatabaseType.MSSQL:
vendorAdapter.setDatabase(Database.SQL_SERVER);
break;
case AXBootTypes.DatabaseType.MYSQL:
vendorAdapter.setDatabase(Database.MYSQL);
break;
case AXBootTypes.DatabaseType.ORACLE:
vendorAdapter.setDatabase(Database.ORACLE);
break;
case AXBootTypes.DatabaseType.POSTGRESQL:
vendorAdapter.setDatabase(Database.POSTGRESQL);
break;
case AXBootTypes.DatabaseType.H2:
vendorAdapter.setDatabase(Database.H2);
break;
}
if (StringUtils.isEmpty(dialect)) {
switch (databaseType.toLowerCase()) {
case AXBootTypes.DatabaseType.MSSQL:
vendorAdapter.setDatabase(Database.SQL_SERVER);
vendorAdapter.setDatabasePlatform(SQLServer2005Dialect.class.getName());
break;
case AXBootTypes.DatabaseType.MYSQL:
vendorAdapter.setDatabase(Database.MYSQL);
vendorAdapter.setDatabasePlatform(MySQL57InnoDBDialect.class.getName());
break;
case AXBootTypes.DatabaseType.ORACLE:
vendorAdapter.setDatabase(Database.ORACLE);
vendorAdapter.setDatabasePlatform(Oracle10gDialect.class.getName());
break;
case AXBootTypes.DatabaseType.POSTGRESQL:
vendorAdapter.setDatabase(Database.POSTGRESQL);
vendorAdapter.setDatabasePlatform(PostgreSQL9Dialect.class.getName());
break;
case AXBootTypes.DatabaseType.H2:
vendorAdapter.setDatabase(Database.H2);
vendorAdapter.setDatabasePlatform(H2Dialect.class.getName());
}
} else {
try {
vendorAdapter.setDatabasePlatform(Class.forName("org.hibernate.dialect." + dialect).getName());
} catch (ClassNotFoundException e) {
try {
vendorAdapter.setDatabasePlatform(Class.forName(String.format("com.chequer.axboot.core.db.dialect.%s", dialect)).getName());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
return vendorAdapter;
}
public Properties getAdditionalProperties() {
Properties additionalProperties = new Properties();
additionalProperties.put(Environment.USE_SECOND_LEVEL_CACHE, this.isL2Cache());
additionalProperties.put(Environment.USE_QUERY_CACHE, isQueryCache());
additionalProperties.put(Environment.HBM2DDL_AUTO, getHbm2ddlAuto());
return additionalProperties;
}
}
}
}
| 32.823129
| 152
| 0.587668
|
72b85846447a1f8e58b775ec082bf54e318b4825
| 425
|
package com.mrkirby153.bfs.query;
import java.util.concurrent.ThreadFactory;
/**
* Thread pool factory for query threads
*/
class QueryThreadPoolFactory implements ThreadFactory {
private int threadNumber = 1;
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, String.format("bfs-query-%d", threadNumber++));
thread.setDaemon(true);
return thread;
}
}
| 22.368421
| 85
| 0.691765
|
4ca6689bfb583060881140ac23c96ff73e0e547d
| 5,072
|
package com.huyunit.rxbus2.event;
import com.huyunit.rxbus2.thread.EventThread;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import io.reactivex.BackpressureStrategy;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;
/**
* Wraps a single-argument 'subscriber' method on a specific object.
* <p/>
* <p>This class only verifies the suitability of the method and event type if something fails. Callers are expected to
* verify their uses of this class.
* <p/>
* <p>Two SubscriberEvent are equivalent when they refer to the same method on the same object (not class). This
* property is used to ensure that no subscriber method is registered more than once.
* <p>
* author: bobo
* create time: 2016/12/15 10:57
* Email: jqbo84@163.com
*/
public class SubscriberEvent extends Event {
/**
* Object sporting the method.
*/
private final Object target;
/**
* Subscriber method.
*/
private final Method method;
/**
* Subscriber thread
*/
private final EventThread thread;
/**
* RxJava {@link Subject}
*/
private Subject subject;
/**
* Object hash code.
*/
private final int hashCode;
/**
* Should this Subscriber receive events?
*/
private boolean valid = true;
public SubscriberEvent(Object target, Method method, EventThread thread) {
if (target == null) {
throw new NullPointerException("SubscriberEvent target cannot be null.");
}
if (method == null) {
throw new NullPointerException("SubscriberEvent method cannot be null.");
}
if (thread == null) {
throw new NullPointerException("SubscriberEvent thread cannot be null.");
}
this.target = target;
this.method = method;
this.thread = thread;
method.setAccessible(true);
initObservable();
// Compute hash code eagerly since we know it will be used frequently and we cannot estimate the runtime of the
// target's hashCode call.
final int prime = 31;
hashCode = (prime + method.hashCode()) * prime + target.hashCode();
}
private void initObservable() {
subject = PublishSubject.create();
subject.toFlowable(BackpressureStrategy.BUFFER)
.onBackpressureBuffer()
.observeOn(EventThread.getScheduler(thread))
.subscribe(new Consumer<Object>() {
@Override
public void accept(@NonNull Object event) throws Exception {
try {
if (valid) {
handleEvent(event);
}
} catch (InvocationTargetException e) {
throwRuntimeException("Could not dispatch event: " + event.getClass() + " to subscriber " + SubscriberEvent.this, e);
}
}
});
}
public boolean isValid() {
return valid;
}
/**
* If invalidated, will subsequently refuse to handle events.
* <p/>
* Should be called when the wrapped object is unregistered from the Bus.
*/
public void invalidate() {
valid = false;
}
public void handle(Object event) {
subject.onNext(event);
}
public Subject getSubject() {
return subject;
}
/**
* Invokes the wrapped subscriber method to handle {@code event}.
*
* @param event event to handle
* @throws IllegalStateException if previously invalidated.
* @throws InvocationTargetException if the wrapped method throws any {@link Throwable} that is not
* an {@link Error} ({@code Error}s are propagated as-is).
*/
protected void handleEvent(Object event) throws InvocationTargetException {
if (!valid) {
throw new IllegalStateException(toString() + " has been invalidated and can no longer handle events.");
}
try {
method.invoke(target, event);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof Error) {
throw (Error) e.getCause();
}
throw e;
}
}
@Override
public String toString() {
return "[SubscriberEvent " + method + "]";
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final SubscriberEvent other = (SubscriberEvent) obj;
return method.equals(other.method) && target == other.target;
}
}
| 29.660819
| 141
| 0.59306
|
a390bdb55c76c2e1d33652a8d94dc63913888e17
| 255
|
package com.fanap.podchat.model;
public class OutPutInfoThread {
private ResultThread result;
public ResultThread getResult() {
return result;
}
public void setResult(ResultThread result) {
this.result = result;
}
}
| 18.214286
| 48
| 0.670588
|
9ef0e0fac98d641af142a893d1b79a77514da39e
| 184
|
package com.qstarter.core.enums.convert2db;
/**
* @param <DB> : 保存到数据库的数据类型
* @author peter
* date: 2019-09-12 09:19
**/
public interface PersistEnum2DB<DB> {
DB getData();
}
| 16.727273
| 43
| 0.663043
|
a9f6e0216c9fc1a6e6c313d9e33e03bf524d7433
| 729
|
/**
*
*/
package demo;
/**
* @author Arockia
*
*/
public class Pojo {
private String type = null;
private static String[] types = new String[8];
public Pojo() {
types[0] = "byte";
types[1] = "short";
types[2] = "int";
types[3] = "long";
types[4] = "float";
types[5] = "double";
types[6] = "boolean";
types[7] = "char";
}
public static boolean isAcceptableType(String type) {
boolean acceptable = false;
for (String string : types) {
if (string.equalsIgnoreCase(type)) {
acceptable = true;
break;
}
}
return acceptable;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 15.847826
| 55
| 0.559671
|
f816d8f80e9427eea2703b72c9fc5d05e34f428f
| 6,302
|
package ru.mk.pump.commons.utils;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.core.IsAnything;
@Slf4j
@SuppressWarnings({"unchecked", "UnusedReturnValue", "unused", "WeakerAccess"})
public class Waiter implements Cloneable {
private TimeUnit timeoutUnit = TimeUnit.SECONDS;
/**
* ALL ASSERTS. CAN BE CLEAN
*/
private Class<? extends Throwable>[] DEFAULT_NOT_IGNORED_THROWABLE = new Class[]{Error.class};
private Set<Class<? extends Throwable>> notIgnoringException = Sets.newHashSet();
private Set<Class<? extends Throwable>> ignoringException = Sets.newHashSet();
private boolean reThrow = true;
/**
* default enable ignoring AssertionError.class
*/
public Waiter() {
this(true);
}
/**
* @param notIgnoringAsserts disable/enable ignoring AssertionError.class
*/
public Waiter(boolean notIgnoringAsserts) {
if (!notIgnoringAsserts) {
DEFAULT_NOT_IGNORED_THROWABLE = new Class[0];
} else {
notIgnoringException.addAll(Arrays.asList(DEFAULT_NOT_IGNORED_THROWABLE));
}
}
public static void sleep(int timeoutMS) {
try {
Thread.sleep(timeoutMS);
} catch (InterruptedException ignore) {
}
}
/**
* Full clear notIgnoringException and ignoringException
*/
public Waiter clear() {
notIgnoringException.clear();
ignoringException.clear();
return this;
}
/**
* Priority is greater than {@link #withIgnoreExceptions(Class)}
*/
public Waiter withNotIgnoreExceptions(@NonNull Class<? extends Throwable> notIgnoringThrowable) {
notIgnoringException.add(notIgnoringThrowable);
return this;
}
public Waiter withTimeoutUnit(TimeUnit timeoutUnit) {
this.timeoutUnit = timeoutUnit;
return this;
}
public Waiter withReThrow(boolean reThrow) {
this.reThrow = reThrow;
return this;
}
/**
* Priority is less than {@link #withNotIgnoreExceptions(Class)})
*/
public Waiter withIgnoreExceptions(@NonNull Class<? extends Throwable> ignoringThrowable) {
ignoringException.add(ignoringThrowable);
return this;
}
public WaitResult wait(int timeout, int intervalMs, @NonNull Callable<Boolean> successCondition) {
return wait(timeout, intervalMs, successCondition, Matchers.is(true));
}
public WaitResult<Boolean> waitIgnoreExceptions(int timeout, int intervalMs, @NonNull Callable<Boolean> successCondition) {
final Waiter clone = this.clone();
clone.notIgnoringException.addAll(Arrays.asList(DEFAULT_NOT_IGNORED_THROWABLE));
clone.ignoringException.clear();
clone.withIgnoreExceptions(Throwable.class);
return clone.wait(timeout, intervalMs, successCondition);
}
public <T> WaitResult<T> wait(int timeout, int intervalMs, @NonNull Callable<T> action, @Nullable Matcher<T> matcher) {
if (matcher == null) {
matcher = new IsAnything();
}
T result;
final AtomicLong elapsedTime = new AtomicLong(timeout * 1000);
try {
result = Awaitility.await()
.conditionEvaluationListener(condition -> elapsedTime.set(condition.getElapsedTimeInMS()))
.ignoreExceptionsMatching(this::isIgnore)
.pollInterval(intervalMs, TimeUnit.MILLISECONDS)
.atMost(timeout, timeoutUnit)
.until(action, matcher);
} catch (Throwable ex) {
if (reThrow && !isIgnore(ex) && !(ex instanceof ConditionTimeoutException)) {
throw ex;
}
try {
result = action.call();
} catch (Throwable throwable) {
return this.<T>resultDelegate(false, elapsedTime.get()).withInfo(timeout, intervalMs).withCause(throwable);
}
return this.<T>resultDelegate(false, elapsedTime.get()).withInfo(timeout, intervalMs).withResult(result).withCause(ex);
}
if (result != null) {
return this.<T>resultDelegate(true, elapsedTime.get()).withResult(result).withInfo(timeout, intervalMs);
} else {
return this.<T>resultDelegate(true, elapsedTime.get()).withInfo(timeout, intervalMs);
}
}
public <T> WaitResult<T> waitIgnoreExceptions(int timeout, int intervalMs, @NonNull Callable<T> action, @Nullable Matcher<T> matcher) {
final Waiter clone = this.clone();
clone.notIgnoringException.addAll(Arrays.asList(DEFAULT_NOT_IGNORED_THROWABLE));
clone.ignoringException.clear();
clone.withIgnoreExceptions(Throwable.class);
return clone.wait(timeout, intervalMs, action, matcher);
}
protected <T> WaitResult<T> resultDelegate(boolean success, long elapsedTime) {
return new WaitResult<>(success, elapsedTime);
}
@Override
public Waiter clone() {
Waiter waiter = null;
try {
waiter = (Waiter) super.clone();
waiter.ignoringException = new HashSet<>(ignoringException);
waiter.notIgnoringException = new HashSet<>(notIgnoringException);
waiter.DEFAULT_NOT_IGNORED_THROWABLE = DEFAULT_NOT_IGNORED_THROWABLE.clone();
} catch (CloneNotSupportedException ex) {
log.error("Error while cloning waiter", ex);
}
return waiter;
}
private boolean isIgnore(Throwable throwable) {
//noinspection SimplifiableIfStatement
if (notIgnoringException.stream().anyMatch(throwableClass -> throwableClass.isAssignableFrom(throwable.getClass()))) {
return false;
}
return ignoringException.stream().anyMatch(throwableClass -> throwableClass.isAssignableFrom(throwable.getClass()));
}
}
| 35.806818
| 139
| 0.664868
|
4f5eacb939439c63bd3fe5b6b0a74134aff0b037
| 3,455
|
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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 backtype.storm.utils;
import org.junit.Test;
import junit.framework.TestCase;
import static org.junit.Assert.*;
/**
* Unit test for RateTracker
*/
public class RateTrackerTest extends TestCase {
@Test
public void testExactRate() {
//This test is in two phases. The first phase fills up the 10 buckets with 10 tuples each
// We purposely simulate a 1 second bucket size so the rate will always be 10 per second.
final long interval = 1000l;
long time = 0l;
RateTracker rt = new RateTracker(10000, 10, time);
double [] expected = new double[] {10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0};
for (int i = 0; i < expected.length; i++) {
double exp = expected[i];
rt.notify(10);
time += interval;
double actual = rt.reportRate(time);
rt.forceRotate(1, interval);
assertEquals("Expected rate on iteration "+i+" is wrong.", exp, actual, 0.00001);
}
//In the second part of the test the rate doubles to 20 per second but the rate tracker
// increases its result slowly as we push the 10 tuples per second buckets out and relpace them
// with 20 tuples per second.
expected = new double[] {11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0};
for (int i = 0; i < expected.length; i++) {
double exp = expected[i];
rt.notify(20);
time += interval;
double actual = rt.reportRate(time);
rt.forceRotate(1, interval);
assertEquals("Expected rate on iteration "+i+" is wrong.", exp, actual, 0.00001);
}
}
@Test
public void testEclipsedAllWindows() {
long time = 0;
RateTracker rt = new RateTracker(10000, 10, time);
rt.notify(10);
rt.forceRotate(10, 1000l);
assertEquals(0.0, rt.reportRate(10000l), 0.00001);
}
@Test
public void testEclipsedOneWindow() {
long time = 0;
RateTracker rt = new RateTracker(10000, 10, time);
rt.notify(1);
double r1 = rt.reportRate(1000l);
rt.forceRotate(1, 1000l);
rt.notify(1);
double r2 = rt.reportRate(2000l);
assertEquals(r1, r2, 0.00001);
}
@Test
public void testEclipsedNineWindows() {
long time = 0;
RateTracker rt = new RateTracker(10000, 10, time);
rt.notify(1);
double r1 = rt.reportRate(1000);
rt.forceRotate(9, 1000);
rt.notify(9);
double r2 = rt.reportRate(10000);
assertEquals(r1, r2, 0.00001);
}
}
| 36.368421
| 103
| 0.621129
|
32bad0ac4d6cc19087e147fcf478ee899b72e15f
| 496
|
package io.mycat.util.dataMigrator;
import io.mycat.util.dataMigrator.dataIOImpl.MysqlDataIO;
import io.mycat.util.exception.DataMigratorException;
public class DataIOFactory {
public static final String MYSQL = "mysql";
public static final String ORACLE = "oracle";
public static DataIO createDataIO(String dbType){
switch (dbType) {
case MYSQL:
return new MysqlDataIO();
default:
throw new DataMigratorException("dbType:"+dbType+" is not support for the moment!");
}
}
}
| 24.8
| 87
| 0.754032
|
963a5f7230d15e5269d58eb13a4c572fc4ba2ea0
| 868
|
package com.jeffdisher.laminar.types.payload;
import java.nio.ByteBuffer;
/**
* Contains nothing - used for message types which require no payload.
*/
public final class Payload_Empty implements IPayload {
public static Payload_Empty create() {
return new Payload_Empty();
}
public static Payload_Empty deserialize(ByteBuffer serialized) {
return new Payload_Empty();
}
private Payload_Empty() {
}
@Override
public int serializedSize() {
return 0;
}
@Override
public void serializeInto(ByteBuffer buffer) {
}
@Override
public boolean equals(Object arg0) {
boolean isEqual = (this == arg0);
if (!isEqual && (null != arg0) && (this.getClass() == arg0.getClass())) {
isEqual = true;
}
return isEqual;
}
@Override
public int hashCode() {
return 0;
}
@Override
public String toString() {
return "Payload_Empty()";
}
}
| 17.36
| 75
| 0.6947
|
b6e5b8ae7998e444959e36c9e26e81dca2bd539f
| 1,894
|
package cn.shu.test;
import cn.shu.dealwithdata.ParseData;
import cn.shu.helper.DatabaseHelper;
import cn.shu.model.Customer;
import cn.shu.service.CustomerService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by shu on 2017/3/6.
*/
//单元测试
public class CustomerServiceTest {
private final CustomerService customerService;
public CustomerServiceTest() {
customerService = new CustomerService();
}
@Before
public void init() {
//初始化数据库
// String filePath = "sql/customer_init.sql";
// DatabaseHelper.executeSqlFile(filePath);
}
@Test //数据解析
public void getCustomerListTest() throws Exception {
List<Customer> customers = customerService.getCustomerList();
ParseData.newWordDoc(Customer.class, customers, "customer");
}
@Test
public void getCustomerTest() throws Exception {
Customer customer = customerService.getCustomer(1);
Assert.assertNotNull(customer);
}
@Test
public void createCustomerTest() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name", "LiBai");
map.put("contact", "li");
map.put("email", "21@foxmail.com");
boolean result = customerService.createCustomer(map);
Assert.assertTrue(result);
}
@Test
public void updateCustomerTest() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name", "json");
long id = 1;
boolean result = customerService.updateCustomer(id, map);
Assert.assertTrue(result);
}
@Test
public void deleteCustomerTest() throws Exception {
long id = 1;
boolean result = customerService.deleteCustomer(id);
Assert.assertTrue(result);
}
}
| 26.676056
| 69
| 0.657339
|
839f123a930008a8f35efde9e86a75bbd81a3bf8
| 4,346
|
package com.socialapp.services.internal.callback.custom;
import java.util.Collections;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.socialapp.services.IResultProcessor;
import com.socialapp.services.dao.Member;
import com.socialapp.services.internal.callback.AQuery;
import com.socialapp.services.internal.callback.AjaxStatus;
import com.socialapp.services.internal.callback.custom.sharedstate.LoginState;
import com.socialapp.services.util.SocialappFeature;
import com.socialapp.services.util.PerfLog.PerfMeasureStep;
abstract public class AbstractGetMembersCallback extends
ProcessableCallback<List<Member>> {
private long responseParsingTime;
private long extractEntriesTime;
private long waitingTimeForCallback;
private long parsingResultIteratingTime;
private long membersFinalizationTime;
protected long beginFinalize;
List<Element> entries = Collections.emptyList();
List<Member> members = null;
protected IResultProcessor<Boolean> updateOnlineStatusProcessor;
protected AbstractGetMembersCallback(IResultProcessor<List<Member>> proc,
IResultProcessor<Boolean> updateOnlineStatusProcessor) {
super(proc);
this.updateOnlineStatusProcessor = updateOnlineStatusProcessor;
}
@Override
public void callback(String request, String response, AjaxStatus status) {
try {
this.requestString = request;
this.responseString = response;
this.status = status;
waitingTimeForCallback = System.currentTimeMillis() - creationTime;
entries = Collections.emptyList();
members = null;
if (response != null) {
entries = parseEntries(response);
}
long beginIteration = System.currentTimeMillis();
if (!entries.isEmpty()) {
members = createMembersListFromEntries(entries);
} else {
System.err.println(SocialappFeature.WEB.name() +
" cannot retrive entries from response!");
}
parsingResultIteratingTime = System.currentTimeMillis()
- beginIteration;
finalize(members, response);
perfLog.log(PerfMeasureStep.waitingTimeForCallback,
waitingTimeForCallback);
perfLog.log(PerfMeasureStep.responseParsingTime,
responseParsingTime);
perfLog.log(PerfMeasureStep.extractEntriesTime, extractEntriesTime);
perfLog.log(PerfMeasureStep.parsingResultIteratingTime,
parsingResultIteratingTime);
perfLog.log(PerfMeasureStep.membersFinalizationTime,
membersFinalizationTime);
} catch (Throwable e) {
System.err.println(SocialappFeature.WEB.name() +
" Error in Get Members Callback: ");
e.printStackTrace();
}
}
protected List<Element> parseEntries(String response) {
long begin = System.currentTimeMillis();
Document document = Jsoup.parse(response);
responseParsingTime = System.currentTimeMillis() - begin;
begin = System.currentTimeMillis();
List<Element> entries = extractEntries(document);
extractEntriesTime = System.currentTimeMillis() - begin;
return entries;
}
abstract protected List<Element> extractEntries(Document response);
abstract protected List<Member> createMembersListFromEntries(
List<Element> entries);
@Override
public void finalize(List<Member> processable, Object... paras) {
super.finalize(processable, paras);
membersFinalizationTime = System.currentTimeMillis() - beginFinalize;
}
protected void updateOnlineStatus(final List<Member> result) {
new Thread(new Runnable(){
public void run() {
try {
internalUpdateOnlineStatus(result);
} catch (RuntimeException ex) {
System.err.println(SocialappFeature.WEB.toString() +
" error while updating online status!");
ex.printStackTrace();
}
}
}).start();
}
protected void internalUpdateOnlineStatus(List<Member> result) {
if (LoginState.isLoggedIn()) { // the online status is
// available only in
// logged in state
UpdateLastOnlineTimestampCallback updateOnlineTimestampCallback = new UpdateLastOnlineTimestampCallback(result, this.updateOnlineStatusProcessor);
AQuery aq = new AQuery();
aq.ajax(updateOnlineTimestampCallback.getUrl(),
updateOnlineTimestampCallback.getParams(), updateOnlineTimestampCallback);
}
}
}
| 33.953125
| 150
| 0.743442
|
27e6e85cacf6da420f07c7a33ac175dbb64cef26
| 4,289
|
//JungleJuice: Johnny Wong, Qian Zhou, Victor Lin
//APCS2 pd01
//Lab02 All Hands on Deque!
import java.util.Iterator;
public class QQKachoo<T> implements Deque<T> {
private DLLNode<T> _front, _end;
private int _size;
public QQKachoo(){
_front = _end = null;
_size = 0;
}
//add element to the front of collection
public void enqueueFront(T x){
_front = new DLLNode<T>(x,null,_front);
if(isEmpty())
_end = _front; //if deque was empty, the end is also the front
else
_front.getNext().setPrev(_front); //establish connection with next node
_size++;
}
//add element to the end of the collection
public void enqueueEnd(T x){
_end = new DLLNode<T>(x,_end,null);
if(isEmpty())
_front = _end;//if deque was empty, the front is also the end
else
_end.getPrev().setNext(_end); //establish connection with previous node
_size++;
}
//returns element at front without dequeFront
public T peekFront(){
if(isEmpty()){
System.out.println("nothing to peek");
return null;
}
return _front.getCargo();
}
//returns element at end without dequeEnd
public T peekEnd(){
if(isEmpty()){
System.out.println("nothing to peek");
return null;
}
return _end.getCargo();
}
//removes element at front of deque
//returns removed element
public T dequeueFront(){
if(isEmpty()){
System.out.println("nothing to remove");
return null;
}
T temp = _front.getCargo();
_front = _front.getNext(); //the removed node with java garbage collector
_size--;
return temp;
}
//removes element at end of deque
//returns removed element
public T dequeueEnd(){
if(isEmpty()){
System.out.println("nothing to remove");
return null;
}
T temp = _end.getCargo();
_end = _end.getPrev();//the removed node with java garbage collector
_size--;
return temp;
}
//returns true if deque is empty, false otherwise
public boolean isEmpty(){
return _size == 0;
}
//returns an iterator to allow for-each loop from front to end
public Iterator<T> iterator(){
return new FrontIterator<T>();
}
//returns an iterator to allow loop from end to front
public Iterator<T> diterator(){
return new EndIterator<T>();
}
public String toString(){
String str = "FRONT-->";
DLLNode<T> alias = _front;
for(int i=0;i<_size;i++){
str += alias.getCargo() + "-->";
alias = alias.getNext();
}
str += "END";
return str;
}
//end it
class EndIterator<T> implements Iterator<T>{
private DLLNode<T> alias;
private boolean _okToRemove;
public EndIterator(){
alias = (DLLNode<T>)_end;
_okToRemove = false;
}
public boolean hasNext(){
return alias != null;
}
public T next(){
T c = alias.getCargo();
alias = alias.getPrev();
_okToRemove = true;
return c;
}
public void remove(){
if (_size==0)
return;
if (_okToRemove){
if (_size==1)
_front=_end = null;
else{
alias.setNext(alias.getNext().getNext());
if (alias.getNext()!=null)
alias.getNext().setPrev(alias);
}
_size--;
}
_okToRemove=false;
}
}
//front it
class FrontIterator<T> implements Iterator<T>{
private DLLNode<T> alias;
private boolean _okToRemove;
public FrontIterator(){
alias =(DLLNode<T>) _front;
_okToRemove = false;
}
public boolean hasNext(){
return alias != null;
}
public T next(){
T c = alias.getCargo();
alias = alias.getNext();
_okToRemove = true;
return c;
}
public void remove(){
if (_size==0)
return;
if (_okToRemove){
if (_size==1)
_front=_end=null;
else{
alias.setPrev(alias.getPrev().getPrev());
if (alias.getPrev()!=null)
alias.getPrev().setNext(alias);
}
_size--;
}
_okToRemove= false;
}
}
}
| 23.309783
| 79
| 0.564467
|
a337d9f088b8d87b5428dee282bdfb4475f55ea7
| 823
|
package cn.apisium.nekoguard.fabric.callback;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.jetbrains.annotations.NotNull;
public interface BlockFormCallback {
Event<BlockFormCallback> EVENT = EventFactory.createArrayBacked(BlockFormCallback.class,
(listeners) -> (block, world, pos) -> {
for (BlockFormCallback event : listeners) {
event.interact(block, world, pos);
}
});
/**
* 方块自然变化被放置、更改或者蔓延事件
* @param block 方块
* @param world 世界
* @param pos 位置
*/
void interact(@NotNull Block block, @NotNull World world, @NotNull BlockPos pos);
}
| 31.653846
| 92
| 0.669502
|
4fa13b4dc12865e35bf09555814056c36bdb8e50
| 6,001
|
package org.huber.keytool.action;
import java.awt.Component;
import java.awt.Dialog;
import java.io.File;
import java.text.MessageFormat;
import javax.swing.JComponent;
import org.huber.keytool.KeyStoreBeanHistory;
import org.huber.keytool.KeyStoreTopComponent;
import org.huber.keytool.model.ConstantsHelper;
import org.huber.keytool.model.KeyStoreBean;
import org.huber.keytool.model.KeyStoreBeanFactory;
import org.huber.keytool.ui.wizard.loadkeystore.EnterKeyStorePasswordWizardPanel;
import org.huber.keytool.ui.wizard.loadkeystore.SelectKeyStoreWizardPanel;
import org.openide.DialogDisplayer;
import org.openide.WizardDescriptor;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.actions.CallableSystemAction;
// An example action demonstrating how the wizard could be called from within
// your code. You can copy-paste the code below wherever you need.
public final class LoadKeyStoreAction extends CallableSystemAction {
private WizardDescriptor.Panel[] panels;
private WizardDescriptor wizardDescriptor;
public void performActionWith( File keyStoreFile ) {
doPerformAction(keyStoreFile );
}
public void performAction() {
doPerformAction(null);
}
private void doPerformAction( File preSelectedKeyStoreFile ) {
final KeyStoreTopComponent win = KeyStoreTopComponent.findInstance();
if (win != null) {
final String prevKeyStoreName = win.getKeyStoreBean().getName();
final KeyStoreBeanHistory ksbh = win.getKeyStoreBeanHistory();
boolean cancelled = showWizard(preSelectedKeyStoreFile, prevKeyStoreName, ksbh);
if (!cancelled) {
// do something
final File keyStoreFile = (File)this.wizardDescriptor.getProperty( "keyStoreFile" );
final char[] password = (char[])this.wizardDescriptor.getProperty( "password" );
KeyStoreBeanFactory ksbf = new KeyStoreBeanFactory();
final KeyStoreBean ksb = ksbf.createKeyStoreBean(keyStoreFile, password);
if (ksb != null) {
win.setKeyStoreBean( ksb );
win.open();
win.requestActive();
}
}
}
}
/**
* Show the wizard for loading the keystore file
*
* @param prevKeyStoreName
* @param kshbh
*/
private boolean showWizard(File preSelectedKeyStoreFile, String prevKeyStoreName, KeyStoreBeanHistory ksbh) {
this.wizardDescriptor = new WizardDescriptor(getPanels());
if (preSelectedKeyStoreFile != null) {
this.wizardDescriptor.putProperty( "keyStoreFile", preSelectedKeyStoreFile );
}
// {0} will be replaced by WizardDesriptor.Panel.getComponent().getName()
this.wizardDescriptor.setTitleFormat(new MessageFormat("{0}"));
this.wizardDescriptor.setTitle( NbBundle.getMessage(LoadKeyStoreAction.class, "TTL_LoadKeyStoreYour" ) );
//this.wizardDescriptor.putProperty()
this.wizardDescriptor.putProperty( "currentDirectoryOrFile", prevKeyStoreName );
this.wizardDescriptor.putProperty( "keyStoreBeanHistory", ksbh );
final Dialog dialog = DialogDisplayer.getDefault().createDialog(wizardDescriptor);
dialog.setVisible(true);
dialog.toFront();
boolean cancelled = this.wizardDescriptor.getValue() != WizardDescriptor.FINISH_OPTION;
return cancelled;
}
/**
* Initialize panels representing individual wizard's steps and sets
* various properties for them influencing wizard appearance.
*/
private WizardDescriptor.Panel[] getPanels() {
if (panels == null) {
panels = new WizardDescriptor.Panel[] {
new SelectKeyStoreWizardPanel(),
new EnterKeyStorePasswordWizardPanel()
};
String[] steps = new String[panels.length];
for (int i = 0; i < panels.length; i++) {
Component c = panels[i].getComponent();
// Default step name to component name of panel. Mainly useful
// for getting the name of the target chooser to appear in the
// list of steps.
steps[i] = c.getName();
if (c instanceof JComponent) { // assume Swing components
JComponent jc = (JComponent) c;
// Sets step number of a component
jc.putClientProperty("WizardPanel_contentSelectedIndex", Integer.valueOf(i));
// Sets steps names for a panel
jc.putClientProperty("WizardPanel_contentData", steps);
// Turn on subtitle creation on each step
jc.putClientProperty("WizardPanel_autoWizardStyle", Boolean.TRUE);
// Show steps on the left side with the image on the background
jc.putClientProperty("WizardPanel_contentDisplayed", Boolean.TRUE);
// Turn on numbering of all steps
jc.putClientProperty("WizardPanel_contentNumbered", Boolean.TRUE);
}
}
}
return panels;
}
public String getName() {
return NbBundle.getMessage(LoadKeyStoreAction.class, "ACT_LoadKeyStore" );
}
public String iconResource() {
return "org/huber/keytool/images/password-open16x16.png";
}
protected void initialize() {
super.initialize();
// see org.openide.util.actions.SystemAction.iconResource() javadoc for more details
// putValue("noIconInMenu", Boolean.TRUE);
}
public HelpCtx getHelpCtx() {
return ConstantsHelper.getHelpCtx();
}
protected boolean asynchronous() {
return false;
}
}
| 40.006667
| 114
| 0.636394
|
0ad79dc5946254b03a6c0b3f358e54d153f3730f
| 6,544
|
package wangchen.java.com.cnews;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SignupActivity extends AppCompatActivity {
// @BindView(R.id.input_name)
EditText nameText;
EditText addressText;
EditText usernameText;
EditText passwordText;
EditText reEnterPasswordText;
Button signupButton;
TextView loginLink;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
nameText = ((TextInputLayout)findViewById(R.id.input_name)).getEditText();
addressText = ((TextInputLayout)findViewById(R.id.input_address)).getEditText();
usernameText = ((TextInputLayout)findViewById(R.id.username_signup)).getEditText();
passwordText = ((TextInputLayout)findViewById(R.id.password_signup)).getEditText();
reEnterPasswordText = ((TextInputLayout)findViewById(R.id.repassword_signup)).getEditText();
signupButton = findViewById(R.id.btn_signup);
loginLink = findViewById(R.id.link_login);
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signup();
}
});
loginLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Finish the registration screen and return to the Login activity
Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(intent);
finish();
}
});
}
private void signup() {
if(!validate()) {
Toast.makeText(getBaseContext(), "注册失败", Toast.LENGTH_LONG).show();
return;
}
final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("正在创建账号...");
progressDialog.show();
String name = nameText.getText().toString();
String address = addressText.getText().toString();
final String username = usernameText.getText().toString();
final String password = passwordText.getText().toString();
final String ipAdress = "101.5.121.239";
new Thread() {
public void run() {
try {
Socket s1 = new Socket(ipAdress, 6666);
OutputStream os = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Register" + " " + username + " " + password);
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
//
// }
// }, 1000);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
String getStr = dis.readUTF();
if(getStr.equals("USEREXISTS")) {
SignupActivity.this.runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "用户名已经存在", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
return;
} else if(getStr.equals("REGISTERSUCCESS")) {
SignupActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
return;
}
dis.close();
dos.close();
s1.close();
} catch(IOException e) {
Toast.makeText(getApplicationContext(), "登录失败 ", Toast.LENGTH_SHORT).show();
}
}
}.start();
// new Thread(new Runnable() {
// @Override
// public void run() {
// NewsDBHelper db = ((CNewsApp)getApplicationContext()).getDB();
// int res = db.createUser(username, password);
// if(res == NewsDBHelper.USER_EXITS) {
// SignupActivity.this.runOnUiThread(new Runnable()
// {
// public void run()
// {
// Toast.makeText(getApplicationContext(), "用户名已被占用", Toast.LENGTH_SHORT).show();
// progressDialog.dismiss();
// }
// });
// return;
// } else {
// SignupActivity.this.runOnUiThread(new Runnable()
// {
// public void run()
// {
// Toast.makeText(getApplicationContext(), "创建账号成功", Toast.LENGTH_SHORT).show();
// progressDialog.dismiss();
// }
// });
// startActivity(new Intent(getApplicationContext(), LoginActivity.class));
// return;
// }
// }
// }) {
// }.start();
}
public boolean validate() {
boolean valid = true;
String name = nameText.getText().toString();
String address = addressText.getText().toString();
String username = usernameText.getText().toString();
String password = passwordText.getText().toString();
String reEnterPassword = reEnterPasswordText.getText().toString();
if (name.isEmpty() || name.length() < 2) {
nameText.setError("名字最少两个字符");
valid = false;
} else {
nameText.setError(null);
}
if (address.isEmpty()) {
addressText.setError("地址不能为空");
valid = false;
} else {
addressText.setError(null);
}
if (username.isEmpty() || username.length() < 4 || username.length() > 10) {
usernameText.setError("请输入4到10位的用户名");
valid = false;
} else {
usernameText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
passwordText.setError("密码应为4-10位");
valid = false;
} else {
passwordText.setError(null);
}
if (!(reEnterPassword.equals(password))) {
reEnterPasswordText.setError("两次输入的密码不一致");
valid = false;
} else {
reEnterPasswordText.setError(null);
}
return valid;
}
}
| 32.078431
| 96
| 0.619499
|
885e7b5fca50f33a17ca0e164152337e35144bbf
| 3,342
|
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 com.alibaba.cloud.dubbo.openfeign;
import static com.alibaba.cloud.dubbo.autoconfigure.DubboOpenFeignAutoConfiguration.TARGETER_CLASS_NAME;
import static java.lang.reflect.Proxy.newProxyInstance;
import static org.springframework.util.ClassUtils.getUserClass;
import static org.springframework.util.ClassUtils.isPresent;
import static org.springframework.util.ClassUtils.resolveClassName;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.env.Environment;
import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory;
import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory;
/**
* org.springframework.cloud.openfeign.Targeter {@link BeanPostProcessor}
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public class TargeterBeanPostProcessor
implements BeanPostProcessor, BeanClassLoaderAware {
private final Environment environment;
private final DubboServiceMetadataRepository dubboServiceMetadataRepository;
private final DubboGenericServiceFactory dubboGenericServiceFactory;
private final DubboGenericServiceExecutionContextFactory contextFactory;
private ClassLoader classLoader;
public TargeterBeanPostProcessor(Environment environment,
DubboServiceMetadataRepository dubboServiceMetadataRepository,
DubboGenericServiceFactory dubboGenericServiceFactory,
DubboGenericServiceExecutionContextFactory contextFactory) {
this.environment = environment;
this.dubboServiceMetadataRepository = dubboServiceMetadataRepository;
this.dubboGenericServiceFactory = dubboGenericServiceFactory;
this.contextFactory = contextFactory;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, String beanName)
throws BeansException {
if (isPresent(TARGETER_CLASS_NAME, classLoader)) {
Class<?> beanClass = getUserClass(bean.getClass());
Class<?> targetClass = resolveClassName(TARGETER_CLASS_NAME, classLoader);
if (targetClass.isAssignableFrom(beanClass)) {
return newProxyInstance(classLoader, new Class[] { targetClass },
new TargeterInvocationHandler(bean, environment, classLoader,
dubboServiceMetadataRepository,
dubboGenericServiceFactory, contextFactory));
}
}
return bean;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
}
| 38.413793
| 104
| 0.812986
|
9f0a3c0ad75e339fc42cc970eb0f67748dcd070c
| 2,615
|
/*
* 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.commons.jelly.tags.http;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.TagSupport;
import org.apache.commons.jelly.XMLOutput;
/**
* A tag to hold parameters
*
* @author dion
* @version $Id$
*/
public class ParameterTag extends TagSupport {
/** parameter name */
private String _name;
/** parameter value */
private String _value;
/** Creates a new instance of ParameterTag */
public ParameterTag() {
}
/**
* Perform the tag functionality. In this case, simply evaluate the body.
*
* @param xmlOutput where to send output
* @throws Exception when an error occurs
*/
public void doTag(XMLOutput xmlOutput) throws JellyTagException {
HttpTagSupport http = (HttpTagSupport) findAncestorWithClass(
HttpTagSupport.class);
http.addParameter(getName(), getValue());
invokeBody(xmlOutput);
}
//--------------------------------------------------------------------------
// Property accessors/mutators
//--------------------------------------------------------------------------
/**
* Getter for property name.
*
* @return Value of property name.
*/
public String getName() {
return _name;
}
/**
* Setter for property name.
*
* @param name New value of property name.
*/
public void setName(String name) {
_name = name;
}
/**
* Getter for property value.
*
* @return Value of property value.
*/
public String getValue() {
return _value;
}
/**
* Setter for property value.
*
* @param value New value of property value.
*/
public void setValue(String value) {
_value = value;
}
}
| 28.11828
| 80
| 0.617973
|
ff98948363f149f85e209ccda9ab2c4238316d90
| 92
|
/** Package location for Pure Fabrication util classes tests. */
package lapr.project.utils;
| 46
| 64
| 0.782609
|
c10c55be2c42c8a1079b8c2c978dc6d622c9ff04
| 3,104
|
package me.neznamy.tab.api;
import java.util.UUID;
public interface TabPlayer {
/**
* Changes the requested property of a player temporarily (until next restart, reload or /tab reload)
* @param type Type of property
* @param value The value to be used
* @since 2.8.3
*/
public void setValueTemporarily(EnumProperty type, String value);
/**
* Changes the requested property of a player permanently (saved into config too)
* @param type Type of property
* @param value The value to be used
* @since 2.8.3
*/
public void setValuePermanently(EnumProperty type, String value);
/**
* Returns temporary value of player's property or null if not set
* @param type Type of property
* @return Temporary value of player's property or null if not set
* @see hasTemporaryValue
* @see setValueTemporarily
* @since 2.8.3
*/
public String getTemporaryValue(EnumProperty type);
/**
* Returns Whether player has temporary value or not
* @param type Type of property
* @return Whether player has temporary value or not
* @since 2.8.3
*/
public boolean hasTemporaryValue(EnumProperty type);
/**
* Removes temporary value from player if set
* @param type Type of property
* @since 2.8.3
*/
public void removeTemporaryValue(EnumProperty type);
/**
* Returns original value of property of player
* @param type Type of property
* @return Original value of property of player
* @since 2.8.3
*/
public String getOriginalValue(EnumProperty type);
/**
* Sends requested header and footer to player
* @param header - Header
* @param footer - Footer
* @since 2.8.3
*/
public void sendHeaderFooter(String header, String footer);
/**
* Makes player's nametag invisible until server restart/reload or /plugman reload tab
* @see showNametag
* @see hasHiddenNametag
* @since 2.8.3
*/
public void hideNametag();
/**
* Makes player's nametag visible again
* @see hideNametag
* @see hasHiddenNametag
* @since 2.8.3
*/
public void showNametag();
/**
* Return whether player has hidden nametag or not
* @return Whether player has hidden nametag or not
* @since 2.8.3
* @see hideNametag
* @see showNametag
*/
public boolean hasHiddenNametag();
/**
* Refreshes all visuals on the player
* @since 2.8.3
*/
public void forceRefresh();
/**
* Displays a scoreboard created using TABAPI.createScoreboard method
* @see removeCustomScoreboard
* @since 2.8.3
*/
public void showScoreboard(Scoreboard scoreboard);
/**
* Displays a scoreboard defined in premiumconfig.yml
* @see removeCustomScoreboard
* @since 2.8.3
*/
public void showScoreboard(String name);
/**
* Removes forced scoreboard sent using one of the showScoreboard methods
* @see showScoreboard
* @since 2.8.3
*/
public void removeCustomScoreboard();
/**
* Returns player's name
* @return Player's name
* @since 2.8.3
*/
public String getName();
/**
* Returns player's UUID
* @return Player's UUID
* @since 2.8.3
*/
public UUID getUniqueId();
}
| 21.406897
| 102
| 0.685889
|
c0f35c6f0c887620653128782e15674b12ebdef9
| 1,547
|
package dixx.game;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class StartActivity extends AppCompatActivity {
private MediaPlayer mp;
@Override
protected void onCreate(Bundle SavedInstance)
{
super.onCreate(SavedInstance);
setContentView(R.layout.activity_main);
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().name("realmdb.realm")
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(config);
mp = MediaPlayer.create(StartActivity.this, R.raw.sound);
mp.start();
Thread thread = new Thread()
{
@Override
public void run()
{
try
{
sleep(5000);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
Intent mainIntent = new Intent(StartActivity.this, MainActivity.class);
startActivity(mainIntent);
}
}
};
thread.start();
}
@Override
protected void onPause() {
super.onPause();
mp.release();
finish();
}
}
| 23.8
| 92
| 0.515837
|
628b10b015a799fcc1ad4f54e37b9c54821699e1
| 1,220
|
/*
* ExponentialDistribution.java
*
* Created on August 9, 2005, 3:24 PM
*
* author: Stephen A. Smith
*/
package jade.math;
import java.util.*;
/**
*
* @author stephensmith
*/
public class ExponentialDistribution implements ProbDistribution{
/** Creates a new instance of ExponentialDistribution */
public ExponentialDistribution() {
}
public ExponentialDistribution( double beta ){
if(beta<=0)
throw new IllegalArgumentException(" Exponential fall-off must be positive ( function was sent a negative value ) ");
else
this.beta = beta;
}
/**
*@param beta the falloff value for the exponential distribution
*/
public void setFallOff( double beta ){
this.beta = beta;
}
public double getFallOff(){ return beta; }
public double getValue(){
return -beta * Math.log(r.nextDouble());
}
//
//probability of finding something smaller than x
//@return the intregral of the probability distribution function from 0 to x
public double getPDF(double x){
return (1/beta)*Math.exp(-(1/beta)*x);
}
private double beta;
private Random r = new Random();
}
| 24.897959
| 129
| 0.633607
|
c9af9d5da5c43c183b7f334138ae9100e735d40b
| 3,987
|
package c.a.l.a;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import androidx.core.graphics.drawable.a;
public class c extends Drawable implements Drawable.Callback {
/* renamed from: b reason: collision with root package name */
private Drawable f1812b;
public c(Drawable drawable) {
a(drawable);
}
public Drawable a() {
return this.f1812b;
}
public void a(Drawable drawable) {
Drawable drawable2 = this.f1812b;
if (drawable2 != null) {
drawable2.setCallback(null);
}
this.f1812b = drawable;
if (drawable != null) {
drawable.setCallback(this);
}
}
public void draw(Canvas canvas) {
this.f1812b.draw(canvas);
}
public int getChangingConfigurations() {
return this.f1812b.getChangingConfigurations();
}
public Drawable getCurrent() {
return this.f1812b.getCurrent();
}
public int getIntrinsicHeight() {
return this.f1812b.getIntrinsicHeight();
}
public int getIntrinsicWidth() {
return this.f1812b.getIntrinsicWidth();
}
public int getMinimumHeight() {
return this.f1812b.getMinimumHeight();
}
public int getMinimumWidth() {
return this.f1812b.getMinimumWidth();
}
public int getOpacity() {
return this.f1812b.getOpacity();
}
public boolean getPadding(Rect rect) {
return this.f1812b.getPadding(rect);
}
public int[] getState() {
return this.f1812b.getState();
}
public Region getTransparentRegion() {
return this.f1812b.getTransparentRegion();
}
public void invalidateDrawable(Drawable drawable) {
invalidateSelf();
}
public boolean isAutoMirrored() {
return a.f(this.f1812b);
}
public boolean isStateful() {
return this.f1812b.isStateful();
}
public void jumpToCurrentState() {
this.f1812b.jumpToCurrentState();
}
/* access modifiers changed from: protected */
public void onBoundsChange(Rect rect) {
this.f1812b.setBounds(rect);
}
/* access modifiers changed from: protected */
public boolean onLevelChange(int i2) {
return this.f1812b.setLevel(i2);
}
public void scheduleDrawable(Drawable drawable, Runnable runnable, long j2) {
scheduleSelf(runnable, j2);
}
public void setAlpha(int i2) {
this.f1812b.setAlpha(i2);
}
public void setAutoMirrored(boolean z) {
a.a(this.f1812b, z);
}
public void setChangingConfigurations(int i2) {
this.f1812b.setChangingConfigurations(i2);
}
public void setColorFilter(ColorFilter colorFilter) {
this.f1812b.setColorFilter(colorFilter);
}
public void setDither(boolean z) {
this.f1812b.setDither(z);
}
public void setFilterBitmap(boolean z) {
this.f1812b.setFilterBitmap(z);
}
public void setHotspot(float f2, float f3) {
a.a(this.f1812b, f2, f3);
}
public void setHotspotBounds(int i2, int i3, int i4, int i5) {
a.a(this.f1812b, i2, i3, i4, i5);
}
public boolean setState(int[] iArr) {
return this.f1812b.setState(iArr);
}
public void setTint(int i2) {
a.b(this.f1812b, i2);
}
public void setTintList(ColorStateList colorStateList) {
a.a(this.f1812b, colorStateList);
}
public void setTintMode(PorterDuff.Mode mode) {
a.a(this.f1812b, mode);
}
public boolean setVisible(boolean z, boolean z2) {
return super.setVisible(z, z2) || this.f1812b.setVisible(z, z2);
}
public void unscheduleDrawable(Drawable drawable, Runnable runnable) {
unscheduleSelf(runnable);
}
}
| 24.018072
| 81
| 0.638826
|
52eab14055096f87841e956a9745223c724f89a5
| 8,952
|
package com.jerryjin.kit.img.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.jerryjin.kit.img.loader.GlideImageLoader;
import com.jerryjin.kit.img.loader.ImageLoader;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Author: Jerry
* Generated at: 2019/5/2 13:31
* GitHub: https://github.com/JerryJin93
* Blog:
* WeChat: enGrave93
* Version: 1.0.0
* Description: View group for 1 {@link CircleImageView} object and many {@link CrescentImageView} objects.
*/
public class PeekGallery extends ViewGroup {
private static final int DEFAULT_SIZE = 100;
private static final String TAG = "PeekGallery";
private static final boolean DEBUG = true;
private static final int ERROR_CODE = -1;
private Context mContext;
private List<ImageView> absImageViews = new ArrayList<>();
private ImageLoader mImageLoader;
private List<Object> mImages = new ArrayList<>();
private PopupWindow mPeekWindow;
private int intersectionLen = ERROR_CODE;
private int mAvailableWidth;
private Handler handler = new Handler(Looper.getMainLooper());
public PeekGallery(@NonNull Context context) {
this(context, null);
}
public PeekGallery(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public PeekGallery(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
int height;
mAvailableWidth = widthSpecSize - getPaddingLeft() - getPaddingRight();
measureChildren(widthMeasureSpec, heightMeasureSpec);
if (DEBUG) {
Log.d(TAG, "measure children.");
}
int childCount = getChildCount();
int maxLineHeight = 0;
int childWidth = getChildWidth();
if (childCount > 0) {
maxLineHeight = getChildAt(0).getMeasuredHeight();
}
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (maxLineHeight < child.getMeasuredHeight()) {
maxLineHeight = child.getMeasuredHeight();
}
}
height = maxLineHeight + getPaddingTop() + getPaddingBottom();
if (DEBUG) {
Log.d(TAG, "maxLineHeight: " + maxLineHeight);
Log.d(TAG, "height: " + height);
}
int newWidth = getPaddingLeft() + childWidth + (childCount - 1) * (childWidth - intersectionLen) + getPaddingRight();
if (childCount == 0) {
setMeasuredDimension(0, 0);
} else if ((widthSpecMode == MeasureSpec.AT_MOST || widthSpecMode == MeasureSpec.UNSPECIFIED)
&& (heightSpecMode == MeasureSpec.AT_MOST || heightSpecMode == MeasureSpec.UNSPECIFIED)) {
setMeasuredDimension(newWidth, height);
} else {
setMeasuredDimension(widthSpecSize, height);
}
// layout child -> trigger {@link CrescentImageView#computeIntersectionLen()}
// layout -> sizedChange -> onSizeChanged
performOnLayout();
}
/**
* It has to be invoked after {@link ViewGroup#measureChildren(int, int)}.
*
* @return The suitable width of each child for PeekGallery.
*/
private int getChildWidth() {
int childCount = getChildCount();
if (childCount == 0) {
return 0;
} else {
return getChildAt(0).getMeasuredWidth();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
performOnLayout();
}
private void performOnLayout() {
int childCount = getChildCount();
if (childCount == 0) {
return;
}
if (DEBUG) {
Log.d(TAG, "perform onLayout children.");
}
mAvailableWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
final int maxRight = mAvailableWidth + getPaddingLeft();
if (DEBUG) {
Log.d(TAG, "measuredWidth: " + getMeasuredWidth());
Log.d(TAG, "maxRight: " + maxRight);
}
int mTop = getPaddingTop();
int mLeft;
int maxHeight = 0;
int overallWidth = getPaddingLeft() + getPaddingRight();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (maxHeight == 0) {
maxHeight = child.getMeasuredHeight();
} else {
maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
}
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
mLeft = getPaddingLeft() + (i != 0 ? i * (childWidth - (intersectionLen = ((CrescentImageView) child).getIntersectionLen())) : 0);
child.layout(mLeft, mTop, mLeft + childWidth, mTop + childHeight);
if (DEBUG) {
Log.d(TAG, "left: " + mLeft + ", top: " + mTop + ", right: " + (mLeft + childWidth) + ", bottom: " + (mTop + childHeight));
}
// use CircleImageView for now.
if (child instanceof CircleImageView) {
overallWidth += childWidth;
} else if (child instanceof CrescentImageView) {
overallWidth += childWidth - ((CrescentImageView) child).getIntersectionLen();
}
if (DEBUG) {
Log.d(TAG, "overallWidth: " + overallWidth);
}
if (overallWidth > maxRight) {
if (DEBUG) {
Log.d(TAG, "break at " + i);
}
// ensure the last view is intact.
child.setVisibility(GONE);
break;
}
}
}
private void init(Context context, AttributeSet attrs) {
mContext = context;
mPeekWindow = new PopupWindow(mContext);
if (attrs != null) {
// TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PeekGallery);
// mGap = ta.getDimensionPixelSize(R.styleable.PeekGallery_gap, 0);
// ta.recycle();
} else {
}
}
public void setImageLoader(ImageLoader imageLoader) {
this.mImageLoader = imageLoader;
}
private PeekGallery.LayoutParams generateLayoutParams(int width, int height) {
return new PeekGallery.LayoutParams(width, height);
}
public void addImage(Object img, int pos, int width, int height) {
if (mImages != null) {
if (mImageLoader == null) {
mImageLoader = new GlideImageLoader();
}
ImageView imageView;
PeekGallery.LayoutParams params = generateLayoutParams(width, height);
if (pos == 0) {
imageView = new CircleImageView(mContext);
// params1.leftMargin = pos * (100 - (intersectionLen = ((CrescentImageView) tmp).getIntersectionLen()));
} else {
imageView = new CrescentImageView(mContext);
}
imageView.setLayoutParams(params);
mImageLoader.showImage(mContext, img, imageView);
addView(imageView);
absImageViews.add(imageView);
}
}
public void setImages(List<Object> images) {
setImages(images, DEFAULT_SIZE, DEFAULT_SIZE);
}
public void setImages(List<Object> images, int width, int height) {
if (images == null) {
Log.e(TAG, "Null given images.");
return;
}
clear();
for (int i = 0; i < images.size(); i++) {
addImage(images.get(i), i, width, height);
}
requestLayout();
}
public void clear() {
if (absImageViews.size() == 0) {
Log.i(TAG, "No image inside, skip.");
return;
}
absImageViews.clear();
removeAllViews();
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
}
| 33.27881
| 142
| 0.600871
|
9350e128918a629ef5c4ed8f7846ebad6b893dc7
| 1,748
|
/*
* Copyright (C) 2020 ActiveJ LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.activej.test.rules;
import io.activej.test.TestUtils;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
/**
* {@link TestRule} that fails if not all active promises have been completed either successfully or exceptionally.
* Promises to be monitored should have either a {@link TestUtils#assertCompleteFn()}
* listener attached
*/
public final class ActivePromisesRule implements TestRule {
private static final Logger logger = LoggerFactory.getLogger(ActivePromisesRule.class);
@Override
public Statement apply(Statement base, Description description) {
return new LambdaStatement(() -> {
TestUtils.clearActivePromises();
try {
base.evaluate();
} catch (Throwable t) {
int n = TestUtils.getActivePromises();
if (n != 0) {
logger.info(n + " promise assertion" + (n == 1 ? " was" : "s were") + " not checked");
}
throw t;
}
assertEquals("Some promises have not been completed", 0, TestUtils.getActivePromises());
});
}
}
| 32.981132
| 115
| 0.730549
|
cead699e9d5f3c0f5e0ebe7198aa413d39d28757
| 7,830
|
/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
* Copyright © 2017-2018 European Software Marketing Ltd.
* ================================================================================
* 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.
* ============LICENSE_END=========================================================
*/
package org.onap.aai.modelloader.entity.catalog;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.onap.aai.modelloader.config.ModelLoaderConfig;
import org.onap.aai.modelloader.entity.Artifact;
import org.onap.aai.modelloader.entity.ArtifactType;
import org.onap.aai.modelloader.restclient.AaiRestClient;
import org.onap.aai.restclient.client.OperationResult;
public class TestVnfCatalogArtifactHandler {
protected static String CONFIG_FILE = "model-loader.properties";
private AaiRestClient mockRestClient = mock(AaiRestClient.class);
/**
* Update A&AI with 4 images, 2 of which already exist.
*
* @throws Exception
*/
@Test
public void testUpdateVnfImages() throws Exception {
// GET operation
OperationResult mockGetResp = mock(OperationResult.class);
// @formatter:off
when(mockGetResp.getResultCode())
.thenReturn(Response.Status.OK.getStatusCode())
.thenReturn(Response.Status.NOT_FOUND.getStatusCode())
.thenReturn(Response.Status.NOT_FOUND.getStatusCode())
.thenReturn(Response.Status.OK.getStatusCode());
// @formatter:on
when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class)))
.thenReturn(mockGetResp);
mockPutOperations();
// Example VNF Catalog XML
VnfCatalogArtifactHandler handler = new VnfCatalogArtifactHandler(createConfig());
assertThat(handler.pushArtifacts(createVnfCatalogArtifact(), "test", new ArrayList<Artifact>(), mockRestClient),
is(true));
assertPutOperationsSucceeded();
}
@Test
public void testUpdateVnfImagesFromXml() throws Exception {
// GET operation
OperationResult mockGetResp = mock(OperationResult.class);
// @formatter:off
when(mockGetResp.getResultCode())
.thenReturn(Response.Status.OK.getStatusCode())
.thenReturn(Response.Status.NOT_FOUND.getStatusCode())
.thenReturn(Response.Status.NOT_FOUND.getStatusCode())
.thenReturn(Response.Status.OK.getStatusCode());
// @formatter:on
when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class)))
.thenReturn(mockGetResp);
mockPutOperations();
// Example VNF Catalog XML
VnfCatalogArtifactHandler handler = new VnfCatalogArtifactHandler(createConfig());
assertThat(
handler.pushArtifacts(createVnfCatalogXmlArtifact(), "test", new ArrayList<Artifact>(), mockRestClient),
is(true));
// Only two of the VNF images should be pushed
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
AaiRestClient client = Mockito.verify(mockRestClient, Mockito.times(2));
client.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(), Mockito.any(MediaType.class));
assertThat(argument.getAllValues().size(), is(2));
assertThat(argument.getAllValues().get(0), containsString("5.2.5"));
assertThat(argument.getAllValues().get(0), containsString("VM00"));
assertThat(argument.getAllValues().get(1), containsString("5.2.4"));
assertThat(argument.getAllValues().get(1), containsString("VM00"));
}
private ModelLoaderConfig createConfig() {
Properties configProperties = new Properties();
try {
configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE));
} catch (IOException e) {
fail();
}
ModelLoaderConfig config = new ModelLoaderConfig(configProperties, null);
return config;
}
/**
* Example VNF Catalog based on JSON data (returned by Babel)
*
* @return test Artifacts
* @throws IOException
* @throws UnsupportedEncodingException
*/
private List<Artifact> createVnfCatalogArtifact() throws IOException, UnsupportedEncodingException {
String examplePath = "src/test/resources/imagedataexample.json";
byte[] encoded = Files.readAllBytes(Paths.get(examplePath));
List<Artifact> artifacts = new ArrayList<Artifact>();
artifacts.add(new VnfCatalogArtifact(new String(encoded, "utf-8")));
return artifacts;
}
/**
* Example VNF Catalog based on VNF_CATALOG XML
*
* @return test Artifacts
* @throws IOException
* @throws UnsupportedEncodingException
*/
private List<Artifact> createVnfCatalogXmlArtifact() throws IOException, UnsupportedEncodingException {
byte[] encoded = Files.readAllBytes(Paths.get("src/test/resources/xmlFiles/fortigate.xml"));
List<Artifact> artifacts = new ArrayList<Artifact>();
artifacts.add(new VnfCatalogArtifact(ArtifactType.VNF_CATALOG_XML, new String(encoded, "utf-8")));
return artifacts;
}
/**
* Always return CREATED (success) for a PUT operation.
*/
private void mockPutOperations() {
OperationResult mockPutResp = mock(OperationResult.class);
when(mockPutResp.getResultCode()).thenReturn(Response.Status.CREATED.getStatusCode());
when(mockRestClient.putResource(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
Mockito.any(MediaType.class))).thenReturn(mockPutResp);
}
private void assertPutOperationsSucceeded() {
// Only two of the VNF images should be pushed
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
AaiRestClient mockedClient = Mockito.verify(mockRestClient, Mockito.times(2));
mockedClient.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(),
Mockito.any(MediaType.class));
assertThat(argument.getAllValues().get(0), containsString("3.16.9"));
assertThat(argument.getAllValues().get(0), containsString("VM00"));
assertThat(argument.getAllValues().get(1), containsString("3.16.1"));
assertThat(argument.getAllValues().get(1), containsString("VM01"));
}
}
| 43.5
| 120
| 0.66986
|
4f6c5c61b86d8a54431b6063f1b761c3f0ed9c90
| 8,194
|
package gov.med.va.innovations.ui.action;
import gov.med.va.innovations.Constants;
import gov.med.va.innovations.domain.Component;
import gov.med.va.innovations.domain.Template;
import gov.med.va.innovations.domain.VistaLocation;
import gov.med.va.innovations.service.PagingLookupManager;
import gov.med.va.innovations.service.TemplateManager;
import gov.med.va.innovations.ui.listener.StartupListener;
import gov.med.va.innovations.ui.util.ExtendedPaginatedList;
import gov.med.va.innovations.ui.util.PaginateListFactory;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.displaytag.pagination.PaginatedList;
import org.springframework.dao.DataIntegrityViolationException;
import com.opensymphony.xwork2.validator.annotations.Validation;
@Validation
public class TemplateAction extends BaseAction implements ServletContextAware {
private static final long serialVersionUID = 110706864090515863L;
private static final String COMPONENT = "component";
private PagingLookupManager pagingManager;
private PaginateListFactory paginatedListFactory;
private TemplateManager templateManager;
private PaginatedList templates;
private Template template;
private Component component;
private Long id;
private Long componentId;
private ServletContext sContext;
public void setId(Long id) {
this.id = id;
}
public Template getTemplate() {
return template;
}
public void setTemplate(Template template) {
this.template = template;
}
public void setPagingLookupManager(PagingLookupManager pagingManager) {
this.pagingManager = pagingManager;
}
public void setPaginatedListFactory(PaginateListFactory paginatedListFactory) {
this.paginatedListFactory = paginatedListFactory;
}
public void setTemplateManager(
TemplateManager templateManager2) {
this.templateManager = (TemplateManager) templateManager2;
}
public String lookup() {
loadTemplates();
return SUCCESS;
}
public PaginatedList getTemplates() {
return templates;
}
@SuppressWarnings("unchecked")
public List<VistaLocation> getWards() {
if (null == getSession().getAttribute(Constants.WARD_LIST)) {
getSession().setAttribute(Constants.WARD_LIST, vistaManager.getWards());
}
return (List<VistaLocation>) getSession().getAttribute(Constants.WARD_LIST);
}
public String list() {
loadTemplates();
return SUCCESS;
}
private void loadTemplates() {
ExtendedPaginatedList paginatedList = paginatedListFactory
.getPaginatedListFromRequest(getRequest());
paginatedList.setSortCriterion("template_name");
templates = pagingManager.getAllRecordsPage(Template.class, paginatedList);
}
public String delete() {
templateManager.remove(template.getId());
saveMessage(getText("template.deleted"));
return SUCCESS;
}
public String deleteComponent() {
templateManager.removeComponent(component.getId());
StartupListener.setupContext(sContext);
saveMessage(getText("component.deleted"));
return SUCCESS;
}
public String edit() {
if (id != null) {
template = (Template) templateManager.get(id);
stripMandatory();
} else {
template = new Template();
}
return SUCCESS;
}
private void stripMandatory() {
// Strip all Mandatory components, as these are not editable
List<Component> comps = new ArrayList<Component>();
comps.addAll(template.getComponents());
for (Component comp:comps) {
if (comp.isMandatory()) {
template.getComponents().remove(comp);
}
}
}
public String editComponent() {
Long compId = (Long) getRequest().getAttribute("componentId");
if (componentId != null) {
component = (Component) templateManager.getComponent(componentId);
} else if (compId != null) {
component = (Component) templateManager.getComponent(compId);
componentId = compId;
} else {
component = new Component();
}
return SUCCESS;
}
public String doComponent() {
getRequest().setAttribute("componentId", this.componentId);
return COMPONENT;
}
public String getJsonComponents() {
List<JSONObject> comps = new ArrayList<JSONObject>();
for (Component comp : templateManager.getComponentsByType(false)) {
JSONObject json = new JSONObject();
try {
json.put("id", comp.getId());
json.put("name", comp.getName());
comps.add(json);
} catch (JSONException e) {
LOG.error("Error converting component to JSON", e);
}
}
return new JSONArray(comps).toString();
}
public boolean isComponentOwned() {
return templateManager.isComponentOwned(componentId);
}
public String save() throws Exception {
if (cancel != null) {
return CANCEL;
}
if (LOG.isDebugEnabled()) LOG.debug("Starting Save...");
if (delete != null) {
return delete();
}
boolean isNew = (template.getId() == null);
try {
List<Component> components = templateManager.getAllComponents();
String[] selComponents = getRequest().getParameterValues("components");
if (null == selComponents)
selComponents = new String[]{};
template.setComponents(new ArrayList<Component>(selComponents.length));
for (String componentName : selComponents) {
for (Component comp : components) {
if (comp.getName().equals(componentName)) {
template.getComponents().add(comp);
break;
}
}
}
if (null == template.getCreatedBy())
template.setCreatedBy(getRequest().getUserPrincipal().getName());
template = (Template) templateManager.saveTemplate(template);
stripMandatory();
}
catch(DataIntegrityViolationException die) {
addActionError(getText("template.exists", new String[]{template.getName()}));
return INPUT;
}
String key = (isNew) ? "template.added" : "template.updated";
saveMessage(getText(key));
if (!isNew) {
return INPUT;
} else {
return SUCCESS;
}
}
public String saveComponent() throws Exception {
if (cancel != null) {
return CANCEL;
}
if (LOG.isDebugEnabled()) LOG.debug("Starting SaveComponent...");
if (delete != null) {
return deleteComponent();
}
boolean isNew = (component.getId() == null);
try {
if (!component.getTitle().startsWith("<h4>")) {
component.setTitle(new StringBuffer("<h4>").append(component.getTitle()).append("</h4>").toString());
}
if (isNew) {
component.setMandatory(false);
component.setMethod("getDefault");
}
if (null == component.getCreatedBy())
component.setCreatedBy(getRequest().getUserPrincipal().getName());
component = (Component) templateManager.saveComponent(component);
}
catch(DataIntegrityViolationException die) {
addActionError(getText("component.exists", new String[]{component.getName()}));
return INPUT;
}
StartupListener.setupContext(sContext);
String key = (isNew) ? "component.added" : "component.updated";
saveMessage(getText(key));
if (!isNew) {
return INPUT;
} else {
return SUCCESS;
}
}
public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
@Override
public void setServletContext(ServletContext ctx) {
this.sContext = ctx;
}
public Long getComponentId() {
return componentId;
}
public void setComponentId(Long componentId) {
this.componentId = componentId;
}
}
| 28.65035
| 109
| 0.664267
|
b07ccc09145c653a24075a30ced7b7ed3ae0a89f
| 3,236
|
/*
* 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.kafka.connect.data;
import org.apache.kafka.connect.errors.DataException;
import org.junit.jupiter.api.Test;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class TimeTest {
private static final GregorianCalendar EPOCH;
private static final GregorianCalendar EPOCH_PLUS_DATE_COMPONENT;
private static final GregorianCalendar EPOCH_PLUS_TEN_THOUSAND_MILLIS;
static {
EPOCH = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
EPOCH.setTimeZone(TimeZone.getTimeZone("UTC"));
EPOCH_PLUS_TEN_THOUSAND_MILLIS = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
EPOCH_PLUS_TEN_THOUSAND_MILLIS.setTimeZone(TimeZone.getTimeZone("UTC"));
EPOCH_PLUS_TEN_THOUSAND_MILLIS.add(Calendar.MILLISECOND, 10000);
EPOCH_PLUS_DATE_COMPONENT = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
EPOCH_PLUS_DATE_COMPONENT.setTimeZone(TimeZone.getTimeZone("UTC"));
EPOCH_PLUS_DATE_COMPONENT.add(Calendar.DATE, 10000);
}
@Test
public void testBuilder() {
Schema plain = Time.SCHEMA;
assertEquals(Time.LOGICAL_NAME, plain.name());
assertEquals(1, (Object) plain.version());
}
@Test
public void testFromLogical() {
assertEquals(0, Time.fromLogical(Time.SCHEMA, EPOCH.getTime()));
assertEquals(10000, Time.fromLogical(Time.SCHEMA, EPOCH_PLUS_TEN_THOUSAND_MILLIS.getTime()));
}
@Test
public void testFromLogicalInvalidSchema() {
assertThrows(DataException.class,
() -> Time.fromLogical(Time.builder().name("invalid").build(), EPOCH.getTime()));
}
@Test
public void testFromLogicalInvalidHasDateComponents() {
assertThrows(DataException.class,
() -> Time.fromLogical(Time.SCHEMA, EPOCH_PLUS_DATE_COMPONENT.getTime()));
}
@Test
public void testToLogical() {
assertEquals(EPOCH.getTime(), Time.toLogical(Time.SCHEMA, 0));
assertEquals(EPOCH_PLUS_TEN_THOUSAND_MILLIS.getTime(), Time.toLogical(Time.SCHEMA, 10000));
}
@Test
public void testToLogicalInvalidSchema() {
assertThrows(DataException.class,
() -> Time.toLogical(Time.builder().name("invalid").build(), 0));
}
}
| 38.52381
| 101
| 0.720952
|
0290784e72c15b8fcee2eb633746f4030fbbb32b
| 2,739
|
/* Copyright 2022 G. Matthew Heitker
*
* 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.dappermoose.batchlitcal.calendar;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Locale;
import javax.inject.Inject;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
/**
* This is the class which makes the calendar.
*
* @author heitkergm@acm.org
*/
@Slf4j
@Component
public class MakeCalendar
{
@Inject
private MessageSource messageSource;
@Inject
private Locale locale;
@Inject
private BufferedWriter writer;
@Inject
private OutputUtils outputUtils;
/**
* Make an instance of the calendar maker class.
*/
public MakeCalendar ()
{
LOG.debug ("Creating the MakeCalendar class");
}
/**
* this is the routine which makes the calendar.
*/
public void makeCal ()
{
String msg = messageSource.getMessage ("startCalendar", null, locale);
LOG.info (msg);
// make the 6 "seasons"
// 1 Advent
// 2 Christmas
// 3 Ordinary time, beginning at week 1
// 4 Lent
// 5 Easter
// 6 Ordinary time, ending at week 34 (Christ the King)
// for each, put the seasonal dates.
// when done with seasons, as a multi-stage processor, do the following:
// override seasonal entries for Solemnities and Feasts
// put in memorials and optional memorials
// along the way, add options to CalendarOptions.
// e.g. observe Ascension on Thursday or following Sunday,
// observe Epiphany on Jan 6 or first Sunday after New Year,
// country-specific Solemnities, Feasts, Memorials, and Optional
// Memorials...
// etc.
outputUtils.writeHeader ();
// THE END
outputUtils.writeFooter ();
try
{
// close does a flush, then closes
writer.close ();
}
catch (IOException e)
{
LOG.error (e.getClass ().getName () + " " + e.getMessage ());
}
}
}
| 26.852941
| 80
| 0.633078
|
e962c2a37cdd32676174ce508bf62a0d63686f02
| 2,520
|
package org.interledger.core.asn.codecs;
import static java.lang.String.format;
import org.interledger.core.InterledgerFulfillPacket;
import org.interledger.core.InterledgerPacket;
import org.interledger.core.InterledgerPreparePacket;
import org.interledger.core.InterledgerRejectPacket;
import org.interledger.encoding.asn.codecs.AsnOpenTypeCodec;
import org.interledger.encoding.asn.codecs.AsnSequenceCodec;
import org.interledger.encoding.asn.codecs.AsnUint8Codec;
import org.interledger.encoding.asn.framework.AsnObjectCodec;
import org.interledger.encoding.asn.framework.CodecException;
/**
* ASN.1 object representing an {@link InterledgerPacket} including it's type code prefix.
*/
public class AsnInterledgerPacketCodec<T extends InterledgerPacket> extends AsnSequenceCodec<T> {
/**
* Default constructor.
*/
public AsnInterledgerPacketCodec() {
super(new AsnUint8Codec(), null);
AsnUint8Codec asnTypeId = (AsnUint8Codec) getCodecAt(0);
asnTypeId.setEncodeEventListener(this::onTypeIdChanged);
}
@Override
public T decode() {
return getValueAt(1);
}
@Override
public void encode(T value) {
if (value instanceof InterledgerPreparePacket) {
setValueAt(0, InterledgerPacketTypes.PREPARE);
} else if (value instanceof InterledgerFulfillPacket) {
setValueAt(0, InterledgerPacketTypes.FULFILL);
} else if (value instanceof InterledgerRejectPacket) {
setValueAt(0, InterledgerPacketTypes.REJECT);
} else {
throw new CodecException(
format("Unknown Interledger Packet Type: %s", value.getClass().getName()));
}
setValueAt(1, value);
}
protected void onTypeIdChanged(Integer typeId) {
//The packet type has been set so set the packet data
switch (typeId) {
case InterledgerPacketTypes.PREPARE:
setCodecAt(1, new AsnOpenTypeCodec<>(new AsnInterledgerPreparePacketDataCodec()));
return;
case InterledgerPacketTypes.FULFILL:
setCodecAt(1, new AsnOpenTypeCodec<>(new AsnInterledgerFulfillPacketDataCodec()));
return;
case InterledgerPacketTypes.REJECT:
setCodecAt(1, new AsnOpenTypeCodec<>(new AsnInterledgerRejectPacketDataCodec()));
return;
default:
throw new CodecException(
format("Unknown Interledger packet type code: %s", typeId));
}
}
private static class InterledgerPacketTypes {
static final int PREPARE = 12;
static final int FULFILL = 13;
static final int REJECT = 14;
}
}
| 31.111111
| 97
| 0.734921
|
8399e80812b97beaec41552910d544a28e21edda
| 3,678
|
//
// $Id: MailTemplate.java 5677 2004-12-09 14:59:48Z anunez $
//
package edu.gemini.shared.mail;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* An email template, which can be used to substitute variables of the form
* <code>@VARIABLE_NAME@</code> for their corresponding values. A few
* "standard" variables are known by the Template class itself, and can be
* obtained with their current value by calling {@link #addPluralProperties}
* method.
*/
public class MailTemplate {
/** Current date formatted for the platform's default locale. */
// public static final String DATE_VAR = "DATE";
/** Current time formatted for the platform's default locale. */
// public static final String TIME_VAR = "TIME";
/** Current date and time formated for the platform's default locale. */
// public static final String DATE_TIME_VAR = "DATE_TIME";
/** "is" or "are" */
public static final String IS_ARE_VAR = "IS_ARE";
/** "was" or "were" */
public static final String WAS_WERE_VAR = "WAS_WERE";
/** "have" or "has" */
public static final String HAS_HAVE_VAR = "HAS_HAVE";
/** "s" or "" */
public static final String S_OR_EMPTY_VAR = "S_OR_EMPTY";
private String _tmplText;
// private static final DateFormat _dateFormatInstance = DateFormat.getDateInstance();
// private static final DateFormat _timeFormatInstance = DateFormat.getTimeInstance();
// private static final DateFormat _dateTimeFormatInstance = DateFormat.getDateTimeInstance();
public MailTemplate(String tmplText) {
_tmplText = tmplText;
}
// public static void addDateProperties(Properties props, Calendar cal) {
// Date date = new Date();
// String dateStr = _dateFormatInstance.format(date);
// String timeStr = _timeFormatInstance.format(date);
// String dateAndTime = _dateTimeFormatInstance.format(date);
//
// props.put(DATE_VAR, dateStr);
// props.put(TIME_VAR, timeStr);
// props.put(DATE_TIME_VAR, dateAndTime);
// }
/**
* Adds values for all the singular vs plural properties. For example,
* "IS_ARE" and "WAS_WERE".
*
* @param props the Properties object to which the properties will be
* added
* @param isPlural if <code>true</code> choose values appropriate for
* a plural subject; otherwise values appropriate for a singular subject
*/
public static void addPluralProperties(Properties props, boolean isPlural) {
if (isPlural) {
props.put(IS_ARE_VAR, "are");
props.put(WAS_WERE_VAR, "were");
props.put(S_OR_EMPTY_VAR, "s");
props.put(HAS_HAVE_VAR, "have");
} else {
props.put(IS_ARE_VAR, "is");
props.put(WAS_WERE_VAR, "was");
props.put(S_OR_EMPTY_VAR, "");
props.put(HAS_HAVE_VAR, "has");
}
}
public String subsitute(Properties props) {
StringBuffer buf = new StringBuffer();
Pattern pat = Pattern.compile("@([A-Z_]*)@");
Matcher mat = pat.matcher(_tmplText);
for (boolean notDone = mat.find(); notDone; notDone = mat.find()) {
String var = mat.group(1);
String val = props.getProperty(var);
//TODO: Escape dollar signs, using something like .replaceAll("\\$","\\\\\\$");
if (val == null) {
// Just write the variable back in.
val = "@" + var + "@";
}
mat.appendReplacement(buf, val);
}
mat.appendTail(buf);
return buf.toString();
}
}
| 35.365385
| 97
| 0.629146
|
20b01e00c27085da114b4fb0cffaec6a072131c9
| 1,318
|
package org.lvgo.octopus.core;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.lvgo.octopus.bean.OctopusPage;
import org.lvgo.silent.TaskHandler;
/**
* 数据提取
*
* @author lvgorice@gmail.com
* @version 1.0
* @date 2019/12/12 10:21
*/
public interface Extractor {
/**
* 多线程解析时, 获取记录总页数&分页数据地址
*
* @param octopus 连接器(复制机)
* @return 记录总页数
*/
OctopusPage getPageInfo(Octopus octopus);
/**
* 提取数据
*
* @param octopus 连接信息, 包含请求及返回数据内容
*/
void extract(Octopus octopus);
/**
* 并发解析数据, 提供这个方法出于对 silent 不熟悉仍然可以开箱即用的多线程
* <p>
* 此方法为对 silent 处理数据的封装, 将上下文参数及数据参数 elements 提供给 #concurrentHandle 来处理
*
* @param octopus 上下文参数
* @param elements 数据元素
*/
default void concurrentHandle(Octopus octopus, Elements elements) {
// 线程数大于0时, 启动多线程处理
new TaskHandler<Element>(elements) {
@Override
public void run(Element element) {
// 提供方法用于用户对数据的解析处理
elementHandle(octopus, element);
}
}.sync(true).execute(Math.max(octopus.getPageSize(), 1));
}
/**
* 多线程数据数据元素处理
*
* @param octopus 上下文
* @param element 当前数据
*/
void elementHandle(Octopus octopus, Element element);
}
| 21.966667
| 75
| 0.603187
|
64ba09e29acc8a7e87c2fda739a8753f13fbe045
| 2,492
|
package com.msd.gin.examples.mapreduce;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.SnappyCodec;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.orc.mapred.OrcStruct;
import org.apache.orc.mapreduce.OrcOutputFormat;
public class OrcMapReduce extends Configured implements Tool {
@Override
public int run(String[] args) throws Exception {
Job job = parseInputAndOutput(this, getConf(), args);
if (job == null) {
return -1;
}
job.setInputFormatClass(TextInputFormat.class);
job.setMapperClass(OrcMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
job.setNumReduceTasks(1);
job.setReducerClass(OrcReducer.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(OrcStruct.class);
job.setOutputFormatClass(OrcOutputFormat.class);
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new Configuration(), new OrcMapReduce(), args);
System.exit(exitCode);
}
public static Job parseInputAndOutput(Tool tool, Configuration conf, String[] args) throws IOException {
if (args.length < 2) {
System.err.println("inputDirs outputDir");
return null;
}
conf.set("orc.compress", "SNAPPY");
conf.set("hive.exec.orc.default.compress", "SNAPPY");
conf.set("orc.mapred.output.schema", OrcReducer.SCHEMA);
Job job = Job.getInstance(conf);
OrcOutputFormat.setOutputCompressorClass(job, SnappyCodec.class);
job.setJarByClass(tool.getClass());
for (int i = 0; i < args.length - 1; i++) {
FileInputFormat.addInputPath(job, new Path(args[i]));
}
OrcOutputFormat.setOutputPath(job, new Path(args[args.length - 1] + File.separator + System.currentTimeMillis()));
return job;
}
}
| 38.338462
| 122
| 0.696629
|
41caf996e8c35d8fc891fcfb48f27797e1488835
| 434
|
package com.ekain06.neopi.item;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.ArmorMaterial;
public class UnbreakableArmorItem extends ArmorItem {
public UnbreakableArmorItem(ArmorMaterial material, EquipmentSlot slot, Settings settings) {
super(material, slot, settings);
}
@Override
public boolean isDamageable() {
return false;
}
}
| 25.529412
| 96
| 0.748848
|
aaf5be846ab06614e60886f41075b9ee31edff03
| 596
|
package cn.tswine.jdbc.plus.conditions.update;
import cn.tswine.jdbc.plus.conditions.AbstractWrapper;
/**
* @Author: silly
* @Date: 2019/9/18 20:37
* @Version 1.0
* @Desc
*/
public class UpdateWrapper extends AbstractWrapper<UpdateWrapper> implements Update<UpdateWrapper> {
String[] excludeColumns;
@Override
public UpdateWrapper exclude(String... excludeColumns) {
this.excludeColumns = excludeColumns;
return this;
}
/**
* 获取查询的列数据
*
* @return
*/
public String[] getExcludeColumns() {
return excludeColumns;
}
}
| 20.551724
| 100
| 0.657718
|
c4df21129aa8901c6658460e40c6219b5255c9f2
| 1,161
|
package com.vucao;
import java.util.Arrays;
public class MyStack
{
private String[] stack;
private int currentIndex;
public MyStack()
{
this.stack = new String[1000];
this.currentIndex = 0;
}
public void push(String s)
{
if (currentIndex == 1000)
{
System.out.println("Stack is full.");
} else
{
stack[currentIndex] = s;
currentIndex++;
}
}
public void pop()
{
if (currentIndex == 0)
{
System.out.println("There are no items in your Stack.");
} else
{
stack[currentIndex] = null;
currentIndex--;
}
}
public String getLength()
{
if (currentIndex==0)
{
return "There are no items in your Stack.";
}
return Integer.toString(currentIndex);
}
@Override
public String toString()
{
String[] rtnArr = new String[currentIndex];
for (int i=0; i<currentIndex; i++)
{
rtnArr[i] = stack[i];
}
return Arrays.toString(rtnArr);
}
}
| 18.725806
| 68
| 0.495263
|
e9aa2e57d320b670e0f5285087b6dfa08bb91e12
| 11,638
|
/*
* Copyright 2012 DTO Labs, Inc. (http://dtolabs.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.
*
*/
/*
* TestGeneratorPlugin.java
*
* User: Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
* Created: 11/20/12 11:15 AM
*
*/
package com.dtolabs.rundeck.plugin.example;
import com.dtolabs.rundeck.core.common.INodeEntry;
import com.dtolabs.rundeck.core.plugins.Plugin;
import com.dtolabs.rundeck.core.plugins.configuration.PropertyScope;
import com.dtolabs.rundeck.core.plugins.configuration.PropertyValidator;
import com.dtolabs.rundeck.core.plugins.configuration.ValidationException;
import com.dtolabs.rundeck.plugins.ServiceNameConstants;
import com.dtolabs.rundeck.plugins.descriptions.PluginDescription;
import com.dtolabs.rundeck.plugins.descriptions.PluginProperty;
import com.dtolabs.rundeck.plugins.descriptions.SelectValues;
import com.dtolabs.rundeck.plugins.descriptions.TextArea;
import com.dtolabs.rundeck.plugins.step.GeneratedScript;
import com.dtolabs.rundeck.plugins.step.GeneratedScriptBuilder;
import com.dtolabs.rundeck.plugins.step.PluginStepContext;
import com.dtolabs.rundeck.plugins.step.RemoteScriptNodeStepPlugin;
import com.dtolabs.rundeck.plugins.util.DescriptionBuilder;
import com.dtolabs.rundeck.plugins.util.PropertyBuilder;
import java.util.Map;
/**
* ExampleRemoteScriptNodeStepPlugin demonstrates a basic {@link com.dtolabs.rundeck.plugins.step.RemoteScriptNodeStepPlugin},
* it extends the {@link com.dtolabs.rundeck.plugins.step.BaseRemoteScriptNodeStepPlugin}. This example demonstrates how
* to annotate instance fields to define the plugin's Properties that should be exposed in the Rundeck GUI. At execution
* time, they will be automatically set to the appropriate configuration values. Annotating fields with a specific
* {@link PropertyScope} can also allow values to be configured in a Rundeck Project or at the global application
* (Framework) level.
* <p/>
* A property "scope" defines how the property value is determined at runtime. When a property value is not found at a
* particular scope, the search widens to the next scope (with some caveats). Property scopes from narrowest to widest
* are: <ol> <li>Instance - the value set for a workflow step</li> <li>Project - the value set in the project's
* configuration properties</li> <li>Framework - the value set in the application configuration properties</li> </ol>
* Two special scopes "InstanceOnly" and "ProjectOnly" do not allow the search to widen, and must be present in that
* scope.
* <p/>
* The default scope for plugin properties is "InstanceOnly", but you can use any scope for property. Note: only
* properties of "Instance"/"InstanceOnly" scope will be shown for configuration in the Workflow step GUI.
* <p/>
* The plugin class is annotated with {@link Plugin} to define the service and name of this service provider plugin.
* <p/>
* The provider name of this plugin statically defined in the class. The service name makes use of {@link
* ServiceNameConstants} to provide the known Rundeck service names
* <p/>
* This plugin is also annotated with {@link PluginDescription} to provide the title (display name) and description text
* displayed by Rundeck in the GUI.
*
* @author Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
*/
@Plugin(service = ServiceNameConstants.RemoteScriptNodeStep,
name = ExampleRemoteScriptNodeStepPlugin.SERVICE_PROVIDER_NAME)
@PluginDescription(title = "Remote Script Node Step", description = "Generator")
public class ExampleRemoteScriptNodeStepPlugin implements RemoteScriptNodeStepPlugin, DescriptionBuilder.Collaborator {
/**
* Define a name used to identify your plugin. It is a good idea to use a fully qualified package-style name.
*/
public static final String SERVICE_PROVIDER_NAME
= "com.dtolabs.rundeck.plugin.example.ExampleRemoteScriptNodeStepPlugin";
/**
* Defines a string field annotated with {@link PluginProperty} so that it is shown in the Rundeck GUI for this
* plugin. The annotation can define a title (display name), description text, default string value, whether it is
* required, and specific scope for the property.
*
* @see com.dtolabs.rundeck.core.plugins.configuration.Property
*/
@PluginProperty(title = "Funky", description = "Funk name", required = true)
protected String funky;
/**
* Defines a multi-line textarea for a string property.
*/
@PluginProperty(title = "Thesis", description = "Thesis")
@TextArea
protected String thesis;
/**
* Defines a boolean field as a property
*/
@PluginProperty(title = "Jam", description = "Want jam?")
protected boolean jam;
/**
* Defines an integer field as a property, and uses a defaultValue defined as a string
*/
@PluginProperty(title = "Amount", description = "How amount?", defaultValue = "2")
protected int amount;
/**
* Defines a Long field
*/
@PluginProperty(title = "Money", description = "how money?", defaultValue = "20")
protected long money;
/**
* This field is annotated to be a "FreeSelect" property. It is a String field and has a {@link SelectValues}
* annotation which defines a set of string values that will be shown in a pop-up menu in the GUI. If "freeSelect"
* is "true", then the GUI will allow the user to enter any text for the field in addition to selecting a value. If
* freeSelect is "false" (the default), then the user will only be able to select values from the pop-up menu.
*/
@PluginProperty(title = "Fruit",
description = "your fruit",
defaultValue = "banana",
scope = PropertyScope.Instance)
@SelectValues(values = {"banana", "lemon", "orange"}, freeSelect = true)
protected String fruit;
/**
* This field is a Select property, because it uses the {@link SelectValues} annotation with freeSelect=false.
*/
@PluginProperty(title = "Cake", description = "Cake flavor")
@SelectValues(values = {"vanilla", "chocolate"}, freeSelect = false)
protected String cake;
/**
* Here is an example of a field that sets a custom scope of "Project", which indicates that it can be configured in
* the Project or Framework level configuration settings to supply the value, but will not be shown
*/
@PluginProperty(title = "Debug", description = "Turn on debug?", scope = PropertyScope.Project)
protected boolean debug;
/**
* This class overrides the method to demonstrate how to modify the description and properties before it is used by
* Rundeck. All fields which were annotated as properties can be modified/removed. In this example, the Plugin
* description is changed, and the "money" field property is altered to define a custom validator for the field.
*/
public void buildWith(final DescriptionBuilder builder) {
//override the annotated description of this plugin
builder.title("Example Remote Script Node Step");
builder.description("Demonstrates a remote script node step");
/**
* calling DescriptionBuilder.property() will replace an existing property of
* the same name.
*/
builder.property(
/**
* In this case builder.property("money") returns the existing property we
* have already defined via annotation, allowing us to modify it with the {@link PropertyBuilder}
*
*/
builder.property("money")
/**
* change the property's description
*/
.description("How much money? (1..5)")
/**
* set a custom validator for the property
*/
.validator(new PropertyValidator() {
public boolean isValid(String s) throws ValidationException {
try {
final int i = Integer.parseInt(s);
if (i <= 0 || i >= 6) {
//throw ValidationException to indicate a problem, with a reason
throw new ValidationException("Must be between 1 and 5");
}
} catch (NumberFormatException e) {
throw new ValidationException("Not a valid integer");
}
return true;
}
})
);
/**
* Here we create a wholly new property not bound to an existing instance field. The runtime
* value for this property will be included in the input configuration map when the plugin method is called.
*/
builder.property(
PropertyBuilder.builder()
.string("fakey")
.title("Fake")
.description("Extra value")
);
}
/**
* Here your plugin should create a script or command to execute on the given remote node.
* <p/>
* The {@link GeneratedScriptBuilder} provides a factory for returning the correct type.
*/
public GeneratedScript generateScript(final PluginStepContext context,
final Map<String, Object> configuration,
final INodeEntry entry) {
if (debug) {
System.err.println("DEBUG for ExampleRemoteScriptNodeStepPlugin is true");
}
if (jam) {
/**
* Returns a script to execute
*/
return GeneratedScriptBuilder.script(
"#!/bin/bash\n"
+ "echo this is node " + entry.getNodename() + "\n"
+ "echo stepnum " + context.getStepNumber() + "\n"
+ "echo step context " + context.getStepContext() + "\n"
+ "echo funky is " + funky + "\n"
+ "echo fruit is " + fruit + "\n"
+ "echo amount is " + amount + "\n"
+ "echo money is " + money + "\n"
+ "echo cake is " + cake + "\n"
+ "echo extra: " + configuration + "\n"
+ "echo thesis: '" + thesis.replaceAll("'", "'\"'\"'") + "'\n"
,
null
);
} else {
/**
* Returns a command to execute.
*/
return GeneratedScriptBuilder.command("echo",
context.getStepNumber() + " " + context.getStepContext() + " " +
"Hi funky is" +
" (" + funky + ")" +
" jam is" + jam
);
}
}
}
| 47.502041
| 126
| 0.628458
|
1ad0f26239383af0ed55eb16c60f90e20ede7bfd
| 453
|
package g0901_1000.s0984_string_without_aaa_or_bbb;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void strWithout3a3b() {
assertThat(new Solution().strWithout3a3b(1, 2), equalTo("bba"));
}
@Test
void strWithout3a3b2() {
assertThat(new Solution().strWithout3a3b(4, 1), equalTo("aabaa"));
}
}
| 23.842105
| 74
| 0.710817
|
baf94aa61f2ae098106bf42749b6513cb85b3707
| 4,182
|
package pl.lodz.p.it.inz.sgruda.multiStore.entities.mop;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import pl.lodz.p.it.inz.sgruda.multiStore.utils.enums.ProductType;
import pl.lodz.p.it.inz.sgruda.multiStore.utils.interfaces.VersionGetter;
import javax.persistence.*;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
@ToString
@Getter
@Setter
@Entity
@Table(name = "product", schema = "public",
uniqueConstraints = {
@UniqueConstraint(columnNames = {"title"})
})
@TableGenerator(name = "ProductIdGen", table = "id_generator", schema = "public", pkColumnName = "class_name",
valueColumnName = "id_range", pkColumnValue = "product")
public class ProductEntity implements Serializable, VersionGetter {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "ProductIdGen")
private long id;
@Basic(optional = false)
@NotNull(message = "validation.notnull")
@Size(min = 1, max = 64, message = "validation.size")
@Pattern(regexp = "[0-9a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ?!:., ]+", message = "validation.pattern")
@Column(name = "title", nullable = false, unique = true, length = 32)
private String title;
@Basic(optional = false)
@NotNull(message = "validation.notnull")
@Size(min = 1, max = 512, message = "validation.size")
@Pattern(regexp = "[0-9a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ?!:., ]+", message = "validation.pattern")
@Column(name = "description", nullable = false, length = 512)
private String description;
@Digits(integer = 7, fraction = 0, message = "validation.digits")
@Basic(optional = false)
@NotNull(message = "validation.notnull")
@Column(name = "in_store", nullable = false)
private int inStore;
@Digits(integer = 7, fraction = 2, message = "validation.digits")
@Basic(optional = false)
@NotNull(message = "validation.notnull")
@Column(name = "price", nullable = false)
private double price;
@Basic(optional = false)
@NotNull(message = "validation.notnull")
@Enumerated(EnumType.STRING)
private ProductType type;
@NotNull(message = "validation.notnull")
@JoinColumn(name = "category_id", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private CategoryEntity categoryEntity;
@Basic(optional = false)
@NotNull(message = "validation.notnull")
@Column(name = "active", nullable = false)
private boolean active;
@Version
@Basic
@Column(name = "version", nullable = false)
private long version;
public ProductEntity() {
}
public ProductEntity(@NotNull(message = "validation.notnull") @Size(min = 1, max = 32, message = "validation.size")
@Pattern(regexp = "[a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+", message = "validation.pattern")
String title,
@NotNull(message = "validation.notnull") @Size(min = 1, max = 512, message = "validation.size")
String description,
@Digits(integer = 7, fraction = 0, message = "validation.digits") @NotNull(message = "validation.notnull")
int inStore,
@Digits(integer = 7, fraction = 2, message = "validation.digits") @NotNull(message = "validation.notnull")
double price,
@NotNull(message = "validation.notnull")
ProductType type) {
this.title = title;
this.description = description;
this.inStore = inStore;
this.price = price;
this.type = type;
this.active = true;
}
}
| 41.82
| 135
| 0.594213
|
cc65476623725a4bcb5faf04c26b09688580ebac
| 73,382
|
package top.atstudy.advistory.advistory.dao.dto;
import top.atstudy.component.enums.EnumAdvistoryCategory;
import top.atstudy.component.enums.EnumAdvistoryLevel;
import top.atstudy.component.enums.EnumAdvistoryType;
import top.atstudy.component.enums.EnumDeleted;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class AdvistoryInfoDTOExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
protected Integer offset;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
protected Integer rows;
public AdvistoryInfoDTOExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
rows = null;
offset = null;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public void setOffset(Integer offset) {
this.offset = offset;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public Integer getOffset() {
return this.offset;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public void setRows(Integer rows) {
this.rows = rows;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public Integer getRows() {
return this.rows;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public AdvistoryInfoDTOExample limit(Integer rows) {
this.rows = rows;
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public AdvistoryInfoDTOExample limit(Integer offset, Integer rows) {
this.offset = offset;
this.rows = rows;
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advistory_info
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public AdvistoryInfoDTOExample page(Integer page, Integer pageSize) {
this.offset = page * pageSize;
this.rows = pageSize;
return this;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andAdvistoryIdIsNull() {
addCriterion("advistory_id is null");
return (Criteria) this;
}
public Criteria andAdvistoryIdIsNotNull() {
addCriterion("advistory_id is not null");
return (Criteria) this;
}
public Criteria andAdvistoryIdEqualTo(Long value) {
addCriterion("advistory_id =", value, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdNotEqualTo(Long value) {
addCriterion("advistory_id <>", value, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdGreaterThan(Long value) {
addCriterion("advistory_id >", value, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdGreaterThanOrEqualTo(Long value) {
addCriterion("advistory_id >=", value, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdLessThan(Long value) {
addCriterion("advistory_id <", value, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdLessThanOrEqualTo(Long value) {
addCriterion("advistory_id <=", value, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdIn(List<Long> values) {
addCriterion("advistory_id in", values, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdNotIn(List<Long> values) {
addCriterion("advistory_id not in", values, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdBetween(Long value1, Long value2) {
addCriterion("advistory_id between", value1, value2, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryIdNotBetween(Long value1, Long value2) {
addCriterion("advistory_id not between", value1, value2, "advistoryId");
return (Criteria) this;
}
public Criteria andAdvistoryLevelIsNull() {
addCriterion("advistory_level is null");
return (Criteria) this;
}
public Criteria andAdvistoryLevelIsNotNull() {
addCriterion("advistory_level is not null");
return (Criteria) this;
}
public Criteria andAdvistoryLevelEqualTo(EnumAdvistoryLevel value) {
addCriterion("advistory_level =", value, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelNotEqualTo(EnumAdvistoryLevel value) {
addCriterion("advistory_level <>", value, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelGreaterThan(EnumAdvistoryLevel value) {
addCriterion("advistory_level >", value, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelGreaterThanOrEqualTo(EnumAdvistoryLevel value) {
addCriterion("advistory_level >=", value, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelLessThan(EnumAdvistoryLevel value) {
addCriterion("advistory_level <", value, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelLessThanOrEqualTo(EnumAdvistoryLevel value) {
addCriterion("advistory_level <=", value, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelLike(EnumAdvistoryLevel value) {
addCriterion("advistory_level like", value, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelNotLike(EnumAdvistoryLevel value) {
addCriterion("advistory_level not like", value, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelIn(List<EnumAdvistoryLevel> values) {
addCriterion("advistory_level in", values, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelNotIn(List<EnumAdvistoryLevel> values) {
addCriterion("advistory_level not in", values, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelBetween(EnumAdvistoryLevel value1, EnumAdvistoryLevel value2) {
addCriterion("advistory_level between", value1, value2, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryLevelNotBetween(EnumAdvistoryLevel value1, EnumAdvistoryLevel value2) {
addCriterion("advistory_level not between", value1, value2, "advistoryLevel");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryIsNull() {
addCriterion("advistory_category is null");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryIsNotNull() {
addCriterion("advistory_category is not null");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryEqualTo(EnumAdvistoryCategory value) {
addCriterion("advistory_category =", value, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryNotEqualTo(EnumAdvistoryCategory value) {
addCriterion("advistory_category <>", value, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryGreaterThan(EnumAdvistoryCategory value) {
addCriterion("advistory_category >", value, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryGreaterThanOrEqualTo(EnumAdvistoryCategory value) {
addCriterion("advistory_category >=", value, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryLessThan(EnumAdvistoryCategory value) {
addCriterion("advistory_category <", value, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryLessThanOrEqualTo(EnumAdvistoryCategory value) {
addCriterion("advistory_category <=", value, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryLike(EnumAdvistoryCategory value) {
addCriterion("advistory_category like", value, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryNotLike(EnumAdvistoryCategory value) {
addCriterion("advistory_category not like", value, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryIn(List<EnumAdvistoryCategory> values) {
addCriterion("advistory_category in", values, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryNotIn(List<EnumAdvistoryCategory> values) {
addCriterion("advistory_category not in", values, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryBetween(EnumAdvistoryCategory value1, EnumAdvistoryCategory value2) {
addCriterion("advistory_category between", value1, value2, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryCategoryNotBetween(EnumAdvistoryCategory value1, EnumAdvistoryCategory value2) {
addCriterion("advistory_category not between", value1, value2, "advistoryCategory");
return (Criteria) this;
}
public Criteria andAdvistoryTypeIsNull() {
addCriterion("advistory_type is null");
return (Criteria) this;
}
public Criteria andAdvistoryTypeIsNotNull() {
addCriterion("advistory_type is not null");
return (Criteria) this;
}
public Criteria andAdvistoryTypeEqualTo(EnumAdvistoryType value) {
addCriterion("advistory_type =", value, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeNotEqualTo(EnumAdvistoryType value) {
addCriterion("advistory_type <>", value, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeGreaterThan(EnumAdvistoryType value) {
addCriterion("advistory_type >", value, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeGreaterThanOrEqualTo(EnumAdvistoryType value) {
addCriterion("advistory_type >=", value, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeLessThan(EnumAdvistoryType value) {
addCriterion("advistory_type <", value, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeLessThanOrEqualTo(EnumAdvistoryType value) {
addCriterion("advistory_type <=", value, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeLike(EnumAdvistoryType value) {
addCriterion("advistory_type like", value, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeNotLike(EnumAdvistoryType value) {
addCriterion("advistory_type not like", value, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeIn(List<EnumAdvistoryType> values) {
addCriterion("advistory_type in", values, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeNotIn(List<EnumAdvistoryType> values) {
addCriterion("advistory_type not in", values, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeBetween(EnumAdvistoryType value1, EnumAdvistoryType value2) {
addCriterion("advistory_type between", value1, value2, "advistoryType");
return (Criteria) this;
}
public Criteria andAdvistoryTypeNotBetween(EnumAdvistoryType value1, EnumAdvistoryType value2) {
addCriterion("advistory_type not between", value1, value2, "advistoryType");
return (Criteria) this;
}
public Criteria andTitleIsNull() {
addCriterion("title is null");
return (Criteria) this;
}
public Criteria andTitleIsNotNull() {
addCriterion("title is not null");
return (Criteria) this;
}
public Criteria andTitleEqualTo(String value) {
addCriterion("title =", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotEqualTo(String value) {
addCriterion("title <>", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThan(String value) {
addCriterion("title >", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThanOrEqualTo(String value) {
addCriterion("title >=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThan(String value) {
addCriterion("title <", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThanOrEqualTo(String value) {
addCriterion("title <=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLike(String value) {
addCriterion("title like", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotLike(String value) {
addCriterion("title not like", value, "title");
return (Criteria) this;
}
public Criteria andTitleIn(List<String> values) {
addCriterion("title in", values, "title");
return (Criteria) this;
}
public Criteria andTitleNotIn(List<String> values) {
addCriterion("title not in", values, "title");
return (Criteria) this;
}
public Criteria andTitleBetween(String value1, String value2) {
addCriterion("title between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andTitleNotBetween(String value1, String value2) {
addCriterion("title not between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andDigestIsNull() {
addCriterion("digest is null");
return (Criteria) this;
}
public Criteria andDigestIsNotNull() {
addCriterion("digest is not null");
return (Criteria) this;
}
public Criteria andDigestEqualTo(String value) {
addCriterion("digest =", value, "digest");
return (Criteria) this;
}
public Criteria andDigestNotEqualTo(String value) {
addCriterion("digest <>", value, "digest");
return (Criteria) this;
}
public Criteria andDigestGreaterThan(String value) {
addCriterion("digest >", value, "digest");
return (Criteria) this;
}
public Criteria andDigestGreaterThanOrEqualTo(String value) {
addCriterion("digest >=", value, "digest");
return (Criteria) this;
}
public Criteria andDigestLessThan(String value) {
addCriterion("digest <", value, "digest");
return (Criteria) this;
}
public Criteria andDigestLessThanOrEqualTo(String value) {
addCriterion("digest <=", value, "digest");
return (Criteria) this;
}
public Criteria andDigestLike(String value) {
addCriterion("digest like", value, "digest");
return (Criteria) this;
}
public Criteria andDigestNotLike(String value) {
addCriterion("digest not like", value, "digest");
return (Criteria) this;
}
public Criteria andDigestIn(List<String> values) {
addCriterion("digest in", values, "digest");
return (Criteria) this;
}
public Criteria andDigestNotIn(List<String> values) {
addCriterion("digest not in", values, "digest");
return (Criteria) this;
}
public Criteria andDigestBetween(String value1, String value2) {
addCriterion("digest between", value1, value2, "digest");
return (Criteria) this;
}
public Criteria andDigestNotBetween(String value1, String value2) {
addCriterion("digest not between", value1, value2, "digest");
return (Criteria) this;
}
public Criteria andFavoriteNumberIsNull() {
addCriterion("favorite_number is null");
return (Criteria) this;
}
public Criteria andFavoriteNumberIsNotNull() {
addCriterion("favorite_number is not null");
return (Criteria) this;
}
public Criteria andFavoriteNumberEqualTo(Long value) {
addCriterion("favorite_number =", value, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberNotEqualTo(Long value) {
addCriterion("favorite_number <>", value, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberGreaterThan(Long value) {
addCriterion("favorite_number >", value, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberGreaterThanOrEqualTo(Long value) {
addCriterion("favorite_number >=", value, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberLessThan(Long value) {
addCriterion("favorite_number <", value, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberLessThanOrEqualTo(Long value) {
addCriterion("favorite_number <=", value, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberIn(List<Long> values) {
addCriterion("favorite_number in", values, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberNotIn(List<Long> values) {
addCriterion("favorite_number not in", values, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberBetween(Long value1, Long value2) {
addCriterion("favorite_number between", value1, value2, "favoriteNumber");
return (Criteria) this;
}
public Criteria andFavoriteNumberNotBetween(Long value1, Long value2) {
addCriterion("favorite_number not between", value1, value2, "favoriteNumber");
return (Criteria) this;
}
public Criteria andReadNumberIsNull() {
addCriterion("read_number is null");
return (Criteria) this;
}
public Criteria andReadNumberIsNotNull() {
addCriterion("read_number is not null");
return (Criteria) this;
}
public Criteria andReadNumberEqualTo(Long value) {
addCriterion("read_number =", value, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberNotEqualTo(Long value) {
addCriterion("read_number <>", value, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberGreaterThan(Long value) {
addCriterion("read_number >", value, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberGreaterThanOrEqualTo(Long value) {
addCriterion("read_number >=", value, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberLessThan(Long value) {
addCriterion("read_number <", value, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberLessThanOrEqualTo(Long value) {
addCriterion("read_number <=", value, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberIn(List<Long> values) {
addCriterion("read_number in", values, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberNotIn(List<Long> values) {
addCriterion("read_number not in", values, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberBetween(Long value1, Long value2) {
addCriterion("read_number between", value1, value2, "readNumber");
return (Criteria) this;
}
public Criteria andReadNumberNotBetween(Long value1, Long value2) {
addCriterion("read_number not between", value1, value2, "readNumber");
return (Criteria) this;
}
public Criteria andCoverImageIsNull() {
addCriterion("cover_image is null");
return (Criteria) this;
}
public Criteria andCoverImageIsNotNull() {
addCriterion("cover_image is not null");
return (Criteria) this;
}
public Criteria andCoverImageEqualTo(String value) {
addCriterion("cover_image =", value, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageNotEqualTo(String value) {
addCriterion("cover_image <>", value, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageGreaterThan(String value) {
addCriterion("cover_image >", value, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageGreaterThanOrEqualTo(String value) {
addCriterion("cover_image >=", value, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageLessThan(String value) {
addCriterion("cover_image <", value, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageLessThanOrEqualTo(String value) {
addCriterion("cover_image <=", value, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageLike(String value) {
addCriterion("cover_image like", value, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageNotLike(String value) {
addCriterion("cover_image not like", value, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageIn(List<String> values) {
addCriterion("cover_image in", values, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageNotIn(List<String> values) {
addCriterion("cover_image not in", values, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageBetween(String value1, String value2) {
addCriterion("cover_image between", value1, value2, "coverImage");
return (Criteria) this;
}
public Criteria andCoverImageNotBetween(String value1, String value2) {
addCriterion("cover_image not between", value1, value2, "coverImage");
return (Criteria) this;
}
public Criteria andRecommendStatusIsNull() {
addCriterion("recommend_status is null");
return (Criteria) this;
}
public Criteria andRecommendStatusIsNotNull() {
addCriterion("recommend_status is not null");
return (Criteria) this;
}
public Criteria andRecommendStatusEqualTo(Boolean value) {
addCriterion("recommend_status =", value, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusNotEqualTo(Boolean value) {
addCriterion("recommend_status <>", value, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusGreaterThan(Boolean value) {
addCriterion("recommend_status >", value, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusGreaterThanOrEqualTo(Boolean value) {
addCriterion("recommend_status >=", value, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusLessThan(Boolean value) {
addCriterion("recommend_status <", value, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusLessThanOrEqualTo(Boolean value) {
addCriterion("recommend_status <=", value, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusIn(List<Boolean> values) {
addCriterion("recommend_status in", values, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusNotIn(List<Boolean> values) {
addCriterion("recommend_status not in", values, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusBetween(Boolean value1, Boolean value2) {
addCriterion("recommend_status between", value1, value2, "recommendStatus");
return (Criteria) this;
}
public Criteria andRecommendStatusNotBetween(Boolean value1, Boolean value2) {
addCriterion("recommend_status not between", value1, value2, "recommendStatus");
return (Criteria) this;
}
public Criteria andStickStatusIsNull() {
addCriterion("stick_status is null");
return (Criteria) this;
}
public Criteria andStickStatusIsNotNull() {
addCriterion("stick_status is not null");
return (Criteria) this;
}
public Criteria andStickStatusEqualTo(Boolean value) {
addCriterion("stick_status =", value, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusNotEqualTo(Boolean value) {
addCriterion("stick_status <>", value, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusGreaterThan(Boolean value) {
addCriterion("stick_status >", value, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusGreaterThanOrEqualTo(Boolean value) {
addCriterion("stick_status >=", value, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusLessThan(Boolean value) {
addCriterion("stick_status <", value, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusLessThanOrEqualTo(Boolean value) {
addCriterion("stick_status <=", value, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusIn(List<Boolean> values) {
addCriterion("stick_status in", values, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusNotIn(List<Boolean> values) {
addCriterion("stick_status not in", values, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusBetween(Boolean value1, Boolean value2) {
addCriterion("stick_status between", value1, value2, "stickStatus");
return (Criteria) this;
}
public Criteria andStickStatusNotBetween(Boolean value1, Boolean value2) {
addCriterion("stick_status not between", value1, value2, "stickStatus");
return (Criteria) this;
}
public Criteria andAdStatusIsNull() {
addCriterion("ad_status is null");
return (Criteria) this;
}
public Criteria andAdStatusIsNotNull() {
addCriterion("ad_status is not null");
return (Criteria) this;
}
public Criteria andAdStatusEqualTo(Boolean value) {
addCriterion("ad_status =", value, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusNotEqualTo(Boolean value) {
addCriterion("ad_status <>", value, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusGreaterThan(Boolean value) {
addCriterion("ad_status >", value, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusGreaterThanOrEqualTo(Boolean value) {
addCriterion("ad_status >=", value, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusLessThan(Boolean value) {
addCriterion("ad_status <", value, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusLessThanOrEqualTo(Boolean value) {
addCriterion("ad_status <=", value, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusIn(List<Boolean> values) {
addCriterion("ad_status in", values, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusNotIn(List<Boolean> values) {
addCriterion("ad_status not in", values, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusBetween(Boolean value1, Boolean value2) {
addCriterion("ad_status between", value1, value2, "adStatus");
return (Criteria) this;
}
public Criteria andAdStatusNotBetween(Boolean value1, Boolean value2) {
addCriterion("ad_status not between", value1, value2, "adStatus");
return (Criteria) this;
}
public Criteria andLinkIsNull() {
addCriterion("link is null");
return (Criteria) this;
}
public Criteria andLinkIsNotNull() {
addCriterion("link is not null");
return (Criteria) this;
}
public Criteria andLinkEqualTo(String value) {
addCriterion("link =", value, "link");
return (Criteria) this;
}
public Criteria andLinkNotEqualTo(String value) {
addCriterion("link <>", value, "link");
return (Criteria) this;
}
public Criteria andLinkGreaterThan(String value) {
addCriterion("link >", value, "link");
return (Criteria) this;
}
public Criteria andLinkGreaterThanOrEqualTo(String value) {
addCriterion("link >=", value, "link");
return (Criteria) this;
}
public Criteria andLinkLessThan(String value) {
addCriterion("link <", value, "link");
return (Criteria) this;
}
public Criteria andLinkLessThanOrEqualTo(String value) {
addCriterion("link <=", value, "link");
return (Criteria) this;
}
public Criteria andLinkLike(String value) {
addCriterion("link like", value, "link");
return (Criteria) this;
}
public Criteria andLinkNotLike(String value) {
addCriterion("link not like", value, "link");
return (Criteria) this;
}
public Criteria andLinkIn(List<String> values) {
addCriterion("link in", values, "link");
return (Criteria) this;
}
public Criteria andLinkNotIn(List<String> values) {
addCriterion("link not in", values, "link");
return (Criteria) this;
}
public Criteria andLinkBetween(String value1, String value2) {
addCriterion("link between", value1, value2, "link");
return (Criteria) this;
}
public Criteria andLinkNotBetween(String value1, String value2) {
addCriterion("link not between", value1, value2, "link");
return (Criteria) this;
}
public Criteria andPublishUserIdIsNull() {
addCriterion("publish_user_id is null");
return (Criteria) this;
}
public Criteria andPublishUserIdIsNotNull() {
addCriterion("publish_user_id is not null");
return (Criteria) this;
}
public Criteria andPublishUserIdEqualTo(Long value) {
addCriterion("publish_user_id =", value, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdNotEqualTo(Long value) {
addCriterion("publish_user_id <>", value, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdGreaterThan(Long value) {
addCriterion("publish_user_id >", value, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdGreaterThanOrEqualTo(Long value) {
addCriterion("publish_user_id >=", value, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdLessThan(Long value) {
addCriterion("publish_user_id <", value, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdLessThanOrEqualTo(Long value) {
addCriterion("publish_user_id <=", value, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdIn(List<Long> values) {
addCriterion("publish_user_id in", values, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdNotIn(List<Long> values) {
addCriterion("publish_user_id not in", values, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdBetween(Long value1, Long value2) {
addCriterion("publish_user_id between", value1, value2, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserIdNotBetween(Long value1, Long value2) {
addCriterion("publish_user_id not between", value1, value2, "publishUserId");
return (Criteria) this;
}
public Criteria andPublishUserNameIsNull() {
addCriterion("publish_user_name is null");
return (Criteria) this;
}
public Criteria andPublishUserNameIsNotNull() {
addCriterion("publish_user_name is not null");
return (Criteria) this;
}
public Criteria andPublishUserNameEqualTo(String value) {
addCriterion("publish_user_name =", value, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameNotEqualTo(String value) {
addCriterion("publish_user_name <>", value, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameGreaterThan(String value) {
addCriterion("publish_user_name >", value, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameGreaterThanOrEqualTo(String value) {
addCriterion("publish_user_name >=", value, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameLessThan(String value) {
addCriterion("publish_user_name <", value, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameLessThanOrEqualTo(String value) {
addCriterion("publish_user_name <=", value, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameLike(String value) {
addCriterion("publish_user_name like", value, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameNotLike(String value) {
addCriterion("publish_user_name not like", value, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameIn(List<String> values) {
addCriterion("publish_user_name in", values, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameNotIn(List<String> values) {
addCriterion("publish_user_name not in", values, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameBetween(String value1, String value2) {
addCriterion("publish_user_name between", value1, value2, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishUserNameNotBetween(String value1, String value2) {
addCriterion("publish_user_name not between", value1, value2, "publishUserName");
return (Criteria) this;
}
public Criteria andPublishOperationTimeIsNull() {
addCriterion("publish_operation_time is null");
return (Criteria) this;
}
public Criteria andPublishOperationTimeIsNotNull() {
addCriterion("publish_operation_time is not null");
return (Criteria) this;
}
public Criteria andPublishOperationTimeEqualTo(Date value) {
addCriterion("publish_operation_time =", value, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeNotEqualTo(Date value) {
addCriterion("publish_operation_time <>", value, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeGreaterThan(Date value) {
addCriterion("publish_operation_time >", value, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeGreaterThanOrEqualTo(Date value) {
addCriterion("publish_operation_time >=", value, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeLessThan(Date value) {
addCriterion("publish_operation_time <", value, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeLessThanOrEqualTo(Date value) {
addCriterion("publish_operation_time <=", value, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeIn(List<Date> values) {
addCriterion("publish_operation_time in", values, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeNotIn(List<Date> values) {
addCriterion("publish_operation_time not in", values, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeBetween(Date value1, Date value2) {
addCriterion("publish_operation_time between", value1, value2, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishOperationTimeNotBetween(Date value1, Date value2) {
addCriterion("publish_operation_time not between", value1, value2, "publishOperationTime");
return (Criteria) this;
}
public Criteria andPublishTimeIsNull() {
addCriterion("publish_time is null");
return (Criteria) this;
}
public Criteria andPublishTimeIsNotNull() {
addCriterion("publish_time is not null");
return (Criteria) this;
}
public Criteria andPublishTimeEqualTo(Date value) {
addCriterion("publish_time =", value, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeNotEqualTo(Date value) {
addCriterion("publish_time <>", value, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeGreaterThan(Date value) {
addCriterion("publish_time >", value, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeGreaterThanOrEqualTo(Date value) {
addCriterion("publish_time >=", value, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeLessThan(Date value) {
addCriterion("publish_time <", value, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeLessThanOrEqualTo(Date value) {
addCriterion("publish_time <=", value, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeIn(List<Date> values) {
addCriterion("publish_time in", values, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeNotIn(List<Date> values) {
addCriterion("publish_time not in", values, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeBetween(Date value1, Date value2) {
addCriterion("publish_time between", value1, value2, "publishTime");
return (Criteria) this;
}
public Criteria andPublishTimeNotBetween(Date value1, Date value2) {
addCriterion("publish_time not between", value1, value2, "publishTime");
return (Criteria) this;
}
public Criteria andAuthorIsNull() {
addCriterion("author is null");
return (Criteria) this;
}
public Criteria andAuthorIsNotNull() {
addCriterion("author is not null");
return (Criteria) this;
}
public Criteria andAuthorEqualTo(String value) {
addCriterion("author =", value, "author");
return (Criteria) this;
}
public Criteria andAuthorNotEqualTo(String value) {
addCriterion("author <>", value, "author");
return (Criteria) this;
}
public Criteria andAuthorGreaterThan(String value) {
addCriterion("author >", value, "author");
return (Criteria) this;
}
public Criteria andAuthorGreaterThanOrEqualTo(String value) {
addCriterion("author >=", value, "author");
return (Criteria) this;
}
public Criteria andAuthorLessThan(String value) {
addCriterion("author <", value, "author");
return (Criteria) this;
}
public Criteria andAuthorLessThanOrEqualTo(String value) {
addCriterion("author <=", value, "author");
return (Criteria) this;
}
public Criteria andAuthorLike(String value) {
addCriterion("author like", value, "author");
return (Criteria) this;
}
public Criteria andAuthorNotLike(String value) {
addCriterion("author not like", value, "author");
return (Criteria) this;
}
public Criteria andAuthorIn(List<String> values) {
addCriterion("author in", values, "author");
return (Criteria) this;
}
public Criteria andAuthorNotIn(List<String> values) {
addCriterion("author not in", values, "author");
return (Criteria) this;
}
public Criteria andAuthorBetween(String value1, String value2) {
addCriterion("author between", value1, value2, "author");
return (Criteria) this;
}
public Criteria andAuthorNotBetween(String value1, String value2) {
addCriterion("author not between", value1, value2, "author");
return (Criteria) this;
}
public Criteria andDisplayOrderIsNull() {
addCriterion("display_order is null");
return (Criteria) this;
}
public Criteria andDisplayOrderIsNotNull() {
addCriterion("display_order is not null");
return (Criteria) this;
}
public Criteria andDisplayOrderEqualTo(Integer value) {
addCriterion("display_order =", value, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderNotEqualTo(Integer value) {
addCriterion("display_order <>", value, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderGreaterThan(Integer value) {
addCriterion("display_order >", value, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderGreaterThanOrEqualTo(Integer value) {
addCriterion("display_order >=", value, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderLessThan(Integer value) {
addCriterion("display_order <", value, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderLessThanOrEqualTo(Integer value) {
addCriterion("display_order <=", value, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderIn(List<Integer> values) {
addCriterion("display_order in", values, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderNotIn(List<Integer> values) {
addCriterion("display_order not in", values, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderBetween(Integer value1, Integer value2) {
addCriterion("display_order between", value1, value2, "displayOrder");
return (Criteria) this;
}
public Criteria andDisplayOrderNotBetween(Integer value1, Integer value2) {
addCriterion("display_order not between", value1, value2, "displayOrder");
return (Criteria) this;
}
public Criteria andVersionIsNull() {
addCriterion("version is null");
return (Criteria) this;
}
public Criteria andVersionIsNotNull() {
addCriterion("version is not null");
return (Criteria) this;
}
public Criteria andVersionEqualTo(Integer value) {
addCriterion("version =", value, "version");
return (Criteria) this;
}
public Criteria andVersionNotEqualTo(Integer value) {
addCriterion("version <>", value, "version");
return (Criteria) this;
}
public Criteria andVersionGreaterThan(Integer value) {
addCriterion("version >", value, "version");
return (Criteria) this;
}
public Criteria andVersionGreaterThanOrEqualTo(Integer value) {
addCriterion("version >=", value, "version");
return (Criteria) this;
}
public Criteria andVersionLessThan(Integer value) {
addCriterion("version <", value, "version");
return (Criteria) this;
}
public Criteria andVersionLessThanOrEqualTo(Integer value) {
addCriterion("version <=", value, "version");
return (Criteria) this;
}
public Criteria andVersionIn(List<Integer> values) {
addCriterion("version in", values, "version");
return (Criteria) this;
}
public Criteria andVersionNotIn(List<Integer> values) {
addCriterion("version not in", values, "version");
return (Criteria) this;
}
public Criteria andVersionBetween(Integer value1, Integer value2) {
addCriterion("version between", value1, value2, "version");
return (Criteria) this;
}
public Criteria andVersionNotBetween(Integer value1, Integer value2) {
addCriterion("version not between", value1, value2, "version");
return (Criteria) this;
}
public Criteria andDeletedIsNull() {
addCriterion("deleted is null");
return (Criteria) this;
}
public Criteria andDeletedIsNotNull() {
addCriterion("deleted is not null");
return (Criteria) this;
}
public Criteria andDeletedEqualTo(EnumDeleted value) {
addCriterion("deleted =", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotEqualTo(EnumDeleted value) {
addCriterion("deleted <>", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedGreaterThan(EnumDeleted value) {
addCriterion("deleted >", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedGreaterThanOrEqualTo(EnumDeleted value) {
addCriterion("deleted >=", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedLessThan(EnumDeleted value) {
addCriterion("deleted <", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedLessThanOrEqualTo(EnumDeleted value) {
addCriterion("deleted <=", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedIn(List<EnumDeleted> values) {
addCriterion("deleted in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotIn(List<EnumDeleted> values) {
addCriterion("deleted not in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedBetween(EnumDeleted value1, EnumDeleted value2) {
addCriterion("deleted between", value1, value2, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotBetween(EnumDeleted value1, EnumDeleted value2) {
addCriterion("deleted not between", value1, value2, "deleted");
return (Criteria) this;
}
public Criteria andCreateUserIdIsNull() {
addCriterion("create_user_id is null");
return (Criteria) this;
}
public Criteria andCreateUserIdIsNotNull() {
addCriterion("create_user_id is not null");
return (Criteria) this;
}
public Criteria andCreateUserIdEqualTo(Long value) {
addCriterion("create_user_id =", value, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdNotEqualTo(Long value) {
addCriterion("create_user_id <>", value, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdGreaterThan(Long value) {
addCriterion("create_user_id >", value, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdGreaterThanOrEqualTo(Long value) {
addCriterion("create_user_id >=", value, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdLessThan(Long value) {
addCriterion("create_user_id <", value, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdLessThanOrEqualTo(Long value) {
addCriterion("create_user_id <=", value, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdIn(List<Long> values) {
addCriterion("create_user_id in", values, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdNotIn(List<Long> values) {
addCriterion("create_user_id not in", values, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdBetween(Long value1, Long value2) {
addCriterion("create_user_id between", value1, value2, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserIdNotBetween(Long value1, Long value2) {
addCriterion("create_user_id not between", value1, value2, "createUserId");
return (Criteria) this;
}
public Criteria andCreateUserNameIsNull() {
addCriterion("create_user_name is null");
return (Criteria) this;
}
public Criteria andCreateUserNameIsNotNull() {
addCriterion("create_user_name is not null");
return (Criteria) this;
}
public Criteria andCreateUserNameEqualTo(String value) {
addCriterion("create_user_name =", value, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameNotEqualTo(String value) {
addCriterion("create_user_name <>", value, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameGreaterThan(String value) {
addCriterion("create_user_name >", value, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameGreaterThanOrEqualTo(String value) {
addCriterion("create_user_name >=", value, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameLessThan(String value) {
addCriterion("create_user_name <", value, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameLessThanOrEqualTo(String value) {
addCriterion("create_user_name <=", value, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameLike(String value) {
addCriterion("create_user_name like", value, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameNotLike(String value) {
addCriterion("create_user_name not like", value, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameIn(List<String> values) {
addCriterion("create_user_name in", values, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameNotIn(List<String> values) {
addCriterion("create_user_name not in", values, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameBetween(String value1, String value2) {
addCriterion("create_user_name between", value1, value2, "createUserName");
return (Criteria) this;
}
public Criteria andCreateUserNameNotBetween(String value1, String value2) {
addCriterion("create_user_name not between", value1, value2, "createUserName");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andUpdateUserIdIsNull() {
addCriterion("update_user_id is null");
return (Criteria) this;
}
public Criteria andUpdateUserIdIsNotNull() {
addCriterion("update_user_id is not null");
return (Criteria) this;
}
public Criteria andUpdateUserIdEqualTo(Long value) {
addCriterion("update_user_id =", value, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdNotEqualTo(Long value) {
addCriterion("update_user_id <>", value, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdGreaterThan(Long value) {
addCriterion("update_user_id >", value, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdGreaterThanOrEqualTo(Long value) {
addCriterion("update_user_id >=", value, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdLessThan(Long value) {
addCriterion("update_user_id <", value, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdLessThanOrEqualTo(Long value) {
addCriterion("update_user_id <=", value, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdIn(List<Long> values) {
addCriterion("update_user_id in", values, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdNotIn(List<Long> values) {
addCriterion("update_user_id not in", values, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdBetween(Long value1, Long value2) {
addCriterion("update_user_id between", value1, value2, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserIdNotBetween(Long value1, Long value2) {
addCriterion("update_user_id not between", value1, value2, "updateUserId");
return (Criteria) this;
}
public Criteria andUpdateUserNameIsNull() {
addCriterion("update_user_name is null");
return (Criteria) this;
}
public Criteria andUpdateUserNameIsNotNull() {
addCriterion("update_user_name is not null");
return (Criteria) this;
}
public Criteria andUpdateUserNameEqualTo(String value) {
addCriterion("update_user_name =", value, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameNotEqualTo(String value) {
addCriterion("update_user_name <>", value, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameGreaterThan(String value) {
addCriterion("update_user_name >", value, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameGreaterThanOrEqualTo(String value) {
addCriterion("update_user_name >=", value, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameLessThan(String value) {
addCriterion("update_user_name <", value, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameLessThanOrEqualTo(String value) {
addCriterion("update_user_name <=", value, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameLike(String value) {
addCriterion("update_user_name like", value, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameNotLike(String value) {
addCriterion("update_user_name not like", value, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameIn(List<String> values) {
addCriterion("update_user_name in", values, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameNotIn(List<String> values) {
addCriterion("update_user_name not in", values, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameBetween(String value1, String value2) {
addCriterion("update_user_name between", value1, value2, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateUserNameNotBetween(String value1, String value2) {
addCriterion("update_user_name not between", value1, value2, "updateUserName");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Date value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Date value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Date value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Date value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Date> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Date> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Date value1, Date value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andLastUpdateIsNull() {
addCriterion("last_update is null");
return (Criteria) this;
}
public Criteria andLastUpdateIsNotNull() {
addCriterion("last_update is not null");
return (Criteria) this;
}
public Criteria andLastUpdateEqualTo(Date value) {
addCriterion("last_update =", value, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateNotEqualTo(Date value) {
addCriterion("last_update <>", value, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateGreaterThan(Date value) {
addCriterion("last_update >", value, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateGreaterThanOrEqualTo(Date value) {
addCriterion("last_update >=", value, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateLessThan(Date value) {
addCriterion("last_update <", value, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateLessThanOrEqualTo(Date value) {
addCriterion("last_update <=", value, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateIn(List<Date> values) {
addCriterion("last_update in", values, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateNotIn(List<Date> values) {
addCriterion("last_update not in", values, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateBetween(Date value1, Date value2) {
addCriterion("last_update between", value1, value2, "lastUpdate");
return (Criteria) this;
}
public Criteria andLastUpdateNotBetween(Date value1, Date value2) {
addCriterion("last_update not between", value1, value2, "lastUpdate");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
| 34.993801
| 116
| 0.608187
|
cfa2b91735430c83a0e9f53242d715e9a148d94b
| 1,021
|
package com.crashlytics.android.answers;
import java.util.HashSet;
import java.util.Set;
class SamplingEventFilter
implements EventFilter
{
static final Set<SessionEvent.Type> EVENTS_TYPE_TO_SAMPLE = new HashSet() {};
final int samplingRate;
public SamplingEventFilter(int paramInt)
{
this.samplingRate = paramInt;
}
public boolean skipEvent(SessionEvent paramSessionEvent)
{
boolean bool1 = EVENTS_TYPE_TO_SAMPLE.contains(paramSessionEvent.type);
boolean bool2 = true;
int i;
if ((bool1) && (paramSessionEvent.sessionEventMetadata.betaDeviceToken == null)) {
i = 1;
} else {
i = 0;
}
int j;
if (Math.abs(paramSessionEvent.sessionEventMetadata.installationId.hashCode() % this.samplingRate) != 0) {
j = 1;
} else {
j = 0;
}
if ((i == 0) || (j == 0)) {
bool2 = false;
}
return bool2;
}
}
/* Location: ~/com/crashlytics/android/answers/SamplingEventFilter.class
*
* Reversed by: J
*/
| 23.204545
| 110
| 0.644466
|
0a83bfa354d68299a05e58407b02651723a973e9
| 1,799
|
package com.example.reportproblems;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import java.util.concurrent.atomic.AtomicInteger;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private static AtomicInteger numberClicks = new AtomicInteger(0);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.btn1);
Button c = (Button)findViewById(R.id.btn2);
b.setOnClickListener(this);
c.setOnClickListener(this);
}
public void onClick(View view) {
EditText textPanel = (EditText)findViewById(R.id.et1);
switch (view.getId()) {
case R.id.btn1: // ok
String input = textPanel.getText().toString();
if (! "".equals(input)) {
// just clicking OK with no input ignored
int i = numberClicks.addAndGet(1);
String msg1 = getString(R.string.acknowlege);
msg1 = String.format(msg1, Integer.toString(i)); // Thank you for reporting your problem. Problem id:%s
textPanel.setText("");
textPanel.setHint(msg1);
}
break;
case R.id.btn2: // clear
String msg2 = getString(R.string.initialMessage);
textPanel.setText("");
textPanel.setHint(msg2);
break;
default:
break;
}
}
}
| 33.943396
| 123
| 0.605892
|
10ed71e1bacdd79853bccc628f476d3243106d92
| 896
|
package com.liyulin.demo.common.business.dto;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "分页请求参数基类")
public class BasePageReq<T extends BaseDto> extends BaseDto {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "分页请求参数(不包括分页信息)")
@Valid
private T query;
@ApiModelProperty(value = "第几页,第1页值为1", required = true, example = "1")
@NotNull
@Min(value = 1)
private Integer pageNum;
@ApiModelProperty(value = "页面数据大小", required = true, example = "10")
@NotNull
@Min(value = 1)
private Integer pageSize;
}
| 24.216216
| 72
| 0.780134
|
cfe48b9cc44750213c5799ee9d1a9888ec888a9f
| 3,282
|
package com.cjm721.overloaded.util;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.List;
public class WorldUtil {
public static RayTraceResult rayTraceWithEntities(@Nonnull World world, @Nonnull Vec3d startingLocation, @Nonnull Vec3d direction, @Nonnull Entity excludedEntity, double maxDistance) {
Vec3d endingLocation = startingLocation.add(direction.scale(maxDistance));
RayTraceResult raytraceresult = world.rayTraceBlocks(startingLocation, endingLocation, false, true, false);
if (raytraceresult != null && raytraceresult.hitVec != null) {
endingLocation = new Vec3d(raytraceresult.hitVec.x, raytraceresult.hitVec.y, raytraceresult.hitVec.z);
}
Entity entity = null;
double[] vertexes = new double[6];
vertexes[0] = startingLocation.x - 0.5D;
vertexes[1] = startingLocation.y - 0.5D;
vertexes[2] = startingLocation.z - 0.5D;
vertexes[3] = startingLocation.x + 0.5D;
vertexes[4] = startingLocation.y + 0.5D;
vertexes[5] = startingLocation.z + 0.5D;
int length = (int) Math.ceil(startingLocation.subtract(endingLocation).length());
for (double i = 0; i < length; i += 0.1) {
vertexes[0] += direction.x * i;
vertexes[1] += direction.y * i;
vertexes[2] += direction.z * i;
vertexes[3] += direction.x * i;
vertexes[4] += direction.y * i;
vertexes[5] += direction.z * i;
AxisAlignedBB boundingBox = new AxisAlignedBB(vertexes[0], vertexes[1], vertexes[2], vertexes[3], vertexes[4], vertexes[5]);
List<Entity> list = world.getEntitiesWithinAABBExcludingEntity(excludedEntity, boundingBox);
double smallestEntityDistance = 0.0D;
for (Entity entity1 : list) {
if (entity1.canBeCollidedWith() && (!entity1.isEntityEqual(excludedEntity)) && !entity1.noClip) {
AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().grow(0.30000001192092896D);
RayTraceResult intercept = axisalignedbb.calculateIntercept(startingLocation, endingLocation);
if (intercept != null && intercept.hitVec != null) {
double currentEntityDistance = startingLocation.squareDistanceTo(intercept.hitVec);
if (currentEntityDistance < smallestEntityDistance || smallestEntityDistance == 0.0D) {
entity = entity1;
smallestEntityDistance = currentEntityDistance;
}
}
}
}
if (entity != null) {
RayTraceResult intercept = boundingBox.calculateIntercept(startingLocation, endingLocation);
if (intercept != null) {
Vec3d hitVec = intercept.hitVec;
return new RayTraceResult(entity, hitVec == null ? new Vec3d(0.5, 0.5, 0.5) : hitVec);
}
}
}
return raytraceresult;
}
}
| 43.76
| 188
| 0.617916
|
15b125d94862249acaa1c7031afbc7d1a9619d37
| 3,886
|
public class Banking {
public static void main(String[] args) {
Bank bank = new Bank();
char ch;
do {
printMenu();
ch = getOperation();
try {
switch (ch) {
case 'a':
createAccount(bank);
break;
case 'e':
deposit(bank);
break;
case 'b':
withdraw(bank);
break;
case 't':
transfer(bank);
break;
case 'd':
bank.printAccounts();
break;
case 'q':
break;
default:
Out.println("Ungültige Operation");
break;
}
} catch (IllegalArgumentException e) {
Out.format("Ungültige Eingabe: %s%n", e.getMessage());
}
} while (ch != 'q');
}
private static void printMenu() {
Out.println();
Out.println("*********** Bankverwaltung ********");
Out.println("Kunde+Konto anlegen ............. a");
Out.println("Einzahlen ....................... e");
Out.println("Beheben ......................... b");
Out.println("Überweisen ...................... t");
Out.println("Übersicht drucken ............... d");
Out.println("Beenden ......................... q");
Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
}
private static char getOperation() {
char ch = Character.toLowerCase(In.readChar());
In.readLine();
return ch;
}
private static void createAccount(Bank bank) {
printTitle("Kunde und Bankkonto anlagen");
int accountId = 0;
Customer customer = getCustomer();
double overdraftLimit = getDouble("Überziehungsrahmen");
try {
accountId = bank.createAccount(customer, overdraftLimit);
} catch (Bank.BankServiceException e) {
Out.format("Fehler bei der Kontoanlegung: %s%n", e.getMessage());
}
printMessage("Anlegen", accountId >= 0);
}
private static void deposit(Bank bank) throws IllegalArgumentException {
printTitle("Einzahlen");
boolean success = false;
int accountId = getInt("Kontonummer");
double amount = getDouble("Einzahlungsbetrag");
try {
success = bank.deposit(accountId, amount);
} catch (Account.NoSuchAccountException e) {
Out.format("Fehler bei der Einzahlung: %s%n", e.getMessage());
}
printMessage("Einzahlen", success);
}
private static void withdraw(Bank bank) throws IllegalArgumentException {
printTitle("Abheben");
boolean success = false;
int accountId = getInt("Kontonummer");
double amount = getDouble("Abhebungsbetrag");
try {
success = bank.withdraw(accountId, amount);
} catch (Account.AccountingException e) {
Out.format("Fehler bei der Behebung: %s%n", e.getMessage());
}
printMessage("Abheben", success);
}
private static void transfer(Bank bank) throws IllegalArgumentException {
printTitle("Überweisen");
boolean success = false;
int fromId = getInt("Von Kontonummer");
int toId = getInt("Auf Kontonummer");
double amount = getDouble("Betrag");
try {
success = bank.transfer(fromId, toId, amount);
} catch (Account.AccountingException e) {
Out.format("Fehler bei der Überweisung: %s%n", e.getMessage());
}
printMessage("Überweisen", success);
}
private static void printTitle(String text) {
Out.println("*** " + text + " ***");
}
private static String getString(String text) {
Out.print(text + ": ");
return In.readLine();
}
private static double getDouble(String text) {
Out.print(text + ": ");
return In.readDouble();
}
private static int getInt(String text) {
Out.print(text + ": ");
return In.readInt();
}
private static Customer getCustomer() {
String firstName = getString("Vorname");
String lastName = getString("Nachname");
String phoneNumber = getString("Telefonnummer");
return new Customer(firstName, lastName, phoneNumber);
}
private static void printMessage(String operation, boolean success) {
String message = success ? operation + " erfolgreich durchgeführt" : "Ungültige Operation, versuchen Sie es noch einmal";
Out.println(message);
}
}
| 26.080537
| 123
| 0.64385
|
2dd2a36377c313a5d4aa07a8bc2dbf12838906a8
| 3,545
|
package cn.mcmod.tofucraft.inventory.slot;
import cn.mcmod.tofucraft.advancements.TofuAdvancements;
import cn.mcmod.tofucraft.item.ItemLoader;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.MathHelper;
public class SlotSaltFurnace extends Slot {
/** The player that is using the GUI where this slot resides. */
private EntityPlayer thePlayer;
private int field_75228_b;
public SlotSaltFurnace(EntityPlayer par1EntityPlayer, IInventory par2IInventory, int par3, int par4, int par5)
{
super(par2IInventory, par3, par4, par5);
this.thePlayer = par1EntityPlayer;
}
/**
* Check if the stack is a valid item for this slot. Always true beside for the armor slots.
*/
@Override
public boolean isItemValid(ItemStack par1ItemStack)
{
return false;
}
/**
* Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new
* stack.
*/
@Override
public ItemStack decrStackSize(int par1)
{
if (this.getHasStack())
{
this.field_75228_b += Math.min(par1, this.getStack().getCount());
}
return super.decrStackSize(par1);
}
@Override
public ItemStack onTake(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack)
{
this.onCrafting(par2ItemStack);
super.onTake(par1EntityPlayer, par2ItemStack);
return par2ItemStack;
}
/**
* the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an
* internal count then calls onCrafting(item).
*/
@Override
protected void onCrafting(ItemStack par1ItemStack, int par2)
{
this.field_75228_b += par2;
this.onCrafting(par1ItemStack);
}
/**
* the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood.
*/
@Override
protected void onCrafting(ItemStack par1ItemStack)
{
par1ItemStack.onCrafting(this.thePlayer.world, this.thePlayer, this.field_75228_b);
if (!this.thePlayer.world.isRemote)
{
int i = this.field_75228_b;
float f = par1ItemStack.getItem() == ItemLoader.material ? 0.2f : par1ItemStack.getItem() == ItemLoader.nigari ? 0.3f : 0.0f;
int j;
if (f == 0.0F)
{
i = 0;
}
else if (f < 1.0F)
{
j = MathHelper.floor(i * f);
if (j < MathHelper.ceil(i * f) && (float)Math.random() < i * f - j)
{
++j;
}
i = j;
}
while (i > 0)
{
j = EntityXPOrb.getXPSplit(i);
i -= j;
this.thePlayer.world.spawnEntity(new EntityXPOrb(this.thePlayer.world, this.thePlayer.posX, this.thePlayer.posY + 0.5D, this.thePlayer.posZ + 0.5D, j));
}
}
this.field_75228_b = 0;
if (par1ItemStack.getItem() == ItemLoader.material)
{
TofuAdvancements.grantAdvancement(this.thePlayer, "getsalt");
}
else if (par1ItemStack.getItem() == ItemLoader.nigari)
{
TofuAdvancements.grantAdvancement(this.thePlayer, "getnigari");
}
}
}
| 30.042373
| 168
| 0.605642
|
7ccef010c1c3054d6c62e80c9c40ba253135e25e
| 311
|
public class book {
public static void main(String[] args)
{
String head1="a";
String head2="a^2";
String head3="a^3";
System.out.printf("%-8s%-8s%-8s%n",head1,head2,head3);
for(int i=1;i<5;i++)
System.out.printf("%-8d%-8d%-8d%n",i,i*i,i*i*i);
}
}
| 28.272727
| 62
| 0.511254
|
6fe4913d0742fcafdfc3780bca7a182250e3891d
| 51,809
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.search;
import org.apache.lucene.search.BooleanQuery;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.geo.ShapesAvailability;
import org.elasticsearch.common.geo.builders.ShapeBuilders;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.multibindings.Multibinder;
import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ParseFieldRegistry;
import org.elasticsearch.index.percolator.PercolatorHighlightSubFetchPhase;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.BoostingQueryBuilder;
import org.elasticsearch.index.query.CommonTermsQueryBuilder;
import org.elasticsearch.index.query.ConstantScoreQueryBuilder;
import org.elasticsearch.index.query.DisMaxQueryBuilder;
import org.elasticsearch.index.query.EmptyQueryBuilder;
import org.elasticsearch.index.query.ExistsQueryBuilder;
import org.elasticsearch.index.query.FieldMaskingSpanQueryBuilder;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.GeoBoundingBoxQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceRangeQueryBuilder;
import org.elasticsearch.index.query.GeoPolygonQueryBuilder;
import org.elasticsearch.index.query.GeoShapeQueryBuilder;
import org.elasticsearch.index.query.GeohashCellQuery;
import org.elasticsearch.index.query.HasChildQueryBuilder;
import org.elasticsearch.index.query.HasParentQueryBuilder;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.elasticsearch.index.query.IndicesQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchNoneQueryBuilder;
import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.MoreLikeThisQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.ParentIdQueryBuilder;
import org.elasticsearch.index.query.PercolateQueryBuilder;
import org.elasticsearch.index.query.PrefixQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParser;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.RegexpQueryBuilder;
import org.elasticsearch.index.query.ScriptQueryBuilder;
import org.elasticsearch.index.query.SimpleQueryStringBuilder;
import org.elasticsearch.index.query.SpanContainingQueryBuilder;
import org.elasticsearch.index.query.SpanFirstQueryBuilder;
import org.elasticsearch.index.query.SpanMultiTermQueryBuilder;
import org.elasticsearch.index.query.SpanNearQueryBuilder;
import org.elasticsearch.index.query.SpanNotQueryBuilder;
import org.elasticsearch.index.query.SpanOrQueryBuilder;
import org.elasticsearch.index.query.SpanTermQueryBuilder;
import org.elasticsearch.index.query.SpanWithinQueryBuilder;
import org.elasticsearch.index.query.TemplateQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.index.query.TypeQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.index.query.WrapperQueryBuilder;
import org.elasticsearch.index.query.functionscore.ExponentialDecayFunctionBuilder;
import org.elasticsearch.index.query.functionscore.FieldValueFactorFunctionBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.GaussDecayFunctionBuilder;
import org.elasticsearch.index.query.functionscore.LinearDecayFunctionBuilder;
import org.elasticsearch.index.query.functionscore.RandomScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionParser;
import org.elasticsearch.index.query.functionscore.ScriptScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.WeightBuilder;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.search.action.SearchTransportService;
import org.elasticsearch.search.aggregations.AggregationPhase;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorBuilder;
import org.elasticsearch.search.aggregations.AggregatorParsers;
import org.elasticsearch.search.aggregations.bucket.children.ChildrenAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.children.InternalChildren;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.filters.InternalFilters;
import org.elasticsearch.search.aggregations.bucket.geogrid.GeoGridAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.geogrid.GeoHashGridParser;
import org.elasticsearch.search.aggregations.bucket.geogrid.InternalGeoHashGrid;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramParser;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramParser;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.bucket.missing.InternalMissing;
import org.elasticsearch.search.aggregations.bucket.missing.MissingAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.missing.MissingParser;
import org.elasticsearch.search.aggregations.bucket.nested.InternalNested;
import org.elasticsearch.search.aggregations.bucket.nested.InternalReverseNested;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ReverseNestedAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.range.InternalRange;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.range.RangeParser;
import org.elasticsearch.search.aggregations.bucket.range.date.DateRangeAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.range.date.DateRangeParser;
import org.elasticsearch.search.aggregations.bucket.range.date.InternalDateRange;
import org.elasticsearch.search.aggregations.bucket.range.geodistance.GeoDistanceAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.range.geodistance.GeoDistanceParser;
import org.elasticsearch.search.aggregations.bucket.range.geodistance.InternalGeoDistance;
import org.elasticsearch.search.aggregations.bucket.range.ipv4.IPv4RangeAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.range.ipv4.InternalIPv4Range;
import org.elasticsearch.search.aggregations.bucket.range.ipv4.IpRangeParser;
import org.elasticsearch.search.aggregations.bucket.sampler.DiversifiedAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.sampler.DiversifiedSamplerParser;
import org.elasticsearch.search.aggregations.bucket.sampler.InternalSampler;
import org.elasticsearch.search.aggregations.bucket.sampler.SamplerAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.sampler.UnmappedSampler;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantLongTerms;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantStringTerms;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantTermsAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantTermsParser;
import org.elasticsearch.search.aggregations.bucket.significant.UnmappedSignificantTerms;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.ChiSquare;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.GND;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.JLHScore;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.MutualInformation;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.PercentageScore;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.ScriptHeuristic;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristic;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristicParser;
import org.elasticsearch.search.aggregations.bucket.terms.DoubleTerms;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregatorBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsParser;
import org.elasticsearch.search.aggregations.bucket.terms.UnmappedTerms;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.AvgParser;
import org.elasticsearch.search.aggregations.metrics.avg.InternalAvg;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityParser;
import org.elasticsearch.search.aggregations.metrics.cardinality.InternalCardinality;
import org.elasticsearch.search.aggregations.metrics.geobounds.GeoBoundsAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.geobounds.GeoBoundsParser;
import org.elasticsearch.search.aggregations.metrics.geobounds.InternalGeoBounds;
import org.elasticsearch.search.aggregations.metrics.geocentroid.GeoCentroidAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.geocentroid.GeoCentroidParser;
import org.elasticsearch.search.aggregations.metrics.geocentroid.InternalGeoCentroid;
import org.elasticsearch.search.aggregations.metrics.max.InternalMax;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.max.MaxParser;
import org.elasticsearch.search.aggregations.metrics.min.InternalMin;
import org.elasticsearch.search.aggregations.metrics.min.MinAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.min.MinParser;
import org.elasticsearch.search.aggregations.metrics.percentiles.PercentileRanksAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.percentiles.PercentileRanksParser;
import org.elasticsearch.search.aggregations.metrics.percentiles.PercentilesAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.percentiles.PercentilesParser;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.InternalHDRPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.InternalHDRPercentiles;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.InternalTDigestPercentileRanks;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.InternalTDigestPercentiles;
import org.elasticsearch.search.aggregations.metrics.scripted.InternalScriptedMetric;
import org.elasticsearch.search.aggregations.metrics.scripted.ScriptedMetricAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.InternalStats;
import org.elasticsearch.search.aggregations.metrics.stats.StatsAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.StatsParser;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsParser;
import org.elasticsearch.search.aggregations.metrics.stats.extended.InternalExtendedStats;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.sum.SumParser;
import org.elasticsearch.search.aggregations.metrics.tophits.InternalTopHits;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHitsAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.InternalValueCount;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregatorBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountParser;
import org.elasticsearch.search.aggregations.pipeline.InternalSimpleValue;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.InternalBucketMetricValue;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.avg.AvgBucketPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.avg.AvgBucketPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.max.MaxBucketPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.max.MaxBucketPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.min.MinBucketPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.min.MinBucketPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.percentile.PercentilesBucketPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.percentile.PercentilesBucketPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.StatsBucketPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.StatsBucketPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucketParser;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucketPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucketPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.sum.SumBucketPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.sum.SumBucketPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketscript.BucketScriptPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketscript.BucketScriptPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.bucketselector.BucketSelectorPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketselector.BucketSelectorPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.cumulativesum.CumulativeSumPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.cumulativesum.CumulativeSumPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.derivative.DerivativePipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.derivative.DerivativePipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.derivative.InternalDerivative;
import org.elasticsearch.search.aggregations.pipeline.movavg.MovAvgPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.movavg.MovAvgPipelineAggregatorBuilder;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.EwmaModel;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.HoltLinearModel;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.HoltWintersModel;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.LinearModel;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.MovAvgModel;
import org.elasticsearch.search.aggregations.pipeline.movavg.models.SimpleModel;
import org.elasticsearch.search.aggregations.pipeline.serialdiff.SerialDiffPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.serialdiff.SerialDiffPipelineAggregatorBuilder;
import org.elasticsearch.search.controller.SearchPhaseController;
import org.elasticsearch.search.dfs.DfsPhase;
import org.elasticsearch.search.fetch.FetchPhase;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.fetch.explain.ExplainFetchSubPhase;
import org.elasticsearch.search.fetch.fielddata.FieldDataFieldsFetchSubPhase;
import org.elasticsearch.search.fetch.innerhits.InnerHitsFetchSubPhase;
import org.elasticsearch.search.fetch.matchedqueries.MatchedQueriesFetchSubPhase;
import org.elasticsearch.search.fetch.parent.ParentFieldSubFetchPhase;
import org.elasticsearch.search.fetch.script.ScriptFieldsFetchSubPhase;
import org.elasticsearch.search.fetch.source.FetchSourceSubPhase;
import org.elasticsearch.search.fetch.version.VersionFetchSubPhase;
import org.elasticsearch.search.highlight.HighlightPhase;
import org.elasticsearch.search.highlight.Highlighter;
import org.elasticsearch.search.highlight.Highlighters;
import org.elasticsearch.search.query.QueryPhase;
import org.elasticsearch.search.rescore.QueryRescorerBuilder;
import org.elasticsearch.search.rescore.RescoreBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.ScriptSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.suggest.Suggester;
import org.elasticsearch.search.suggest.Suggesters;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
public class SearchModule extends AbstractModule {
private final Highlighters highlighters = new Highlighters();
private final Suggesters suggesters;
private final ParseFieldRegistry<ScoreFunctionParser<?>> scoreFunctionParserRegistry = new ParseFieldRegistry<>("score_function");
private final IndicesQueriesRegistry queryParserRegistry = new IndicesQueriesRegistry();
private final ParseFieldRegistry<Aggregator.Parser> aggregationParserRegistry = new ParseFieldRegistry<>("aggregation");
private final ParseFieldRegistry<PipelineAggregator.Parser> pipelineAggregationParserRegistry = new ParseFieldRegistry<>(
"pipline_aggregation");
private final AggregatorParsers aggregatorParsers = new AggregatorParsers(aggregationParserRegistry, pipelineAggregationParserRegistry);
private final ParseFieldRegistry<SignificanceHeuristicParser> significanceHeuristicParserRegistry = new ParseFieldRegistry<>(
"significance_heuristic");
private final ParseFieldRegistry<MovAvgModel.AbstractModelParser> movingAverageModelParserRegistry = new ParseFieldRegistry<>(
"moving_avg_model");
private final Set<Class<? extends FetchSubPhase>> fetchSubPhases = new HashSet<>();
private final Settings settings;
private final NamedWriteableRegistry namedWriteableRegistry;
// pkg private so tests can mock
Class<? extends SearchService> searchServiceImpl = SearchService.class;
public SearchModule(Settings settings, NamedWriteableRegistry namedWriteableRegistry) {
this.settings = settings;
this.namedWriteableRegistry = namedWriteableRegistry;
suggesters = new Suggesters(namedWriteableRegistry);
registerBuiltinScoreFunctionParsers();
registerBuiltinQueryParsers();
registerBuiltinRescorers();
registerBuiltinSorts();
registerBuiltinValueFormats();
registerBuiltinSignificanceHeuristics();
registerBuiltinMovingAverageModels();
}
public void registerHighlighter(String key, Class<? extends Highlighter> clazz) {
highlighters.registerExtension(key, clazz);
}
public void registerSuggester(String key, Suggester<?> suggester) {
suggesters.register(key, suggester);
}
/**
* Register a new ScoreFunctionBuilder. Registration does two things:
* <ul>
* <li>Register the {@link ScoreFunctionParser} which parses XContent into a {@link ScoreFunctionBuilder} using its {@link ParseField}
* </li>
* <li>Register the {@link Writeable.Reader} which reads a stream representation of the builder under the
* {@linkplain ParseField#getPreferredName()}.</li>
* </ul>
*/
public <T extends ScoreFunctionBuilder<T>> void registerScoreFunction(Writeable.Reader<T> reader, ScoreFunctionParser<T> parser,
ParseField functionName) {
scoreFunctionParserRegistry.register(parser, functionName);
namedWriteableRegistry.register(ScoreFunctionBuilder.class, functionName.getPreferredName(), reader);
}
/**
* Fetch the registry of {@linkplain ScoreFunction}s. This is public so extensions can access the score functions.
*/
public ParseFieldRegistry<ScoreFunctionParser<?>> getScoreFunctionParserRegistry() {
return scoreFunctionParserRegistry;
}
/**
* Register a new ValueFormat.
*/
// private for now, we can consider making it public if there are actual use cases for plugins
// to register custom value formats
private void registerValueFormat(String name, Writeable.Reader<? extends DocValueFormat> reader) {
namedWriteableRegistry.register(DocValueFormat.class, name, reader);
}
/**
* Register a query.
*
* @param reader the reader registered for this query's builder. Typically a reference to a constructor that takes a
* {@link org.elasticsearch.common.io.stream.StreamInput}
* @param queryParser the parser the reads the query builder from xcontent
* @param queryName holds the names by which this query might be parsed. The {@link ParseField#getPreferredName()} is special as it
* is the name by under which the reader is registered. So it is the name that the query should use as its
* {@link NamedWriteable#getWriteableName()} too.
*/
public <QB extends QueryBuilder> void registerQuery(Writeable.Reader<QB> reader, QueryParser<QB> queryParser,
ParseField queryName) {
queryParserRegistry.register(queryParser, queryName);
namedWriteableRegistry.register(QueryBuilder.class, queryName.getPreferredName(), reader);
}
public IndicesQueriesRegistry getQueryParserRegistry() {
return queryParserRegistry;
}
public void registerFetchSubPhase(Class<? extends FetchSubPhase> subPhase) {
fetchSubPhases.add(subPhase);
}
/**
* Register a {@link SignificanceHeuristic}.
*
* @param heuristicName the name(s) at which the heuristic is parsed and streamed. The {@link ParseField#getPreferredName()} is the name
* under which it is streamed. All names work for the parser.
* @param reader reads the heuristic from a stream
* @param parser reads the heuristic from an XContentParser
*/
public void registerSignificanceHeuristic(ParseField heuristicName, Writeable.Reader<SignificanceHeuristic> reader,
SignificanceHeuristicParser parser) {
significanceHeuristicParserRegistry.register(parser, heuristicName);
namedWriteableRegistry.register(SignificanceHeuristic.class, heuristicName.getPreferredName(), reader);
}
/**
* The registry of {@link SignificanceHeuristic}s.
*/
public ParseFieldRegistry<SignificanceHeuristicParser> getSignificanceHeuristicParserRegistry() {
return significanceHeuristicParserRegistry;
}
/**
* Register a {@link MovAvgModel}.
*
* @param modelName the name(s) at which the model is parsed and streamed. The {@link ParseField#getPreferredName()} is the name under
* which it is streamed. All named work for the parser.
* @param reader reads the model from a stream
* @param parser reads the model from an XContentParser
*/
public void registerMovingAverageModel(ParseField modelName, Writeable.Reader<MovAvgModel> reader,
MovAvgModel.AbstractModelParser parser) {
movingAverageModelParserRegistry.register(parser, modelName);
namedWriteableRegistry.register(MovAvgModel.class, modelName.getPreferredName(), reader);
}
/**
* The registry of {@link MovAvgModel}s.
*/
public ParseFieldRegistry<MovAvgModel.AbstractModelParser> getMovingAverageMdelParserRegistry() {
return movingAverageModelParserRegistry;
}
/**
* Register an aggregation.
*
* @param reader reads the aggregation builder from a stream
* @param aggregationParser reads the aggregation builder from XContent
* @param aggregationName names by which the aggregation may be parsed. The first name is special because it is the name that the reader
* is registered under.
*/
public <AB extends AggregatorBuilder<AB>> void registerAggregation(Writeable.Reader<AB> reader, Aggregator.Parser aggregationParser,
ParseField aggregationName) {
aggregationParserRegistry.register(aggregationParser, aggregationName);
namedWriteableRegistry.register(AggregatorBuilder.class, aggregationName.getPreferredName(), reader);
}
/**
* Register a pipeline aggregation.
*
* @param reader reads the aggregation builder from a stream
* @param aggregationParser reads the aggregation builder from XContent
* @param aggregationName names by which the aggregation may be parsed. The first name is special because it is the name that the reader
* is registered under.
*/
public <AB extends PipelineAggregatorBuilder<AB>> void registerPipelineAggregation(Writeable.Reader<AB> reader,
PipelineAggregator.Parser aggregationParser, ParseField aggregationName) {
pipelineAggregationParserRegistry.register(aggregationParser, aggregationName);
namedWriteableRegistry.register(PipelineAggregatorBuilder.class, aggregationName.getPreferredName(), reader);
}
public AggregatorParsers getAggregatorParsers() {
return aggregatorParsers;
}
@Override
protected void configure() {
bind(IndicesQueriesRegistry.class).toInstance(queryParserRegistry);
bind(Suggesters.class).toInstance(suggesters);
configureSearch();
configureAggs();
configureHighlighters();
configureFetchSubPhase();
configureShapes();
}
protected void configureFetchSubPhase() {
Multibinder<FetchSubPhase> fetchSubPhaseMultibinder = Multibinder.newSetBinder(binder(), FetchSubPhase.class);
fetchSubPhaseMultibinder.addBinding().to(ExplainFetchSubPhase.class);
fetchSubPhaseMultibinder.addBinding().to(FieldDataFieldsFetchSubPhase.class);
fetchSubPhaseMultibinder.addBinding().to(ScriptFieldsFetchSubPhase.class);
fetchSubPhaseMultibinder.addBinding().to(FetchSourceSubPhase.class);
fetchSubPhaseMultibinder.addBinding().to(VersionFetchSubPhase.class);
fetchSubPhaseMultibinder.addBinding().to(MatchedQueriesFetchSubPhase.class);
fetchSubPhaseMultibinder.addBinding().to(HighlightPhase.class);
fetchSubPhaseMultibinder.addBinding().to(ParentFieldSubFetchPhase.class);
fetchSubPhaseMultibinder.addBinding().to(PercolatorHighlightSubFetchPhase.class);
for (Class<? extends FetchSubPhase> clazz : fetchSubPhases) {
fetchSubPhaseMultibinder.addBinding().to(clazz);
}
bind(InnerHitsFetchSubPhase.class).asEagerSingleton();
}
protected void configureHighlighters() {
highlighters.bind(binder());
}
protected void configureAggs() {
registerAggregation(AvgAggregatorBuilder::new, new AvgParser(), AvgAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(SumAggregatorBuilder::new, new SumParser(), SumAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(MinAggregatorBuilder::new, new MinParser(), MinAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(MaxAggregatorBuilder::new, new MaxParser(), MaxAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(StatsAggregatorBuilder::new, new StatsParser(), StatsAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(ExtendedStatsAggregatorBuilder::new, new ExtendedStatsParser(),
ExtendedStatsAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(ValueCountAggregatorBuilder::new, new ValueCountParser(), ValueCountAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(PercentilesAggregatorBuilder::new, new PercentilesParser(),
PercentilesAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(PercentileRanksAggregatorBuilder::new, new PercentileRanksParser(),
PercentileRanksAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(CardinalityAggregatorBuilder::new, new CardinalityParser(),
CardinalityAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(GlobalAggregatorBuilder::new, GlobalAggregatorBuilder::parse, GlobalAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(MissingAggregatorBuilder::new, new MissingParser(), MissingAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(FilterAggregatorBuilder::new, FilterAggregatorBuilder::parse, FilterAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(FiltersAggregatorBuilder::new, FiltersAggregatorBuilder::parse,
FiltersAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(SamplerAggregatorBuilder::new, SamplerAggregatorBuilder::parse,
SamplerAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(DiversifiedAggregatorBuilder::new, new DiversifiedSamplerParser(),
DiversifiedAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(TermsAggregatorBuilder::new, new TermsParser(), TermsAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(SignificantTermsAggregatorBuilder::new,
new SignificantTermsParser(significanceHeuristicParserRegistry, queryParserRegistry),
SignificantTermsAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(RangeAggregatorBuilder::new, new RangeParser(), RangeAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(DateRangeAggregatorBuilder::new, new DateRangeParser(), DateRangeAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(IPv4RangeAggregatorBuilder::new, new IpRangeParser(), IPv4RangeAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(HistogramAggregatorBuilder::new, new HistogramParser(), HistogramAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(DateHistogramAggregatorBuilder::new, new DateHistogramParser(),
DateHistogramAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(GeoDistanceAggregatorBuilder::new, new GeoDistanceParser(),
GeoDistanceAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(GeoGridAggregatorBuilder::new, new GeoHashGridParser(), GeoGridAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(NestedAggregatorBuilder::new, NestedAggregatorBuilder::parse, NestedAggregatorBuilder.AGGREGATION_FIELD_NAME);
registerAggregation(ReverseNestedAggregatorBuilder::new, ReverseNestedAggregatorBuilder::parse,
ReverseNestedAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(TopHitsAggregatorBuilder::new, TopHitsAggregatorBuilder::parse,
TopHitsAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(GeoBoundsAggregatorBuilder::new, new GeoBoundsParser(), GeoBoundsAggregatorBuilder.AGGREGATION_NAME_FIED);
registerAggregation(GeoCentroidAggregatorBuilder::new, new GeoCentroidParser(),
GeoCentroidAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(ScriptedMetricAggregatorBuilder::new, ScriptedMetricAggregatorBuilder::parse,
ScriptedMetricAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerAggregation(ChildrenAggregatorBuilder::new, ChildrenAggregatorBuilder::parse,
ChildrenAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(DerivativePipelineAggregatorBuilder::new, DerivativePipelineAggregatorBuilder::parse,
DerivativePipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(MaxBucketPipelineAggregatorBuilder::new, MaxBucketPipelineAggregatorBuilder.PARSER,
MaxBucketPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(MinBucketPipelineAggregatorBuilder::new, MinBucketPipelineAggregatorBuilder.PARSER,
MinBucketPipelineAggregatorBuilder.AGGREGATION_FIELD_NAME);
registerPipelineAggregation(AvgBucketPipelineAggregatorBuilder::new, AvgBucketPipelineAggregatorBuilder.PARSER,
AvgBucketPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(SumBucketPipelineAggregatorBuilder::new, SumBucketPipelineAggregatorBuilder.PARSER,
SumBucketPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(StatsBucketPipelineAggregatorBuilder::new, StatsBucketPipelineAggregatorBuilder.PARSER,
StatsBucketPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(ExtendedStatsBucketPipelineAggregatorBuilder::new, new ExtendedStatsBucketParser(),
ExtendedStatsBucketPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(PercentilesBucketPipelineAggregatorBuilder::new, PercentilesBucketPipelineAggregatorBuilder.PARSER,
PercentilesBucketPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(MovAvgPipelineAggregatorBuilder::new,
(n, c) -> MovAvgPipelineAggregatorBuilder.parse(movingAverageModelParserRegistry, n, c),
MovAvgPipelineAggregatorBuilder.AGGREGATION_FIELD_NAME);
registerPipelineAggregation(CumulativeSumPipelineAggregatorBuilder::new, CumulativeSumPipelineAggregatorBuilder::parse,
CumulativeSumPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(BucketScriptPipelineAggregatorBuilder::new, BucketScriptPipelineAggregatorBuilder::parse,
BucketScriptPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(BucketSelectorPipelineAggregatorBuilder::new, BucketSelectorPipelineAggregatorBuilder::parse,
BucketSelectorPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
registerPipelineAggregation(SerialDiffPipelineAggregatorBuilder::new, SerialDiffPipelineAggregatorBuilder::parse,
SerialDiffPipelineAggregatorBuilder.AGGREGATION_NAME_FIELD);
AggregationPhase aggPhase = new AggregationPhase();
bind(AggregatorParsers.class).toInstance(aggregatorParsers);
bind(AggregationPhase.class).toInstance(aggPhase);
}
protected void configureSearch() {
// configure search private classes...
bind(DfsPhase.class).asEagerSingleton();
bind(QueryPhase.class).asEagerSingleton();
bind(SearchPhaseController.class).asEagerSingleton();
bind(FetchPhase.class).asEagerSingleton();
bind(SearchTransportService.class).asEagerSingleton();
if (searchServiceImpl == SearchService.class) {
bind(SearchService.class).asEagerSingleton();
} else {
bind(SearchService.class).to(searchServiceImpl).asEagerSingleton();
}
}
private void configureShapes() {
if (ShapesAvailability.JTS_AVAILABLE && ShapesAvailability.SPATIAL4J_AVAILABLE) {
ShapeBuilders.register(namedWriteableRegistry);
}
}
private void registerBuiltinRescorers() {
namedWriteableRegistry.register(RescoreBuilder.class, QueryRescorerBuilder.NAME, QueryRescorerBuilder::new);
}
private void registerBuiltinSorts() {
namedWriteableRegistry.register(SortBuilder.class, GeoDistanceSortBuilder.NAME, GeoDistanceSortBuilder::new);
namedWriteableRegistry.register(SortBuilder.class, ScoreSortBuilder.NAME, ScoreSortBuilder::new);
namedWriteableRegistry.register(SortBuilder.class, ScriptSortBuilder.NAME, ScriptSortBuilder::new);
namedWriteableRegistry.register(SortBuilder.class, FieldSortBuilder.NAME, FieldSortBuilder::new);
}
private void registerBuiltinScoreFunctionParsers() {
registerScoreFunction(ScriptScoreFunctionBuilder::new, ScriptScoreFunctionBuilder::fromXContent,
ScriptScoreFunctionBuilder.FUNCTION_NAME_FIELD);
registerScoreFunction(GaussDecayFunctionBuilder::new, GaussDecayFunctionBuilder.PARSER,
GaussDecayFunctionBuilder.FUNCTION_NAME_FIELD);
registerScoreFunction(LinearDecayFunctionBuilder::new, LinearDecayFunctionBuilder.PARSER,
LinearDecayFunctionBuilder.FUNCTION_NAME_FIELD);
registerScoreFunction(ExponentialDecayFunctionBuilder::new, ExponentialDecayFunctionBuilder.PARSER,
ExponentialDecayFunctionBuilder.FUNCTION_NAME_FIELD);
registerScoreFunction(RandomScoreFunctionBuilder::new, RandomScoreFunctionBuilder::fromXContent,
RandomScoreFunctionBuilder.FUNCTION_NAME_FIELD);
registerScoreFunction(FieldValueFactorFunctionBuilder::new, FieldValueFactorFunctionBuilder::fromXContent,
FieldValueFactorFunctionBuilder.FUNCTION_NAME_FIELD);
//weight doesn't have its own parser, so every function supports it out of the box.
//Can be a single function too when not associated to any other function, which is why it needs to be registered manually here.
namedWriteableRegistry.register(ScoreFunctionBuilder.class, WeightBuilder.NAME, WeightBuilder::new);
}
private void registerBuiltinValueFormats() {
registerValueFormat(DocValueFormat.BOOLEAN.getWriteableName(), in -> DocValueFormat.BOOLEAN);
registerValueFormat(DocValueFormat.DateTime.NAME, DocValueFormat.DateTime::new);
registerValueFormat(DocValueFormat.Decimal.NAME, DocValueFormat.Decimal::new);
registerValueFormat(DocValueFormat.GEOHASH.getWriteableName(), in -> DocValueFormat.GEOHASH);
registerValueFormat(DocValueFormat.IP.getWriteableName(), in -> DocValueFormat.IP);
registerValueFormat(DocValueFormat.RAW.getWriteableName(), in -> DocValueFormat.RAW);
}
private void registerBuiltinSignificanceHeuristics() {
registerSignificanceHeuristic(ChiSquare.NAMES_FIELD, ChiSquare::new, ChiSquare.PARSER);
registerSignificanceHeuristic(GND.NAMES_FIELD, GND::new, GND.PARSER);
registerSignificanceHeuristic(JLHScore.NAMES_FIELD, JLHScore::new, JLHScore::parse);
registerSignificanceHeuristic(MutualInformation.NAMES_FIELD, MutualInformation::new, MutualInformation.PARSER);
registerSignificanceHeuristic(PercentageScore.NAMES_FIELD, PercentageScore::new, PercentageScore::parse);
registerSignificanceHeuristic(ScriptHeuristic.NAMES_FIELD, ScriptHeuristic::new, ScriptHeuristic::parse);
}
private void registerBuiltinMovingAverageModels() {
registerMovingAverageModel(SimpleModel.NAME_FIELD, SimpleModel::new, SimpleModel.PARSER);
registerMovingAverageModel(LinearModel.NAME_FIELD, LinearModel::new, LinearModel.PARSER);
registerMovingAverageModel(EwmaModel.NAME_FIELD, EwmaModel::new, EwmaModel.PARSER);
registerMovingAverageModel(HoltLinearModel.NAME_FIELD, HoltLinearModel::new, HoltLinearModel.PARSER);
registerMovingAverageModel(HoltWintersModel.NAME_FIELD, HoltWintersModel::new, HoltWintersModel.PARSER);
}
private void registerBuiltinQueryParsers() {
registerQuery(MatchQueryBuilder::new, MatchQueryBuilder::fromXContent, MatchQueryBuilder.QUERY_NAME_FIELD);
registerQuery(MatchPhraseQueryBuilder::new, MatchPhraseQueryBuilder::fromXContent, MatchPhraseQueryBuilder.QUERY_NAME_FIELD);
registerQuery(MatchPhrasePrefixQueryBuilder::new, MatchPhrasePrefixQueryBuilder::fromXContent,
MatchPhrasePrefixQueryBuilder.QUERY_NAME_FIELD);
registerQuery(MultiMatchQueryBuilder::new, MultiMatchQueryBuilder::fromXContent, MultiMatchQueryBuilder.QUERY_NAME_FIELD);
registerQuery(NestedQueryBuilder::new, NestedQueryBuilder::fromXContent, NestedQueryBuilder.QUERY_NAME_FIELD);
registerQuery(HasChildQueryBuilder::new, HasChildQueryBuilder::fromXContent, HasChildQueryBuilder.QUERY_NAME_FIELD);
registerQuery(HasParentQueryBuilder::new, HasParentQueryBuilder::fromXContent, HasParentQueryBuilder.QUERY_NAME_FIELD);
registerQuery(DisMaxQueryBuilder::new, DisMaxQueryBuilder::fromXContent, DisMaxQueryBuilder.QUERY_NAME_FIELD);
registerQuery(IdsQueryBuilder::new, IdsQueryBuilder::fromXContent, IdsQueryBuilder.QUERY_NAME_FIELD);
registerQuery(MatchAllQueryBuilder::new, MatchAllQueryBuilder::fromXContent, MatchAllQueryBuilder.QUERY_NAME_FIELD);
registerQuery(QueryStringQueryBuilder::new, QueryStringQueryBuilder::fromXContent, QueryStringQueryBuilder.QUERY_NAME_FIELD);
registerQuery(BoostingQueryBuilder::new, BoostingQueryBuilder::fromXContent, BoostingQueryBuilder.QUERY_NAME_FIELD);
BooleanQuery.setMaxClauseCount(settings.getAsInt("index.query.bool.max_clause_count",
settings.getAsInt("indices.query.bool.max_clause_count", BooleanQuery.getMaxClauseCount())));
registerQuery(BoolQueryBuilder::new, BoolQueryBuilder::fromXContent, BoolQueryBuilder.QUERY_NAME_FIELD);
registerQuery(TermQueryBuilder::new, TermQueryBuilder::fromXContent, TermQueryBuilder.QUERY_NAME_FIELD);
registerQuery(TermsQueryBuilder::new, TermsQueryBuilder::fromXContent, TermsQueryBuilder.QUERY_NAME_FIELD);
registerQuery(FuzzyQueryBuilder::new, FuzzyQueryBuilder::fromXContent, FuzzyQueryBuilder.QUERY_NAME_FIELD);
registerQuery(RegexpQueryBuilder::new, RegexpQueryBuilder::fromXContent, RegexpQueryBuilder.QUERY_NAME_FIELD);
registerQuery(RangeQueryBuilder::new, RangeQueryBuilder::fromXContent, RangeQueryBuilder.QUERY_NAME_FIELD);
registerQuery(PrefixQueryBuilder::new, PrefixQueryBuilder::fromXContent, PrefixQueryBuilder.QUERY_NAME_FIELD);
registerQuery(WildcardQueryBuilder::new, WildcardQueryBuilder::fromXContent, WildcardQueryBuilder.QUERY_NAME_FIELD);
registerQuery(ConstantScoreQueryBuilder::new, ConstantScoreQueryBuilder::fromXContent, ConstantScoreQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SpanTermQueryBuilder::new, SpanTermQueryBuilder::fromXContent, SpanTermQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SpanNotQueryBuilder::new, SpanNotQueryBuilder::fromXContent, SpanNotQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SpanWithinQueryBuilder::new, SpanWithinQueryBuilder::fromXContent, SpanWithinQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SpanContainingQueryBuilder::new, SpanContainingQueryBuilder::fromXContent,
SpanContainingQueryBuilder.QUERY_NAME_FIELD);
registerQuery(FieldMaskingSpanQueryBuilder::new, FieldMaskingSpanQueryBuilder::fromXContent,
FieldMaskingSpanQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SpanFirstQueryBuilder::new, SpanFirstQueryBuilder::fromXContent, SpanFirstQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SpanNearQueryBuilder::new, SpanNearQueryBuilder::fromXContent, SpanNearQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SpanOrQueryBuilder::new, SpanOrQueryBuilder::fromXContent, SpanOrQueryBuilder.QUERY_NAME_FIELD);
registerQuery(MoreLikeThisQueryBuilder::new, MoreLikeThisQueryBuilder::fromXContent, MoreLikeThisQueryBuilder.QUERY_NAME_FIELD);
registerQuery(WrapperQueryBuilder::new, WrapperQueryBuilder::fromXContent, WrapperQueryBuilder.QUERY_NAME_FIELD);
// TODO Remove IndicesQuery in 6.0
registerQuery(IndicesQueryBuilder::new, IndicesQueryBuilder::fromXContent, IndicesQueryBuilder.QUERY_NAME_FIELD);
registerQuery(CommonTermsQueryBuilder::new, CommonTermsQueryBuilder::fromXContent, CommonTermsQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SpanMultiTermQueryBuilder::new, SpanMultiTermQueryBuilder::fromXContent, SpanMultiTermQueryBuilder.QUERY_NAME_FIELD);
registerQuery(FunctionScoreQueryBuilder::new, c -> FunctionScoreQueryBuilder.fromXContent(scoreFunctionParserRegistry, c),
FunctionScoreQueryBuilder.QUERY_NAME_FIELD);
registerQuery(SimpleQueryStringBuilder::new, SimpleQueryStringBuilder::fromXContent, SimpleQueryStringBuilder.QUERY_NAME_FIELD);
registerQuery(TemplateQueryBuilder::new, TemplateQueryBuilder::fromXContent, TemplateQueryBuilder.QUERY_NAME_FIELD);
registerQuery(TypeQueryBuilder::new, TypeQueryBuilder::fromXContent, TypeQueryBuilder.QUERY_NAME_FIELD);
registerQuery(ScriptQueryBuilder::new, ScriptQueryBuilder::fromXContent, ScriptQueryBuilder.QUERY_NAME_FIELD);
registerQuery(GeoDistanceQueryBuilder::new, GeoDistanceQueryBuilder::fromXContent, GeoDistanceQueryBuilder.QUERY_NAME_FIELD);
registerQuery(GeoDistanceRangeQueryBuilder::new, GeoDistanceRangeQueryBuilder::fromXContent,
GeoDistanceRangeQueryBuilder.QUERY_NAME_FIELD);
registerQuery(GeoBoundingBoxQueryBuilder::new, GeoBoundingBoxQueryBuilder::fromXContent,
GeoBoundingBoxQueryBuilder.QUERY_NAME_FIELD);
registerQuery(GeohashCellQuery.Builder::new, GeohashCellQuery.Builder::fromXContent, GeohashCellQuery.QUERY_NAME_FIELD);
registerQuery(GeoPolygonQueryBuilder::new, GeoPolygonQueryBuilder::fromXContent, GeoPolygonQueryBuilder.QUERY_NAME_FIELD);
registerQuery(ExistsQueryBuilder::new, ExistsQueryBuilder::fromXContent, ExistsQueryBuilder.QUERY_NAME_FIELD);
registerQuery(MatchNoneQueryBuilder::new, MatchNoneQueryBuilder::fromXContent, MatchNoneQueryBuilder.QUERY_NAME_FIELD);
registerQuery(ParentIdQueryBuilder::new, ParentIdQueryBuilder::fromXContent, ParentIdQueryBuilder.QUERY_NAME_FIELD);
registerQuery(PercolateQueryBuilder::new, PercolateQueryBuilder::fromXContent, PercolateQueryBuilder.QUERY_NAME_FIELD);
if (ShapesAvailability.JTS_AVAILABLE && ShapesAvailability.SPATIAL4J_AVAILABLE) {
registerQuery(GeoShapeQueryBuilder::new, GeoShapeQueryBuilder::fromXContent, GeoShapeQueryBuilder.QUERY_NAME_FIELD);
}
// EmptyQueryBuilder is not registered as query parser but used internally.
// We need to register it with the NamedWriteableRegistry in order to serialize it
namedWriteableRegistry.register(QueryBuilder.class, EmptyQueryBuilder.NAME, EmptyQueryBuilder::new);
}
static {
// calcs
InternalAvg.registerStreams();
InternalSum.registerStreams();
InternalMin.registerStreams();
InternalMax.registerStreams();
InternalStats.registerStreams();
InternalExtendedStats.registerStreams();
InternalValueCount.registerStreams();
InternalTDigestPercentiles.registerStreams();
InternalTDigestPercentileRanks.registerStreams();
InternalHDRPercentiles.registerStreams();
InternalHDRPercentileRanks.registerStreams();
InternalCardinality.registerStreams();
InternalScriptedMetric.registerStreams();
InternalGeoCentroid.registerStreams();
// buckets
InternalGlobal.registerStreams();
InternalFilter.registerStreams();
InternalFilters.registerStream();
InternalSampler.registerStreams();
UnmappedSampler.registerStreams();
InternalMissing.registerStreams();
StringTerms.registerStreams();
LongTerms.registerStreams();
SignificantStringTerms.registerStreams();
SignificantLongTerms.registerStreams();
UnmappedSignificantTerms.registerStreams();
InternalGeoHashGrid.registerStreams();
DoubleTerms.registerStreams();
UnmappedTerms.registerStreams();
InternalRange.registerStream();
InternalDateRange.registerStream();
InternalIPv4Range.registerStream();
InternalHistogram.registerStream();
InternalGeoDistance.registerStream();
InternalNested.registerStream();
InternalReverseNested.registerStream();
InternalTopHits.registerStreams();
InternalGeoBounds.registerStream();
InternalChildren.registerStream();
// Pipeline Aggregations
DerivativePipelineAggregator.registerStreams();
InternalDerivative.registerStreams();
InternalSimpleValue.registerStreams();
InternalBucketMetricValue.registerStreams();
MaxBucketPipelineAggregator.registerStreams();
MinBucketPipelineAggregator.registerStreams();
AvgBucketPipelineAggregator.registerStreams();
SumBucketPipelineAggregator.registerStreams();
StatsBucketPipelineAggregator.registerStreams();
ExtendedStatsBucketPipelineAggregator.registerStreams();
PercentilesBucketPipelineAggregator.registerStreams();
MovAvgPipelineAggregator.registerStreams();
CumulativeSumPipelineAggregator.registerStreams();
BucketScriptPipelineAggregator.registerStreams();
BucketSelectorPipelineAggregator.registerStreams();
SerialDiffPipelineAggregator.registerStreams();
}
public Suggesters getSuggesters() {
return suggesters;
}
}
| 67.197147
| 140
| 0.811288
|
e87b6a88bd4223a27cecd3de997e851b0584987e
| 2,107
|
package de.adito.propertly.core.common;
import de.adito.propertly.core.spi.IHierarchy;
import de.adito.propertly.core.spi.IProperty;
import de.adito.propertly.core.spi.IPropertyPitProvider;
/**
* Little helper class for debugging.
*
* @author j.boesl, 14.01.15
*/
public class PropertlyDebug
{
/**
* Transforms given IHierarchy to a readable string.
*
* @param pHierarchy the starting point.
* @return the whole tree as a string.
*/
public static String toTreeString(IHierarchy<?> pHierarchy)
{
return toTreeString(pHierarchy.getProperty());
}
/**
* Transforms given IPropertyPitProvider to a readable string.
*
* @param pPitProvider the starting point.
* @return the subtree starting at the supplied IPropertyPitProvider as a string.
*/
public static String toTreeString(IPropertyPitProvider<?, ?, ?> pPitProvider)
{
return toTreeString(pPitProvider.getPit().getOwnProperty());
}
/**
* Transforms given IProperty to a readable string.
*
* @param pProperty the starting point.
* @return the subtree starting at the supplied IProperty as a string.
*/
public static String toTreeString(IProperty<?, ?> pProperty)
{
StringBuilder stringBuilder = new StringBuilder();
_buildTree(stringBuilder, pProperty, "");
return stringBuilder.toString();
}
private static void _buildTree(StringBuilder pStr, IProperty<?, ?> pProperty, String pLevel)
{
if (pProperty == null)
return;
boolean isPitProvider = IPropertyPitProvider.class.isAssignableFrom(pProperty.getType());
Object value = pProperty.getValue();
if (isPitProvider && value == null)
return;
pStr.append(pLevel);
if (isPitProvider)
pStr.append("/");
else
pStr.append(" ");
pStr.append(pProperty.getName());
if (!isPitProvider)
pStr.append(" : ").append(value);
pStr.append("\n");
if (isPitProvider)
{
for (IProperty<?, ?> childProperty : ((IPropertyPitProvider<?, ?, ?>) value).getPit().getProperties())
_buildTree(pStr, childProperty, pLevel + "\t");
}
}
}
| 27.723684
| 108
| 0.680589
|
b4afae360de15b0f4cefb92aa38e6e7f44b44314
| 2,159
|
package dingo;
/**Contains all messages to permit communication among components
*
* @author marco
*
*/
public class CommandProtocol
{
public static final String MESSAGE_HI = "HI";
public static final String MESSAGE_BYE = "BYE";
public static final String MESSAGE_OK = "OK";
public static final String MESSAGE_KO = "KO";
public static final String MESSAGE_SERVER_SHUTDOWN = "SERVER_SHUTDOWN";
public static final String MESSAGE_SERVER_STATUS = "SERVER_STATUS";
//Marco
public static final String MESSAGE_DIR_CONTENT = "DIR_CONTENT";
public static final String MESSAGE_CONNECT_MACHINE = "CONNECT_MACHINE";
public static final String MESSAGE_ADD_BOLT = "ADD_BOLT";
public static final String MESSAGE_REMOVE_BOLT = "REMOVE_BOLT";
public static final String MESSAGE_REMOVE_ALL_BOLTS = "REMOVE_ALL_BOLTS";
public static final String MESSAGE_FILE_ADDED = "file_added";
public static final String MESSAGE_FILE_DELETED = "file_deleted";
public static final String MESSAGE_FILE_CHANGED = "file_changed";
public static final String MESSAGE_DIRECTORY_ADDED = "directory_added";
public static final String MESSAGE_DIRECTORY_DELETED = "directory_deleted";
public static final String MESSAGE_DIRECTORY_CHANGED = "directory_changed";
public static final String COMMAND_EXIT = "exit";
public static final String COMMAND_VER = "ver";
public static final String COMMAND_CONNECT = "connect";
public static final String COMMAND_DISCONNECT = "disconnect";
public static final String COMMAND_STATUS = "status";
public static final String COMMAND_HELP = "help";
public static final String COMMAND_SAY = "say";
public static final String COMMAND_SERVER_SHUTDOWN = "server_shutdown";
public static final String COMMAND_SERVER_STATUS = "server_status";
//Marco
public static final String COMMAND_DIR_CONTENT= "dir_content";
public static final String COMMAND_CONNECT_MACHINE= "connect_machine";
public static final String COMMAND_ADD_BOLT = "add_bolt";
public static final String COMMAND_REMOVE_BOLT = "remove_bolt";
public static final String COMMAND_REMOVE_ALL_BOLTS = "remove_all_bolts";
}
| 46.934783
| 77
| 0.782307
|
1bc3f71ecbbe4ec87e4c7dc9a34192fc75c7b120
| 131
|
package model.dto;
public interface PageInfo {
static final int ROW_PER_PAGE = 5;
static final int PAGE_PER_NEXT = 3;
}
| 16.375
| 37
| 0.709924
|
31e691b94d6d773794e3509f9e6874ecad87db8e
| 4,609
|
/*
* Copyright 2005 Joe Walker
*
* 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.directwebremoting.dwrp;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.directwebremoting.ConversionException;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.extend.ConverterManager;
import org.directwebremoting.extend.EnginePrivate;
import org.directwebremoting.extend.ProtocolConstants;
import org.directwebremoting.extend.ScriptBufferUtil;
import org.directwebremoting.extend.Sleeper;
import org.directwebremoting.util.MimeConstants;
/**
* A ScriptConduit for use with HTML/PRE wrapped Javascript output.
* <p>Scripts begin with an html, body and pre tag followed by plain Javascript
* without 'execute-in-parent-context' wrapping, but with script-start and
* script-end markers.
* <p>If this conduit is used the client should direct the output to an iframe
* and then poll, looking for new data into the iframe. The html tags should be
* removed and script between script-start and script-end tags eval()ed.
* <p>This conduit also sends 4k of whitespace data on each flush. This causes
* IE to recognize new content. This would be a significant network overhead
* so it is important to use gzip on the connection. This complexity has caused
* us to turn this conduit off at the moment.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Html4kScriptConduit extends BaseScriptConduit
{
/**
* Simple ctor
* @param response Used to flush output
* @param batchId The id of the batch that we are responding to
* @param converterManager How we convert objects to script
* @throws IOException If stream actions fail
*/
public Html4kScriptConduit(Sleeper sleeper, HttpServletResponse response, String batchId, ConverterManager converterManager, boolean jsonOutput) throws IOException
{
super(sleeper, response, batchId, converterManager, jsonOutput);
}
/* (non-Javadoc)
* @see org.directwebremoting.dwrp.BaseCallHandler#getOutboundMimeType()
*/
@Override
protected String getOutboundMimeType()
{
return MimeConstants.MIME_HTML;
}
/* (non-Javadoc)
* @see org.directwebremoting.dwrp.BaseScriptConduit#beginStream()
*/
@Override
public void beginStream()
{
synchronized (out)
{
out.println("<html><body><pre>");
out.println(ProtocolConstants.SCRIPT_START_MARKER);
out.println(EnginePrivate.remoteBeginIFrameResponse(batchId, false));
out.println(ProtocolConstants.SCRIPT_END_MARKER);
}
}
/* (non-Javadoc)
* @see org.directwebremoting.dwrp.BaseScriptConduit#endStream()
*/
@Override
public void endStream()
{
synchronized (out)
{
out.println(ProtocolConstants.SCRIPT_START_MARKER);
out.println(EnginePrivate.remoteEndIFrameResponse(batchId, false));
out.println(ProtocolConstants.SCRIPT_END_MARKER);
out.println("</pre></body></html>");
}
}
/* (non-Javadoc)
* @see org.directwebremoting.ScriptConduit#addScript(org.directwebremoting.ScriptBuffer)
*/
@Override
public boolean addScript(ScriptBuffer scriptBuffer) throws IOException, ConversionException
{
String script = ScriptBufferUtil.createOutput(scriptBuffer, converterManager, jsonOutput);
synchronized (out)
{
out.println(ProtocolConstants.SCRIPT_START_MARKER);
out.println(script);
out.println(ProtocolConstants.SCRIPT_END_MARKER);
out.print(FOUR_K_FLUSH_DATA);
return flush();
}
}
/**
* The slab of data we send to IE to get it to stream
*/
protected static final String FOUR_K_FLUSH_DATA;
static
{
StringBuffer buffer = new StringBuffer(409600);
for (int i = 0; i < 4096; i++)
{
buffer.append(" ");
}
FOUR_K_FLUSH_DATA = buffer.toString();
}
}
| 34.654135
| 167
| 0.699067
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.