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 |
|---|---|---|---|---|---|
082a2ee718bf03c81fc0b221d40393d78d5fb681 | 750 | package hackerrank.algorithms;
public class MultiplyStrings {
public String multiply(String a, String b) {
int ans[] = new int[a.length() + b.length()];
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < b.length(); j++) {
int x = (a.charAt(i) - '0') * (b.charAt(j) - '0');
int pos1 = i + j;
int pos2 = i + j + 1;
int y = ans[pos2] + x;
ans[pos1] += y / 10;
ans[pos2] += y % 10;
}
}
StringBuilder sb = new StringBuilder();
for (int p : ans) if (!(sb.length() == 0 && p == 0)) sb.append(p);
return sb.length() == 0 ? "0" : sb.toString();
}
}
| 32.608696 | 75 | 0.412 |
14634116f04a4754db5c44245b14b2931a35a307 | 8,521 | /*
* 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.routing;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.ESIntegTestCase;
import org.mockito.internal.util.collections.Sets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class PartitionedRoutingIT extends ESIntegTestCase {
public void testVariousPartitionSizes() throws Exception {
for (int shards = 1; shards <= 4; shards++) {
for (int partitionSize = 1; partitionSize < shards; partitionSize++) {
String index = "index_" + shards + "_" + partitionSize;
client().admin().indices().prepareCreate(index)
.setSettings(Settings.builder()
.put("index.number_of_shards", shards)
.put("index.routing_partition_size", partitionSize))
.addMapping("type", "{\"type\":{\"_routing\":{\"required\":true}}}")
.execute().actionGet();
ensureGreen();
Map<String, Set<String>> routingToDocumentIds = generateRoutedDocumentIds(index);
verifyGets(index, routingToDocumentIds);
verifyBroadSearches(index, routingToDocumentIds, shards);
verifyRoutedSearches(index, routingToDocumentIds, Sets.newSet(partitionSize));
}
}
}
public void testShrinking() throws Exception {
// creates random routing groups and repeatedly halves the index until it is down to 1 shard
// verifying that the count is correct for each shrunken index
final int partitionSize = 3;
final int originalShards = 8;
int currentShards = originalShards;
String index = "index_" + currentShards;
client().admin().indices().prepareCreate(index)
.setSettings(Settings.builder()
.put("index.number_of_shards", currentShards)
.put("index.routing_partition_size", partitionSize))
.addMapping("type", "{\"type\":{\"_routing\":{\"required\":true}}}")
.execute().actionGet();
ensureGreen();
Map<String, Set<String>> routingToDocumentIds = generateRoutedDocumentIds(index);
while (true) {
int factor = originalShards / currentShards;
verifyGets(index, routingToDocumentIds);
verifyBroadSearches(index, routingToDocumentIds, currentShards);
// we need the floor and ceiling of the routing_partition_size / factor since the partition size of the shrunken
// index will be one of those, depending on the routing value
verifyRoutedSearches(index, routingToDocumentIds,
Math.floorDiv(partitionSize, factor) == 0 ?
Sets.newSet(1, 2) :
Sets.newSet(Math.floorDiv(partitionSize, factor), -Math.floorDiv(-partitionSize, factor)));
client().admin().indices().prepareUpdateSettings(index)
.setSettings(Settings.builder()
.put("index.routing.allocation.require._name", client().admin().cluster().prepareState().get().getState().nodes()
.getDataNodes().values().toArray(DiscoveryNode.class)[0].getName())
.put("index.blocks.write", true)).get();
ensureGreen();
currentShards = Math.floorDiv(currentShards, 2);
if (currentShards == 0) {
break;
}
String previousIndex = index;
index = "index_" + currentShards;
logger.info("--> shrinking index [" + previousIndex + "] to [" + index + "]");
client().admin().indices().prepareShrinkIndex(previousIndex, index)
.setSettings(Settings.builder()
.put("index.number_of_shards", currentShards)
.build()).get();
ensureGreen();
}
}
private void verifyRoutedSearches(String index, Map<String, Set<String>> routingToDocumentIds, Set<Integer> expectedShards) {
for (Map.Entry<String, Set<String>> routingEntry : routingToDocumentIds.entrySet()) {
String routing = routingEntry.getKey();
int expectedDocuments = routingEntry.getValue().size();
SearchResponse response = client().prepareSearch()
.setQuery(QueryBuilders.termQuery("_routing", routing))
.setRouting(routing)
.setIndices(index)
.setSize(100)
.execute().actionGet();
logger.info("--> routed search on index [" + index + "] visited [" + response.getTotalShards()
+ "] shards for routing [" + routing + "] and got hits [" + response.getHits().totalHits() + "]");
assertTrue(response.getTotalShards() + " was not in " + expectedShards + " for " + index,
expectedShards.contains(response.getTotalShards()));
assertEquals(expectedDocuments, response.getHits().totalHits());
Set<String> found = new HashSet<>();
response.getHits().forEach(h -> found.add(h.getId()));
assertEquals(routingEntry.getValue(), found);
}
}
private void verifyBroadSearches(String index, Map<String, Set<String>> routingToDocumentIds, int expectedShards) {
for (Map.Entry<String, Set<String>> routingEntry : routingToDocumentIds.entrySet()) {
String routing = routingEntry.getKey();
int expectedDocuments = routingEntry.getValue().size();
SearchResponse response = client().prepareSearch()
.setQuery(QueryBuilders.termQuery("_routing", routing))
.setIndices(index)
.setSize(100)
.execute().actionGet();
assertEquals(expectedShards, response.getTotalShards());
assertEquals(expectedDocuments, response.getHits().totalHits());
Set<String> found = new HashSet<>();
response.getHits().forEach(h -> found.add(h.getId()));
assertEquals(routingEntry.getValue(), found);
}
}
private void verifyGets(String index, Map<String, Set<String>> routingToDocumentIds) {
for (Map.Entry<String, Set<String>> routingEntry : routingToDocumentIds.entrySet()) {
String routing = routingEntry.getKey();
for (String id : routingEntry.getValue()) {
assertTrue(client().prepareGet(index, "type", id).setRouting(routing).execute().actionGet().isExists());
}
}
}
private Map<String, Set<String>> generateRoutedDocumentIds(String index) {
Map<String, Set<String>> routingToDocumentIds = new HashMap<>();
int numRoutingValues = randomIntBetween(5, 15);
for (int i = 0; i < numRoutingValues; i++) {
String routingValue = String.valueOf(i);
int numDocuments = randomIntBetween(10, 100);
routingToDocumentIds.put(String.valueOf(routingValue), new HashSet<>());
for (int k = 0; k < numDocuments; k++) {
String id = routingValue + "_" + String.valueOf(k);
routingToDocumentIds.get(routingValue).add(id);
client().prepareIndex(index, "type", id)
.setRouting(routingValue)
.setSource("foo", "bar")
.get();
}
}
client().admin().indices().prepareRefresh(index).get();
return routingToDocumentIds;
}
}
| 43.035354 | 133 | 0.61636 |
52b5294cd092380e6e7038268b1f339d90bf3faf | 2,137 | package com.v1690117.app.controllers;
import com.v1690117.app.model.Genre;
import com.v1690117.app.services.GenreService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequiredArgsConstructor
public class GenreController {
private final GenreService genreService;
@GetMapping(value = "/genres")
public String getAll(Model model) {
model.addAttribute("genres", genreService.findAll());
return "genres";
}
@ResponseBody
@GetMapping(value = "/genres.json")
public List<Genre> getAll() {
return genreService.findAll();
}
@GetMapping("/genres/{id}")
public String getById(@PathVariable("id") long id, Model model) {
model.addAttribute("genre", genreService.findById(id));
return "genre";
}
@ResponseBody
@GetMapping("/genres/{id}.json")
public Genre getById(@PathVariable("id") long id) {
return genreService.findById(id);
}
@GetMapping("/genres/new")
public String getCreationForm(Model model) {
model.addAttribute("genre", new Genre());
return "genre";
}
@PostMapping("/genres")
public String add(@RequestParam("name") String name) {
genreService.insert(
new Genre(
name
)
);
return "success";
}
@PostMapping("/genres/{id}")
public String update(Genre genre) {
genreService.update(
genre
);
return "success";
}
@DeleteMapping("/genres/{id}")
public String delete(@PathVariable("id") long id) {
genreService.delete(id);
return "success";
}
}
| 28.118421 | 69 | 0.665419 |
b6aa0127524e4770a3b10b6aee38c9417f33a4b6 | 852 | package com.springstudy.sfdistudy;
import com.springstudy.sfdistudy.controllers.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class SfDiStudyApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SfDiStudyApplication.class, args);
MyController controller = (MyController) ctx.getBean("myController");
System.out.println(controller.hello());
System.out.println(ctx.getBean(PropertyInjectedController.class).sayHello());
System.out.println(ctx.getBean(GetterInjectedController.class).sayHello());
System.out.println(ctx.getBean(ConstructorInjectedController.class).sayHello());
}
}
| 35.5 | 89 | 0.775822 |
33fe18542633132e9fc63117ecf3a83a9d44fb8a | 72 | package io.waterdrop.datastructure.heap;
public class HeapElement {
}
| 12 | 40 | 0.791667 |
fcf39bbd6870bed3108d4a2fd3b53a899ed0a31f | 1,384 | package de.maxanier.guideapi.api;
import de.maxanier.guideapi.GuideMod;
import de.maxanier.guideapi.api.impl.Book;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public interface IGuideBook {
/**
* Build your guide book here. The returned book will be registered for you. The book created here can be modified
* later, so make sure to keep a reference for yourself.
* This is called during the Register<Item> event, so don't do anything here except binding your book.
*
* @return a built book to be registered.
*/
@Nullable
Book buildBook();
/**
* @return The resource location of your own model or null if you want handle rendering yourself somehow
*/
@Nullable
@OnlyIn(Dist.CLIENT)
default ResourceLocation getModel() {
return new ResourceLocation(GuideMod.ID, "guidebook");
}
/**
* Called during Post Initialization.
*/
default void handlePost(@Nonnull ItemStack bookStack) {
// No-op
}
/**
* If you want to register {@link IInfoRenderer} to {@link GuideAPI}, do it in here.
*/
default void registerInfoRenderer(Book yourBook) {
}
}
| 28.833333 | 118 | 0.697977 |
2f0394866eaa51b3dffd8423fe3955da96c5fbd9 | 75,634 | /*
* DarkUniverseView.java
*/
package darkuniverseapp;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.ListSelectionEvent;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import wox.serial.Easy;
import net.sourceforge.jsorter.*;
/**
* The application's main frame.
*/
public class DarkUniverseView extends FrameView {
ArrayList Powers;
Player player = new Player();
SwingSorter sort = new SwingSorter();
DefaultListModel pwrModel = new DefaultListModel();
public DarkUniverseView(SingleFrameApplication app) {
super(app);
initComponents();
PowerList.setModel(new DefaultListModel());
pwrModel = (DefaultListModel) PowerList.getModel();
try {
// Load character data if present
this.loadCharacter();
} catch (FileNotFoundException ex) {
Logger.getLogger(DarkUniverseView.class.getName()).log(Level.WARNING, null, ex);
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(DarkUniverseView.class.getName()).log(Level.SEVERE, null, ex);
}
// Add selectionlistener for Powerlist
PowerList.addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (PowerList.getSelectedIndex() == -1) {
// No selection
PowerDeleteBtn.setEnabled(false);
PowerSaveBtn.setEnabled(true);
} else {
PowerDeleteBtn.setEnabled(true);
ComboBoxModel pwrCompleteModel = PowerCompleted.getModel();
Power p = fetchPower(pwrModel.get(PowerList.getSelectedIndex()).toString());
if (p == null) {
statusMessageLabel.setText("Power not found!");
return;
}
PowerName.setText(p.pwrname);
PowerBase.setText(p.pwrbase);
PowerLevel.setText("" + p.pwrlevel);
PowerDescription.setText(p.pwrdesc);
pwrCompleteModel.setSelectedItem(p.pwrcomplete);
PowerLevelNameLbl.setText(p.pwrcat);
}
}
}
}
);
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
@Override
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (null != propertyName) switch (propertyName) {
case "started":
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
break;
case "done":
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
break;
case "message":
String text = (String) (evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
break;
case "progress":
int value = (Integer) (evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
break;
}
}
});
}
@Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = DarkUniverseApp.getApplication().getMainFrame();
aboutBox = new DarkUniverseAboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
DarkUniverseApp.getApplication().show(aboutBox);
}
@Action
public void getCharacterName() {
String s = (String) JOptionPane.showInputDialog(null, "Please enter the new username",
"User Name", JOptionPane.PLAIN_MESSAGE, null, null, PlayerNameLbl.getText());
PlayerNameLbl.setText(s);
player.playername = s;
}
@Action
public void showDiceFrame() {
if (duDiceFrame == null) {
JFrame mainFrame = DarkUniverseApp.getApplication().getMainFrame();
duDiceFrame = new DiceFrame(mainFrame, false);
duDiceFrame.setLocationRelativeTo(mainFrame);
}
DarkUniverseApp.getApplication().show(duDiceFrame);
}
@Action
public void addKarma() {
// Add karma
int karma = Integer.parseInt(Karma.getText());
karma = karma + Integer.parseInt(KarmaMod.getText());
Karma.setText("" + karma);
}
@Action
public void subKarma() {
// subtract karma
player.karma = Integer.parseInt(Karma.getText());
player.karma = player.karma - Integer.parseInt(KarmaMod.getText());
Karma.setText("" + player.karma);
}
@Action
public void addRes() {
// Add resources
player.resources = Integer.parseInt(Resources.getText());
player.resources = player.resources + Integer.parseInt(ResMod.getText());
Resources.setText("" + player.resources);
}
@Action
public void subRes() {
// subtract resources
player.resources = Integer.parseInt(Resources.getText());
player.resources = player.resources - Integer.parseInt(ResMod.getText());
Resources.setText("" + player.resources);
}
@Action
public void saveCharacter() throws FileNotFoundException, IOException {
if (WantXML.isSelected() == true) {
this.saveCharacterXML();
}
if (WantXML.isSelected() == false) {
this.saveCharacterSerial();
}
}
@Action
private void loadCharacter() throws FileNotFoundException, IOException, ClassNotFoundException {
System.out.println("XML=" + WantXML.isSelected());
if (WantXML.isSelected() == true) {
this.loadCharacterXML();
}
if (WantXML.isSelected() == false) {
this.loadCharacterSerial();
}
}
@Action
public void saveCharacterData() {
// Load all values in the class.
player.playername = this.PlayerNameLbl.getText();
player.baseclass = this.PlayerClassLbl.getText();
player.karma = Integer.parseInt(Karma.getText());
player.resources = Integer.parseInt(Resources.getText());
player.initiative = Integer.parseInt(Initiative.getText());
player.playernotes = PlayerNotes.getText();
player.health = Integer.parseInt(Health.getText());
// FASERIP
player.fighting = Integer.parseInt(Fighting.getText());
player.agility = Integer.parseInt(Agility.getText());
player.strength = Integer.parseInt(Strength.getText());
player.endurance = Integer.parseInt(Endurance.getText());
player.reason = Integer.parseInt(Reason.getText());
player.intuition = Integer.parseInt(Intuition.getText());
player.psycho = Integer.parseInt(Psycho.getText());
// Powers
player.Powers = Powers;
}
@Action
public void saveCharacterSerial() throws FileNotFoundException, IOException {
FileOutputStream f_out;
ObjectOutputStream obj_out;
File uFile = new File("user.data");
uFile.delete();
this.saveCharacterData();
f_out = new FileOutputStream("user.data");
obj_out = new ObjectOutputStream(f_out);
obj_out.writeObject(player);
statusMessageLabel.setText("Character saved.");
}
@Action
public void saveCharacterXML() throws IOException {
File uFile = new File("user.xml");
uFile.delete();
Easy.save(player, "user.xml");
statusMessageLabel.setText("Character saved (XML).");
}
@Action
public void loadCharacterData() {
// We have the data, now update the fields. Update this as stuff gets added.
if (player != null) {
PlayerNameLbl.setText(player.playername);
PlayerClassLbl.setText(player.baseclass);
Karma.setText("" + player.karma);
Resources.setText("" + player.resources);
Initiative.setText("" + player.initiative);
PlayerNotes.setText(player.playernotes);
Health.setText("" + player.health);
// Dump FASERIP
Fighting.setText("" + player.fighting);
Agility.setText("" + player.agility);
Strength.setText("" + player.strength);
Endurance.setText("" + player.endurance);
Reason.setText("" + player.reason);
Intuition.setText("" + player.intuition);
Psycho.setText("" + player.psycho);
Powers = player.Powers;
}
if (Powers == null) {
Powers = new ArrayList();
}
// Populate the powerlist
for (Object o: Powers) {
int index = PowerList.getSelectedIndex();
int size = pwrModel.getSize();
Power p = (Power) o;
// No selection or last position is selected, add new one and select
if (index == -1 || (index + 1 == size)) {
pwrModel.addElement(p.pwrname);
PowerList.setSelectedIndex(size);
} else {
// Otherwise, insert it and select
pwrModel.insertElementAt(p.pwrname, index + 1);
PowerList.setSelectedIndex(index + 1);
PowerList.ensureIndexIsVisible(index + 1);
}
}
PowerList.setSelectedIndex(0);
sort.sortListModel(pwrModel);
}
@Action
public void loadCharacterSerial() throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream f_in = new FileInputStream("user.data");
ObjectInputStream obj_in = new ObjectInputStream(f_in);
Object o = obj_in.readObject();
if (o instanceof Player) {
this.player = (Player) o;
} else {
statusMessageLabel.setText("Could not load character data.");
return;
}
loadCharacterData();
}
@Action
public void loadCharacterXML() throws FileNotFoundException {
try {
player = (Player) Easy.load("user.xml");
} finally {
loadCharacterData();
}
}
@Action
public void importXmlData() {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter ff = new FileNameExtensionFilter("User data", "xml");
String userData;
System.out.println("Trying to open file chooser.");
fc.addChoosableFileFilter(ff);
int res = fc.showOpenDialog(null);
if (res == JFileChooser.APPROVE_OPTION) {
userData = fc.getSelectedFile().getPath();
} else {
return;
}
try {
Powers.clear(); // Reset this
} catch (NullPointerException e) {
Powers = new ArrayList(); // Init
}
try {
player = (Player) Easy.load(userData);
} finally {
loadCharacterData();
}
}
@Action
public void pwrSaveBtnClick() {
int index = PowerList.getSelectedIndex();
int size;
Power p = new Power();
p.pwrname = PowerName.getText();
p.pwrbase = PowerBase.getText();
p.pwrlevel = Integer.parseInt(PowerLevel.getText());
p.pwrcat = lvlToName(p.pwrlevel);
p.pwrdesc = PowerDescription.getText();
p.pwrcomplete = PowerCompleted.getModel().getSelectedItem().toString();
if (powerExists(p.pwrname)) {
// Find power, edit values.
for (Object o: Powers) {
Power gp = (Power) o;
if (gp.pwrname.equals(p.pwrname)) {
delPower(p.pwrname);
Powers.add(p);
}
}
// Check if it is a base power, then update all child
// powers that have it as a base.
// TODO: Make it recurse when base powers have base powers.
if (isBasePower(p.pwrname)) {
for (Object o: Powers) {
Power gp = (Power) o;
if (gp.pwrbase.equals(p.pwrname)) { // Got one!
System.out.println("Found child power: " + gp.pwrname);
gp.pwrlevel = p.pwrlevel;
}
}
}
} else {
// Add power to ArrayList, and add it to list.
try {
Powers.add(p);
} catch (NullPointerException e) {
Powers = new ArrayList();
Powers.add(p);
}
size = pwrModel.getSize();
// No selection or last position is selected, add new one and select
if (index == -1 || (index + 1 == size)) {
pwrModel.addElement(p.pwrname);
PowerList.setSelectedIndex(size);
} else {
// Otherwise, insert it and select
pwrModel.insertElementAt(p.pwrname, index + 1);
PowerList.setSelectedIndex(index + 1);
PowerList.ensureIndexIsVisible(index + 1);
sort.sortListModel(pwrModel);
}
}
}
@Action
public void pwrDeleteBtnClick() {
String pwrname = pwrModel.get(PowerList.getSelectedIndex()).toString();
ListSelectionModel lsm = PowerList.getSelectionModel();
int first = lsm.getMinSelectionIndex();
int last = lsm.getMaxSelectionIndex();
pwrModel.removeRange(first, last);
int size = pwrModel.size();
if (size == 0) { // List is empty
PowerDeleteBtn.setEnabled(false);
return; // No further action.
} else {
// Last item was deleted
if (first == pwrModel.getSize()) {
first--;
}
PowerList.setSelectedIndex(first);
sort.sortListModel(pwrModel);
}
// Delete power from powers list
delPower(pwrname);
}
public Power fetchPower(String pwrname) {
// Power p = new Power();
for (Object q: Powers) {
Power p = (Power) q;
if (p.pwrname.equals(pwrname)) {
return p;
}
}
return null;
}
public Boolean isBasePower(String pwrname) {
for (Object o: Powers) {
Power p = (Power) o;
if (p.pwrname.equals(pwrname)) {
if (p.pwrbase.equals("None") || p.pwrbase.isEmpty())
return true;
}
}
return false;
}
public void delPower(String pwrname) {
int index = 0;
for (Object q: Powers) {
Power p = (Power) q;
if (p.pwrname.equals(pwrname)) {
Powers.remove(index);
return;
}
index++;
}
}
public Boolean powerExists(String pwrname) {
// Check if it's empty, if the object was never instantiated,
// then construct.
try {
if (Powers.isEmpty() == true) {
return false;
}
} catch (NullPointerException e) {
Powers = new ArrayList();
return false;
}
for (Object q: Powers) {
Power p = (Power) q;
if (p.pwrname.equals(pwrname)) {
return true;
}
}
return false;
}
public String lvlToName(Integer power) {
if (power == 0) {
return "Sh";
}
if (power >= 351) {
return "ShZ";
}
if (power >= 176) {
return "ShY";
}
if (power >= 126) {
return "ShX";
}
if (power >= 88) {
return "Un";
}
if (power >= 63) {
return "Mn";
}
if (power >= 46) {
return "Am";
}
if (power >= 37) {
return "In";
}
if (power >= 26) {
return "Rm";
}
if (power >= 16) {
return "Ex";
}
if (power >= 8) {
return "Gd";
}
if (power >= 5) {
return "Ty";
}
if (power >= 3) {
return "Pr";
}
if (power >= 1) {
return "Fe";
}
return "Unk";
}
/** 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() {
mainPanel = new javax.swing.JPanel();
NameChgBtn = new javax.swing.JButton();
PlayerNameLbl = new javax.swing.JLabel();
DiceShowBtn = new javax.swing.JButton();
TabbedPane = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
Fighting = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
Reason = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
Psycho = new javax.swing.JTextField();
Agility = new javax.swing.JTextField();
Intuition = new javax.swing.JTextField();
Endurance = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
Strength = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
Initiative = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
Health = new javax.swing.JTextField();
FCatLbl = new javax.swing.JLabel();
ACatLbl = new javax.swing.JLabel();
SCatLbl = new javax.swing.JLabel();
ECatLbl = new javax.swing.JLabel();
RCatLbl = new javax.swing.JLabel();
ICatLbl = new javax.swing.JLabel();
PCatLbl = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
PowerList = new javax.swing.JList();
jLabel13 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
PowerDescription = new javax.swing.JTextArea();
jLabel14 = new javax.swing.JLabel();
PowerBase = new javax.swing.JTextField();
PwrNameLbl = new javax.swing.JLabel();
PowerCompleted = new javax.swing.JComboBox();
PowerSaveBtn = new javax.swing.JButton();
jLabel12 = new javax.swing.JLabel();
PowerName = new javax.swing.JTextField();
PowerLevelNameLbl = new javax.swing.JLabel();
PowerLevel = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
PowerDeleteBtn = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
Karma = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
KarmaMod = new javax.swing.JTextField();
ResAddBtn = new javax.swing.JButton();
KarmaAddBtn = new javax.swing.JButton();
Resources = new javax.swing.JTextField();
ResMod = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
PlayerNotes = new javax.swing.JEditorPane();
CharSaveBtn = new javax.swing.JButton();
PlayerNameLbl1 = new javax.swing.JLabel();
WantXML = new javax.swing.JCheckBox();
PlayerNameLbl2 = new javax.swing.JLabel();
PlayerClassLbl = new javax.swing.JLabel();
PlayerClassBtn = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
mainPanel.setOpaque(false);
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(darkuniverseapp.DarkUniverseApp.class).getContext().getActionMap(DarkUniverseView.class, this);
NameChgBtn.setAction(actionMap.get("getCharacterName")); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(darkuniverseapp.DarkUniverseApp.class).getContext().getResourceMap(DarkUniverseView.class);
NameChgBtn.setText(resourceMap.getString("NameChgBtn.text")); // NOI18N
NameChgBtn.setToolTipText(resourceMap.getString("NameChgBtn.toolTipText")); // NOI18N
NameChgBtn.setName("NameChgBtn"); // NOI18N
PlayerNameLbl.setFont(PlayerNameLbl.getFont().deriveFont(PlayerNameLbl.getFont().getSize()+4f));
PlayerNameLbl.setText(resourceMap.getString("PlayerNameLbl.text")); // NOI18N
PlayerNameLbl.setName("PlayerNameLbl"); // NOI18N
DiceShowBtn.setAction(actionMap.get("showDiceFrame")); // NOI18N
DiceShowBtn.setText(resourceMap.getString("DiceShowBtn.text")); // NOI18N
DiceShowBtn.setName("DiceShowBtn"); // NOI18N
TabbedPane.setName("TabbedPane"); // NOI18N
jPanel1.setName("jPanel1"); // NOI18N
jPanel4.setName("jPanel4"); // NOI18N
Fighting.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Fighting.setText(resourceMap.getString("Fighting.text")); // NOI18N
Fighting.setName("Fighting"); // NOI18N
Fighting.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FightingActionPerformed(evt);
}
});
Fighting.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
FightingPropertyChange(evt);
}
});
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
jLabel9.setName("jLabel9"); // NOI18N
jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
jLabel5.setName("jLabel5"); // NOI18N
Reason.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Reason.setText(resourceMap.getString("Reason.text")); // NOI18N
Reason.setName("Reason"); // NOI18N
Reason.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ReasonActionPerformed(evt);
}
});
Reason.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
ReasonPropertyChange(evt);
}
});
jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
jLabel7.setName("jLabel7"); // NOI18N
jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
jLabel6.setName("jLabel6"); // NOI18N
Psycho.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Psycho.setText(resourceMap.getString("Psycho.text")); // NOI18N
Psycho.setName("Psycho"); // NOI18N
Psycho.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PsychoActionPerformed(evt);
}
});
Psycho.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
PsychoPropertyChange(evt);
}
});
Agility.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Agility.setText(resourceMap.getString("Agility.text")); // NOI18N
Agility.setName("Agility"); // NOI18N
Agility.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AgilityActionPerformed(evt);
}
});
Agility.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
AgilityPropertyChange(evt);
}
});
Intuition.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Intuition.setText(resourceMap.getString("Intuition.text")); // NOI18N
Intuition.setName("Intuition"); // NOI18N
Intuition.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
IntuitionActionPerformed(evt);
}
});
Intuition.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
IntuitionPropertyChange(evt);
}
});
Endurance.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Endurance.setText(resourceMap.getString("Endurance.text")); // NOI18N
Endurance.setName("Endurance"); // NOI18N
Endurance.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnduranceActionPerformed(evt);
}
});
Endurance.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
EndurancePropertyChange(evt);
}
});
jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
jLabel8.setName("jLabel8"); // NOI18N
Strength.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Strength.setText(resourceMap.getString("Strength.text")); // NOI18N
Strength.setName("Strength"); // NOI18N
Strength.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
StrengthActionPerformed(evt);
}
});
Strength.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
StrengthPropertyChange(evt);
}
});
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
jLabel10.setName("jLabel10"); // NOI18N
Initiative.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Initiative.setText(resourceMap.getString("Initiative.text")); // NOI18N
Initiative.setName("Initiative"); // NOI18N
jLabel16.setText(resourceMap.getString("jLabel16.text")); // NOI18N
jLabel16.setName("jLabel16"); // NOI18N
Health.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Health.setText(resourceMap.getString("Health.text")); // NOI18N
Health.setName("Health"); // NOI18N
FCatLbl.setText(resourceMap.getString("FCatLbl.text")); // NOI18N
FCatLbl.setName("FCatLbl"); // NOI18N
ACatLbl.setText(resourceMap.getString("ACatLbl.text")); // NOI18N
ACatLbl.setName("ACatLbl"); // NOI18N
SCatLbl.setText(resourceMap.getString("SCatLbl.text")); // NOI18N
SCatLbl.setName("SCatLbl"); // NOI18N
ECatLbl.setText(resourceMap.getString("ECatLbl.text")); // NOI18N
ECatLbl.setName("ECatLbl"); // NOI18N
RCatLbl.setText(resourceMap.getString("RCatLbl.text")); // NOI18N
RCatLbl.setName("RCatLbl"); // NOI18N
ICatLbl.setText(resourceMap.getString("ICatLbl.text")); // NOI18N
ICatLbl.setName("ICatLbl"); // NOI18N
PCatLbl.setText(resourceMap.getString("PCatLbl.text")); // NOI18N
PCatLbl.setName("PCatLbl"); // NOI18N
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(FCatLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ACatLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SCatLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ECatLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(RCatLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ICatLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PCatLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(Psycho)
.addComponent(Intuition)
.addComponent(Reason)
.addComponent(Endurance)
.addComponent(Strength)
.addComponent(Agility)
.addComponent(Fighting, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel16))
.addGap(13, 13, 13)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(Initiative)
.addComponent(Health, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Fighting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel16)
.addComponent(Health, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(FCatLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Agility, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(Initiative, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ACatLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Strength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SCatLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Endurance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ECatLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Reason, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(RCatLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Intuition, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ICatLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Psycho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PCatLbl))
.addContainerGap())
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(363, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(127, 127, 127))
);
TabbedPane.addTab(resourceMap.getString("jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N
jPanel5.setName("jPanel5"); // NOI18N
jPanel6.setName("jPanel6"); // NOI18N
jScrollPane2.setName("jScrollPane2"); // NOI18N
PowerList.setToolTipText(resourceMap.getString("PowerList.toolTipText")); // NOI18N
PowerList.setName("PowerList"); // NOI18N
jScrollPane2.setViewportView(PowerList);
jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N
jLabel13.setName("jLabel13"); // NOI18N
jScrollPane3.setName("jScrollPane3"); // NOI18N
PowerDescription.setColumns(20);
PowerDescription.setLineWrap(true);
PowerDescription.setRows(5);
PowerDescription.setWrapStyleWord(true);
PowerDescription.setName("PowerDescription"); // NOI18N
jScrollPane3.setViewportView(PowerDescription);
jLabel14.setText(resourceMap.getString("jLabel14.text")); // NOI18N
jLabel14.setName("jLabel14"); // NOI18N
PowerBase.setText(resourceMap.getString("PowerBase.text")); // NOI18N
PowerBase.setName("PowerBase"); // NOI18N
PwrNameLbl.setText(resourceMap.getString("PwrNameLbl.text")); // NOI18N
PwrNameLbl.setName("PwrNameLbl"); // NOI18N
PowerCompleted.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1/3", "2/3", "3/3", "Completed" }));
PowerCompleted.setName("PowerCompleted"); // NOI18N
PowerSaveBtn.setAction(actionMap.get("pwrSaveBtnClick")); // NOI18N
PowerSaveBtn.setText(resourceMap.getString("PowerSaveBtn.text")); // NOI18N
PowerSaveBtn.setName("PowerSaveBtn"); // NOI18N
jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
jLabel12.setName("jLabel12"); // NOI18N
PowerName.setText(resourceMap.getString("PowerName.text")); // NOI18N
PowerName.setName("PowerName"); // NOI18N
PowerLevelNameLbl.setText(resourceMap.getString("PowerLevelNameLbl.text")); // NOI18N
PowerLevelNameLbl.setName("PowerLevelNameLbl"); // NOI18N
PowerLevel.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
PowerLevel.setText(resourceMap.getString("PowerLevel.text")); // NOI18N
PowerLevel.setName("PowerLevel"); // NOI18N
PowerLevel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PowerLevelActionPerformed(evt);
}
});
PowerLevel.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
PowerLevelPropertyChange(evt);
}
});
jLabel15.setText(resourceMap.getString("jLabel15.text")); // NOI18N
jLabel15.setName("jLabel15"); // NOI18N
PowerDeleteBtn.setAction(actionMap.get("pwrDeleteBtnClick")); // NOI18N
PowerDeleteBtn.setText(resourceMap.getString("PowerDeleteBtn.text")); // NOI18N
PowerDeleteBtn.setName("PowerDeleteBtn"); // NOI18N
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
.addComponent(jLabel15)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel13)
.addComponent(PwrNameLbl)
.addComponent(jLabel12)
.addComponent(jLabel14))
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PowerCompleted, 0, 262, Short.MAX_VALUE)
.addComponent(PowerBase, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
.addComponent(PowerName, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)))
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(PowerLevelNameLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PowerLevel, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(PowerSaveBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PowerDeleteBtn)))))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PwrNameLbl)
.addComponent(PowerName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(PowerBase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(PowerSaveBtn)
.addComponent(PowerLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PowerLevelNameLbl)
.addComponent(PowerDeleteBtn))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(PowerCompleted, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE))
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(56, 56, 56))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(74, 74, 74))
);
TabbedPane.addTab(resourceMap.getString("jPanel5.TabConstraints.tabTitle"), jPanel5); // NOI18N
jPanel2.setName("jPanel2"); // NOI18N
jPanel3.setName("jPanel3"); // NOI18N
Karma.setFont(Karma.getFont());
Karma.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Karma.setText(resourceMap.getString("Karma.text")); // NOI18N
Karma.setName("Karma"); // NOI18N
jLabel1.setFont(jLabel1.getFont());
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setAlignmentX(0.5F);
jLabel1.setName("jLabel1"); // NOI18N
jLabel2.setFont(jLabel2.getFont());
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setAlignmentX(0.5F);
jLabel2.setName("jLabel2"); // NOI18N
KarmaMod.setFont(KarmaMod.getFont());
KarmaMod.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
KarmaMod.setText(resourceMap.getString("KarmaMod.text")); // NOI18N
KarmaMod.setName("KarmaMod"); // NOI18N
ResAddBtn.setAction(actionMap.get("addRes")); // NOI18N
ResAddBtn.setFont(ResAddBtn.getFont());
ResAddBtn.setText(resourceMap.getString("ResAddBtn.text")); // NOI18N
ResAddBtn.setAlignmentX(0.5F);
ResAddBtn.setName("ResAddBtn"); // NOI18N
KarmaAddBtn.setAction(actionMap.get("addKarma")); // NOI18N
KarmaAddBtn.setFont(KarmaAddBtn.getFont());
KarmaAddBtn.setText(resourceMap.getString("KarmaAddBtn.text")); // NOI18N
KarmaAddBtn.setAlignmentX(0.5F);
KarmaAddBtn.setName("KarmaAddBtn"); // NOI18N
Resources.setFont(Resources.getFont());
Resources.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
Resources.setText(resourceMap.getString("Resources.text")); // NOI18N
Resources.setName("Resources"); // NOI18N
ResMod.setFont(ResMod.getFont());
ResMod.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
ResMod.setText(resourceMap.getString("ResMod.text")); // NOI18N
ResMod.setName("ResMod"); // NOI18N
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(42, 42, 42)
.addComponent(Karma, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Resources, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(ResMod)
.addComponent(KarmaMod, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ResAddBtn, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(KarmaAddBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(67, 67, 67))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(Karma, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KarmaMod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KarmaAddBtn))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(ResAddBtn)
.addComponent(Resources, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ResMod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(250, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(327, Short.MAX_VALUE))
);
TabbedPane.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
PlayerNotes.setName("PlayerNotes"); // NOI18N
jScrollPane1.setViewportView(PlayerNotes);
TabbedPane.addTab(resourceMap.getString("jScrollPane1.TabConstraints.tabTitle"), jScrollPane1); // NOI18N
TabbedPane.setSelectedComponent(jPanel1);
CharSaveBtn.setAction(actionMap.get("saveCharacter")); // NOI18N
CharSaveBtn.setText(resourceMap.getString("CharSaveBtn.text")); // NOI18N
CharSaveBtn.setName("CharSaveBtn"); // NOI18N
PlayerNameLbl1.setFont(PlayerNameLbl1.getFont().deriveFont(PlayerNameLbl1.getFont().getSize()+4f));
PlayerNameLbl1.setText(resourceMap.getString("PlayerNameLbl1.text")); // NOI18N
PlayerNameLbl1.setName("PlayerNameLbl1"); // NOI18N
WantXML.setText(resourceMap.getString("WantXML.text")); // NOI18N
WantXML.setName("WantXML"); // NOI18N
PlayerNameLbl2.setFont(PlayerNameLbl2.getFont().deriveFont(PlayerNameLbl2.getFont().getSize()+4f));
PlayerNameLbl2.setText(resourceMap.getString("PlayerNameLbl2.text")); // NOI18N
PlayerNameLbl2.setName("PlayerNameLbl2"); // NOI18N
PlayerClassLbl.setFont(PlayerClassLbl.getFont().deriveFont(PlayerClassLbl.getFont().getSize()+4f));
PlayerClassLbl.setText(resourceMap.getString("PlayerClassLbl.text")); // NOI18N
PlayerClassLbl.setName("PlayerClassLbl"); // NOI18N
PlayerClassLbl.setVerifyInputWhenFocusTarget(false);
PlayerClassBtn.setAction(actionMap.get("getCharacterType")); // NOI18N
PlayerClassBtn.setText(resourceMap.getString("PlayerClassBtn.text")); // NOI18N
PlayerClassBtn.setDoubleBuffered(true);
PlayerClassBtn.setName("PlayerClassBtn"); // NOI18N
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(NameChgBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PlayerClassBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(DiceShowBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CharSaveBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(WantXML))
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(PlayerNameLbl1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(PlayerNameLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PlayerNameLbl2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PlayerClassLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(83, 83, 83))))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PlayerNameLbl1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PlayerNameLbl2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PlayerClassLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PlayerNameLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(NameChgBtn)
.addComponent(DiceShowBtn)
.addComponent(CharSaveBtn)
.addComponent(WantXML)
.addComponent(PlayerClassBtn))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE))
);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
fileMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileMenuActionPerformed(evt);
}
});
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
fileMenu.add(jMenuItem1);
jMenuItem2.setAction(actionMap.get("importXmlData")); // NOI18N
jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
jMenuItem2.setName("jMenuItem2"); // NOI18N
fileMenu.add(jMenuItem2);
jRadioButtonMenuItem1.setAction(actionMap.get("exportCharacterSheet")); // NOI18N
jRadioButtonMenuItem1.setText(resourceMap.getString("jRadioButtonMenuItem1.text")); // NOI18N
jRadioButtonMenuItem1.setName("jRadioButtonMenuItem1"); // NOI18N
fileMenu.add(jRadioButtonMenuItem1);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 843, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusMessageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 659, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statusMessageLabel)
.addComponent(statusAnimationLabel)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
private void FightingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FightingActionPerformed
FCatLbl.setText(lvlToName(Integer.parseInt(Fighting.getText())));
}//GEN-LAST:event_FightingActionPerformed
private void FightingPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_FightingPropertyChange
FCatLbl.setText(lvlToName(Integer.parseInt(Fighting.getText())));
}//GEN-LAST:event_FightingPropertyChange
private void AgilityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AgilityActionPerformed
ACatLbl.setText(lvlToName(Integer.parseInt(Agility.getText())));
}//GEN-LAST:event_AgilityActionPerformed
private void StrengthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StrengthActionPerformed
SCatLbl.setText(lvlToName(Integer.parseInt(Strength.getText())));
}//GEN-LAST:event_StrengthActionPerformed
private void EnduranceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EnduranceActionPerformed
ECatLbl.setText(lvlToName(Integer.parseInt(Endurance.getText())));
}//GEN-LAST:event_EnduranceActionPerformed
private void ReasonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReasonActionPerformed
RCatLbl.setText(lvlToName(Integer.parseInt(Reason.getText())));
}//GEN-LAST:event_ReasonActionPerformed
private void IntuitionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IntuitionActionPerformed
ICatLbl.setText(lvlToName(Integer.parseInt(Intuition.getText())));
}//GEN-LAST:event_IntuitionActionPerformed
private void PsychoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PsychoActionPerformed
PCatLbl.setText(lvlToName(Integer.parseInt(Psycho.getText())));
}//GEN-LAST:event_PsychoActionPerformed
private void AgilityPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_AgilityPropertyChange
ACatLbl.setText(lvlToName(Integer.parseInt(Agility.getText())));
}//GEN-LAST:event_AgilityPropertyChange
private void StrengthPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_StrengthPropertyChange
SCatLbl.setText(lvlToName(Integer.parseInt(Strength.getText())));
}//GEN-LAST:event_StrengthPropertyChange
private void EndurancePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_EndurancePropertyChange
ECatLbl.setText(lvlToName(Integer.parseInt(Endurance.getText())));
}//GEN-LAST:event_EndurancePropertyChange
private void ReasonPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_ReasonPropertyChange
RCatLbl.setText(lvlToName(Integer.parseInt(Reason.getText())));
}//GEN-LAST:event_ReasonPropertyChange
private void IntuitionPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_IntuitionPropertyChange
ICatLbl.setText(lvlToName(Integer.parseInt(Intuition.getText())));
}//GEN-LAST:event_IntuitionPropertyChange
private void PsychoPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_PsychoPropertyChange
PCatLbl.setText(lvlToName(Integer.parseInt(Psycho.getText())));
}//GEN-LAST:event_PsychoPropertyChange
private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuActionPerformed
// Nothing
}//GEN-LAST:event_fileMenuActionPerformed
private void PowerLevelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PowerLevelActionPerformed
PowerLevelNameLbl.setText(lvlToName(Integer.parseInt(PowerLevel.getText())));
}//GEN-LAST:event_PowerLevelActionPerformed
private void PowerLevelPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_PowerLevelPropertyChange
PowerLevelNameLbl.setText(lvlToName(Integer.parseInt(PowerLevel.getText())));
}//GEN-LAST:event_PowerLevelPropertyChange
@Action
public void exportCharacterSheet() {
try {
// Ready data
String outfile = player.playername + ".pdf";
// FASERIP
Map root = new HashMap();
Map playerMap = new HashMap();
playerMap.put("playername", player.playername);
playerMap.put("baseclass", player.baseclass);
playerMap.put("fighting", player.fighting);
playerMap.put("agility", player.agility);
playerMap.put("strength", player.strength);
playerMap.put("endurance", player.endurance);
playerMap.put("reason", player.reason);
playerMap.put("intuition", player.intuition);
playerMap.put("psycho", player.psycho);
playerMap.put("initiative", player.initiative);
playerMap.put("health", player.health);
playerMap.put("karma", player.karma);
playerMap.put("resources", player.resources);
playerMap.put("content", player.playernotes);
root.put("player", playerMap);
// Get player powers
Map powerMap = new HashMap();
for (Object q: Powers) {
Power p = (Power) q;
Map powerattr = new HashMap();
powerattr.put("pwrname", p.pwrname);
powerattr.put("pwrbase", p.pwrbase);
powerattr.put("pwrcat", p.pwrcat);
powerattr.put("pwrcomplete", p.pwrcomplete);
powerattr.put("pwrdesc", p.pwrdesc);
powerattr.put("pwrlvl", p.pwrlevel);
powerMap.put(p.pwrname, powerattr);
}
root.put("powers", powerMap);
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("templates/"));
cfg.setDefaultEncoding("UTF-8");
Template temp = cfg.getTemplate("character.html");
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
} catch (IOException | TemplateException ex) {
Logger.getLogger(DarkUniverseView.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Action
public void getCharacterType() {
String s = (String) JOptionPane.showInputDialog(null, "Please enter the type of character",
"Player Type", JOptionPane.PLAIN_MESSAGE, null, null, PlayerClassLbl.getText());
PlayerClassLbl.setText(s);
player.baseclass = s;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel ACatLbl;
private javax.swing.JTextField Agility;
private javax.swing.JButton CharSaveBtn;
private javax.swing.JButton DiceShowBtn;
private javax.swing.JLabel ECatLbl;
private javax.swing.JTextField Endurance;
private javax.swing.JLabel FCatLbl;
private javax.swing.JTextField Fighting;
private javax.swing.JTextField Health;
private javax.swing.JLabel ICatLbl;
private javax.swing.JTextField Initiative;
private javax.swing.JTextField Intuition;
private javax.swing.JTextField Karma;
private javax.swing.JButton KarmaAddBtn;
private javax.swing.JTextField KarmaMod;
private javax.swing.JButton NameChgBtn;
private javax.swing.JLabel PCatLbl;
private javax.swing.JButton PlayerClassBtn;
private javax.swing.JLabel PlayerClassLbl;
private javax.swing.JLabel PlayerNameLbl;
private javax.swing.JLabel PlayerNameLbl1;
private javax.swing.JLabel PlayerNameLbl2;
private javax.swing.JEditorPane PlayerNotes;
private javax.swing.JTextField PowerBase;
private javax.swing.JComboBox PowerCompleted;
private javax.swing.JButton PowerDeleteBtn;
private javax.swing.JTextArea PowerDescription;
private javax.swing.JTextField PowerLevel;
private javax.swing.JLabel PowerLevelNameLbl;
private javax.swing.JList PowerList;
private javax.swing.JTextField PowerName;
private javax.swing.JButton PowerSaveBtn;
private javax.swing.JTextField Psycho;
private javax.swing.JLabel PwrNameLbl;
private javax.swing.JLabel RCatLbl;
private javax.swing.JTextField Reason;
private javax.swing.JButton ResAddBtn;
private javax.swing.JTextField ResMod;
private javax.swing.JTextField Resources;
private javax.swing.JLabel SCatLbl;
private javax.swing.JTextField Strength;
private javax.swing.JTabbedPane TabbedPane;
private javax.swing.JCheckBox WantXML;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JProgressBar progressBar;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
// End of variables declaration//GEN-END:variables
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
private JDialog aboutBox;
private JDialog duDiceFrame;
}
| 45.727932 | 199 | 0.668694 |
8e6381671ba6e550dcb81df4aeb581ec1ed78e65 | 2,193 |
package org.sj.verb.trilateral.augmented.active.present;
import java.util.*;
import org.sj.verb.trilateral.augmented.*;
import org.sj.verb.util.AugmentationFormula;
import org.sj.verb.util.PresentConjugationDataContainer;
public class AbstractAugmentedPresentConjugator {
private List lastDprList;
private List connectedPronounList;
public AbstractAugmentedPresentConjugator(List lastDprList, List connectedPronounList) {
this.lastDprList = lastDprList;
this.connectedPronounList = connectedPronounList;
}
public AugmentedPresentVerb createVerb(AugmentedTrilateralRoot root, int pronounIndex, int formulaNo) {
String cp = PresentConjugationDataContainer.getInstance().getCp(pronounIndex);
String lastDpr = (String) lastDprList.get(pronounIndex);
String connectedPronoun = (String) connectedPronounList.get(pronounIndex);
String formulaClassName = getClass().getPackage().getName()+".formula."+"AugmentedPresentVerb"+formulaNo;
Object [] parameters = {root, cp, lastDpr, connectedPronoun};
try {
AugmentedPresentVerb verb = (AugmentedPresentVerb) Class.forName(formulaClassName).getConstructors()[0].newInstance(parameters);
return verb;
}
catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public List createVerbList(AugmentedTrilateralRoot root, int formulaNo) {
List result = new LinkedList();
for (int i = 0; i < 13; i++) {
AugmentedPresentVerb verb = createVerb(root, i, formulaNo);
result.add(verb);
}
return result;
}
public Map createAllVerbList(AugmentedTrilateralRoot root) {
Map result = new HashMap();
Iterator iter = root.getAugmentationList().iterator();
while (iter.hasNext()) {
AugmentationFormula formula = (AugmentationFormula) iter.next();
List formulaVerbList = createVerbList(root, formula.getFormulaNo());
result.put(formula.getFormulaNo()+"", formulaVerbList);
}
return result;
}
}
| 35.95082 | 141 | 0.663475 |
f62efe84b24a7c5dbe051ea8c34bc4fd4dd9c716 | 332 | package ru.job4j.servlets.logic;
import ru.job4j.servlets.datamodel.User;
import java.util.Map;
public interface Validate {
User add(User user);
void update(int id, User user);
boolean delete(int id);
Map<Integer, User> findAll();
User findById(int id);
int isCredential(String login, String password);
}
| 22.133333 | 52 | 0.707831 |
2587bd6c8d82229d4a9aa3487f2262e2c2a5d3e1 | 386 | package dao;
import model.Role;
import org.apache.ibatis.annotations.*;
public interface RoleDao {
@Select("select * from tb_role where id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "roleMenu", column = "id", many = @Many(select = "dao.RoleMenuDao.getRoleMenuByRoleId"))
})
Role getRoleById(Integer id);
}
| 27.571429 | 119 | 0.629534 |
5b37cfc55951c32d0fb9fd5f3e96fe6bd1d8614a | 2,091 | // Christopher Diep
package edu.sdccd.cisc191.GameEntities;
public class Combatant extends Entity {
private int maxHealth;
private int health;
private int attack;
private int defense;
private int speed;
private boolean isDefending;
public Combatant() {
super();
maxHealth = 0;
health = 0;
attack = 0;
defense = 0;
speed = 0;
isDefending = false;
}
public Combatant(String name) {
super(name);
maxHealth = 0;
this.health = 0;
this.attack = 0;
this.defense = 0;
this.speed = 0;
isDefending = false;
}
public int getMaxHealth() {
return maxHealth;
}
public int getHealth() {
return health;
}
public int getAttack() {
return attack;
}
public int getDefense() {
if(isDefending) {
return defense * 2;
}
return defense;
}
public int getSpeed() {
return speed;
}
public void setMaxHealth(int maxHealth) {
this.maxHealth = maxHealth;
}
public void setHealth(int health) {
this.health = health;
if(health > maxHealth)
this.health = maxHealth;
}
public void setAttack(int attack) {
this.attack = attack;
}
public void setDefense(int defense) {
this.defense = defense;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void takeDamage(int damage) {
health -= damage;
if(health < 0) {
health = 0;
}
}
public void defendAction() {
isDefending = true;
}
public int attack(int range) {
int min, max;
min = getAttack(); //Character's attack with the very lowest the damage can do.
max = getAttack() + range; //Character's attack with the maximum the damage can do
return (int) ((Math.random() * ((max) - min)) + min);
}
}
| 22.010526 | 92 | 0.522716 |
0aa0505c2ebeb8c2e5158fea08bb176e87c39a3f | 325 | package softuni.exam.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import softuni.exam.models.entities.Picture;
import java.util.List;
public interface PictureRepository extends JpaRepository<Picture, Long> {
Picture findByName(String name);
List<Picture> findByCar_Id(Long id);
}
| 19.117647 | 73 | 0.790769 |
d6521708005df334316c74594ccf17a9fffc7afd | 3,283 | /*
* Copyright (c) 2013-2017 Cinchapi Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cinchapi.concourse.util;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.annotation.concurrent.ThreadSafe;
import com.google.common.base.Throwables;
/**
* A {@link ConcurrentLinkedQueue} that uses a specified supplier
* {@link Callable} to dynamically load elements into the queue when a read
* request is made and the queue is empty.
*
* @author Jeff Nelson
*/
@ThreadSafe
public class ConcurrentLoadingQueue<E> extends ConcurrentLinkedQueue<E> {
/**
* Return a new {@link ConcurrentLoadingQueue} that uses the
* {@code supplier} to populate the queue on demand.
*
* @param supplier
* @return the ConcurrentLoadingQueue
*/
public static <E> ConcurrentLoadingQueue<E> create(Callable<E> supplier) {
return new ConcurrentLoadingQueue<E>(supplier);
}
/**
* Return a new {@link ConcurrentLoadingQueue} that initially contains the
* elements of the given {@code collection} in traversal order of the
* collection's iterator and uses the {@code supplier} to populate the queue
* on demand.
*
* @param collection
* @param supplier
* @return the ConcurrentLoadingQueue
*/
public static <E> ConcurrentLoadingQueue<E> create(
Collection<E> collection, Callable<E> supplier) {
ConcurrentLoadingQueue<E> queue = create(supplier);
for (E element : collection) {
queue.offer(element);
}
return queue;
}
private static final long serialVersionUID = 1L;
/**
* The function that supplies elements to the queue when it is empty.
*/
private final Callable<E> supplier;
/**
* Construct a new instance.
*
* @param supplier
*/
private ConcurrentLoadingQueue(Callable<E> supplier) {
this.supplier = supplier;
}
@Override
public E peek() {
E element = super.peek();
if(element == null) {
loadElement();
return super.peek();
}
else {
return element;
}
}
@Override
public E poll() {
E element = super.poll();
if(element == null) {
loadElement();
return super.poll();
}
else {
return element;
}
}
/**
* Load a new element and place it into the queue.
*/
private void loadElement() {
try {
E element = supplier.call();
offer(element);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
| 27.358333 | 80 | 0.628084 |
6200dd840b542e00a2d42af2f32917e00f1a6b37 | 649 | package rock_paper_scissors_be.game_list;
import java.util.ArrayList;
public class GameListings {
ArrayList<Game> gameList = new ArrayList<Game>();
public boolean addGameToList(Game game){
return gameList.add(game);
}
public Game getGameByGameID(int gameID){
for (Game game: gameList) {
if(game.getGameID() == gameID)
return game;
}
return null;
}
public boolean removeGameFromList(int gameID){
for (Game game: gameList) {
if(game.getGameID() == gameID)
return gameList.remove(game);
}
return false;
}
}
| 23.178571 | 53 | 0.59322 |
35561ea5c9c559c508f69624d8596b95f085f427 | 356 | package net.rizon.moo.events;
import net.rizon.moo.Event;
public class EventWallops extends Event
{
private final String source, message;
public EventWallops(String source, String message)
{
this.source = source;
this.message = message;
}
public String getSource()
{
return source;
}
public String getMessage()
{
return message;
}
}
| 14.24 | 51 | 0.72191 |
b666144e389a068585a2420d88b2905c7b80a267 | 2,059 | package AddAndSearchWord_DSDesign_211;
/**
* Design a data structure that supports the following two operations:
*
* void addWord(word)
* bool search(word)
* search(word) can search a literal word or a regular expression
* string containing only letters a-z or .
* A . means it can represent any one letter.
*
* For example:
* addWord("bad")
* addWord("dad")
* addWord("mad")
* search("pad") -> false
* search("bad") -> true
* search(".ad") -> true
* search("b..") -> true
* Note:
* You may assume that all words are consist of lowercase letters a-z.
*
* You should be familiar with how a Trie works.
* If not, please work on this problem: Implement Trie (Prefix Tree) first.
*/
public class WordDictionary {
private Node root = new Node();
/** Initialize your data structure here. */
public WordDictionary(){}
/** Adds a word into the data structure. */
public void addWord(String word) {
Node cur = root;
char[] s = word.toCharArray();
int pointer = 0;
while(pointer<s.length){
int key = s[pointer++]-'a';
if(cur.children[key]==null) cur.children[key] = new Node();
cur = cur.children[key];
}
cur.str = true;
}
/** Returns if the word is in the data structure.
* A word could contain the dot character '.' to represent any one letter. */
public boolean search2(String word) {
return dfs(root,word.toCharArray(),-1);
}
// Recursive solution
private boolean dfs(Node root,char[] s,int cur){
if(root==null) return false;
if(cur==s.length-1) return root.str;
char key = s[cur+1];
if(key=='.'){
for(int i=0;i<26;i++)
if(root.children[i]!=null&&dfs(root.children[i],s,cur+1))
return true;
return false;
}else{
return dfs(root.children[key-'a'],s,cur+1);
}
}
class Node{
Node[] children = new Node[26];
boolean str = false;
Node(){}
}
}
| 28.205479 | 82 | 0.58135 |
7956d3dfc561e5f36dcf2d40ca896f03d31bcb22 | 1,663 | package es.pablolopez.InventoryJetPack.layout.base;
import android.app.Dialog;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import es.pablolopez.InventoryJetPack.R;
public class BaseDialogFragment extends DialogFragment {
public static final String TITLE = "title";
public static final String MESSAGE= "message";
public static final String TAG = "BaseDialogFragment";
private OnBaseDialogListener fragmentListener;
public static BaseDialogFragment getInstance(Bundle b){
BaseDialogFragment baseDialogFragment = new BaseDialogFragment();
if (b != null){
baseDialogFragment.setArguments(b);
}
return baseDialogFragment;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
fragmentListener = (OnBaseDialogListener) getTargetFragment();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setTitle(getArguments().getString(TITLE));
alertDialog.setMessage(getArguments().getString(MESSAGE));
alertDialog.setPositiveButton(getString(android.R.string.yes), (dialog, which) -> fragmentListener.onAccept());
alertDialog.setNegativeButton(getString(android.R.string.no), (dialog, which) -> fragmentListener.onCancel());
alertDialog.setIcon(R.drawable.ic_action_warning);
return alertDialog.create();
}
public interface OnBaseDialogListener{
void onAccept();
void onCancel();
}
}
| 35.382979 | 119 | 0.733013 |
25aa0c3ecac7ca0d4a70b3f5d8e224e60c8da735 | 259 | package authoring.interfaces;
/**
* An interface implemented by objects that can be updated.
*
* @author Aditya Srinivasan, Arjun Desai, Nick Lockett, Harry Guo
*
*/
public interface Updatable {
/**
* Execute on update.
*/
void update();
}
| 15.235294 | 66 | 0.667954 |
9a12cad98cacaedcc9e094aa60a89b4d393ffaa2 | 14,917 | /*
* Copyright (c) 2017 - 2020 K.Misaki
*
* 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.mickey305.foundation.v4.lang.math;
import com.mickey305.foundation.v3.util.Assert;
import com.mickey305.foundation.v4.lang.math.operator.AbstractNumberOperation;
import com.mickey305.foundation.v4.lang.math.operator.IElementInitializer;
import org.apache.commons.lang3.tuple.Triple;
import java.util.Map;
import java.util.Set;
/**
* 行列演算用クラスです
* @param <E> 行列の要素の総称型です
*/
public class Matrix<E extends Number> extends AbstractNumberTable<E> {
private static final long serialVersionUID = -7165282387150597347L;
public Matrix(int row, int column,
IElementInitializer<E> initializer,
Map<Operator, AbstractNumberOperation<E, E>> op,
Map<RelationalOperator, AbstractNumberOperation<E, Boolean>> rop) {
super(row, column, initializer, op, rop);
}
public Matrix(E[][] initialTable,
IElementInitializer<E> initializer,
Map<Operator, AbstractNumberOperation<E, E>> op,
Map<RelationalOperator, AbstractNumberOperation<E, Boolean>> rop) {
super(initialTable, initializer, op, rop);
}
public Matrix(Matrix<E> matrix) {
this(matrix.getTable(), matrix.getInitializer(), matrix.getOp(), matrix.getRop());
}
public Matrix(E scalar,
IElementInitializer<E> initializer,
Map<Operator, AbstractNumberOperation<E, E>> op,
Map<RelationalOperator, AbstractNumberOperation<E, Boolean>> rop) {
super(scalar, initializer, op, rop);
}
/**
* 加算処理
*
* @param rightMatrix 右行列
* @return 演算結果行列
*/
public Matrix<E> add(Matrix<E> rightMatrix) {
return Matrix.simplyOperate(this, rightMatrix, Operator.Add);
}
/**
* 減算処理
*
* @param rightMatrix 右行列
* @return 演算結果行列
*/
public Matrix<E> sub(Matrix<E> rightMatrix) {
return Matrix.simplyOperate(this, rightMatrix, Operator.Sub);
}
/**
* 乗算処理
*
* @param scalar スカラー
* @return 演算結果行列
*/
public Matrix<E> multi(E scalar) {
E resultCell;
final Matrix<E> R = new Matrix<>(this);
for (int i = 0; i < this.getRowSize(); i++) {
for (int j = 0; j < this.getColumnSize(); j++) {
resultCell = R.getOp(Operator.Multi).apply(this.getCell(i, j), scalar);
R.putCell(i, j, resultCell);
}
}
return R;
}
/**
* 乗算処理
*
* @param rightMatrix 右行列
* @return 演算結果行列
*/
public Matrix<E> multi(Matrix<E> rightMatrix) {
if (this.getColumnSize() != rightMatrix.getRowSize()) {
throw new UnsupportedOperationException("multi-table-size-check failed. lhs-size=" + this.getColumnSize()
+ " rhs-size=" + rightMatrix.getRowSize());
}
final IElementInitializer<E> INI = this.getInitializer();
final Matrix<E> R = new Matrix<>(
INI.table(this.getRowSize(), rightMatrix.getColumnSize()),
INI, this.getOp(), this.getRop());
for (int i = 0; i < this.getRowSize(); i++) {
E[] leftRec = this.getRow(i);
for (int j = 0; j < rightMatrix.getColumnSize(); j++) {
E[] rightRec = rightMatrix.getColumn(j);
//assert leftRec.length == rightRec.length;
Assert.requireEquals(leftRec.length, rightRec.length);
E[] multiRec = INI.array(leftRec.length);
for (int k = 0; k < multiRec.length; k++)
multiRec[k] = this.getOp(Operator.Multi).apply(leftRec[k], rightRec[k]);
E resultCell = INI.zero();
for (E cell : multiRec)
resultCell = this.getOp(Operator.Add).apply(cell, resultCell);
R.putCell(i, j, resultCell);
}
}
return R;
}
/**
* 演算処理
*
* @param leftMatrix 左行列
* @param rightMatrix 右行列
* @param operator オペレータ
* @return 演算結果行列
*/
private static <E extends Number> Matrix<E> simplyOperate(Matrix<E> leftMatrix, Matrix<E> rightMatrix, Operator operator) {
if (leftMatrix.getRowSize() != rightMatrix.getRowSize()
|| leftMatrix.getColumnSize() != rightMatrix.getColumnSize()) {
throw new UnsupportedOperationException("operation-target-tableData-size-check failed.");
}
E resultCell;
final Matrix<E> R = new Matrix<>(leftMatrix);
for (int i = 0; i < leftMatrix.getRowSize(); i++) {
for (int j = 0; j < leftMatrix.getColumnSize(); j++) {
resultCell = leftMatrix.getOp(operator).apply(leftMatrix.getCell(i, j), rightMatrix.getCell(i, j));
R.putCell(i, j, resultCell);
}
}
return R;
}
/**
* べき乗処理
*
* @param index 指数(自然数)
* @return 演算結果行列
*/
public Matrix<E> exp(int index) {
if (index <= 0) {
throw new UnsupportedOperationException("exp-argument-check failed.");
}
Matrix<E> resultMatrix = this;
for (int i = 0; i < index - 1; i++)
resultMatrix = resultMatrix.multi(this);
return resultMatrix;
}
/**
* 水平連結
*
* @param r 右行列
* @return 連結行列
*/
public Matrix<E> horizontalBind(Matrix<E> r) {
if (this.getRowSize() != r.getRowSize()) {
throw new UnsupportedOperationException("bindData-size-check failed.");
}
final Matrix<E> R = new Matrix<>(
this.getRowSize(),
this.getColumnSize() + r.getColumnSize(),
this.getInitializer(), this.getOp(), this.getRop());
for (int i = 0; i < R.getRowSize(); i++) {
for (int j = 0; j < R.getColumnSize(); j++) {
Matrix<E> targetMatrix = r;
int jj = j - this.getColumnSize();
if (j < this.getColumnSize()) {
targetMatrix = this;
jj = j;
}
final E cell = targetMatrix.getCell(i, jj);
R.putCell(i, j, cell);
}
}
return R;
}
/**
* 垂直連結
*
* @param b 下行列
* @return 連結行列
*/
public Matrix<E> verticalBind(Matrix<E> b) {
if (this.getColumnSize() != b.getColumnSize()) {
throw new UnsupportedOperationException("bindData-size-check failed.");
}
final Matrix<E> R = new Matrix<>(
this.getRowSize() + b.getRowSize(),
this.getColumnSize(),
this.getInitializer(), this.getOp(), this.getRop());
for (int i = 0; i < R.getRowSize(); i++) {
Matrix<E> targetMatrix = b;
int ii = i - this.getRowSize();
if (i < this.getRowSize()) {
targetMatrix = this;
ii = i;
}
for (int j = 0; j < R.getColumnSize(); j++) {
final E cell = targetMatrix.getCell(ii, j);
R.putCell(i, j, cell);
}
}
return R;
}
/**
* 零行列取得メソッド
*
* @return 零行列
*/
public Matrix<E> createZeroMatrix() {
final Matrix<E> R = new Matrix<>(this);
for (int i = 0; i < this.getRowSize(); i++)
for (int j = 0; j < this.getColumnSize(); j++)
R.putCell(i, j, this.getInitializer().zero());
return R;
}
/**
* 2値行列取得メソッド
* <p>
* 行列内の要素を<code>0</code>と<code>1</code>の2値に変換する。
* <code>0</code>以下の数は<code>0</code>に、<code>0</code>を越える数は<code>1</code>に変換する。
* </p>
*
* @return 2値行列
*/
public Matrix<E> createLogicalMatrix() {
final Matrix<E> R = new Matrix<>(this);
final IElementInitializer<E> INI = this.getInitializer();
for (int i = 0; i < this.getRowSize(); i++) {
for (int j = 0; j < this.getColumnSize(); j++) {
final E cell = R.getCell(i, j);
R.putCell(i, j, this.getRop(RelationalOperator.LE).apply(cell, INI.zero())
? INI.zero()
: INI.one());
}
}
return R;
}
/**
* elementary transformation method - 1 (row method - 1)
*
* @param row1 swap target row number first
* @param row2 swap target row number second
* <p>
* {@inheritDoc}
*/
@Override
public void swapRow(int row1, int row2) {
E[] tmpRec = this.getRow(row1);
this.putRow(row1, this.getRow(row2));
this.putRow(row2, tmpRec);
}
/**
* elementary transformation method - 2 (column method - 1)
*
* @param column1 swap target column number first
* @param column2 swap target column number second
* <p>
* {@inheritDoc}
*/
@Override
public void swapColumn(int column1, int column2) {
E[] tmpRec = this.getColumn(column1);
this.putColumn(column1, this.getColumn(column2));
this.putColumn(column2, tmpRec);
}
/**
* elementary transformation method - 3 (row method - 2)
*
* @param scalar scalar value
* @param row target row number
* @return result
*/
public E[] multiRow(E scalar, int row) {
final IElementInitializer<E> INI = this.getInitializer();
final E[][] tmpTable = INI.table(1, this.getRow(row).length);
tmpTable[0] = this.getRow(row);
final Matrix<E> matrix = new Matrix<>(tmpTable, INI, this.getOp(), this.getRop());
final E[] rowData = matrix.multi(scalar).getRow(0);
this.putRow(row, rowData);
return rowData;
}
/**
* elementary transformation method - 4 (column method - 2)
*
* @param scalar scalar value
* @param column target column number
* @return result
*/
public E[] multiColumn(E scalar, int column) {
final IElementInitializer<E> INI = this.getInitializer();
final E[][] tmpTable = INI.table(1, this.getColumn(column).length);
tmpTable[0] = this.getColumn(column);
final Matrix<E> matrix = new Matrix<>(tmpTable, INI, this.getOp(), this.getRop());
final E[] columnData = matrix.multi(scalar).getRow(0);
this.putColumn(column, columnData);
return columnData;
}
/**
* elementary transformation method - 5 (row method - 3)
* <p>algorithm: matrix[addRow, i] += scalar * matrix[multiRow, i], (i = 0,1,2...n)</p>
*
* @param scalar scalar value
* @param multiRow multiply target row number
* @param addRow add target row number
*/
public void multiAndAddRow(E scalar, int multiRow, int addRow) {
Matrix<E> matrix;
final IElementInitializer<E> INI = this.getInitializer();
final E[][] tmpTable = INI.table(1, this.getRow(multiRow).length);
tmpTable[0] = this.getRow(multiRow);
matrix = new Matrix<>(tmpTable, INI, this.getOp(), this.getRop());
final Matrix<E> multiMatrix = matrix.multi(scalar);
tmpTable[0] = this.getRow(addRow);
matrix = new Matrix<>(tmpTable, INI, this.getOp(), this.getRop());
final Matrix<E> addMatrix = multiMatrix.add(matrix);
final E[] rowData = addMatrix.getRow(0);
this.putRow(addRow, rowData);
}
/**
* elementary transformation method - 6 (column method - 3)
* <p>algorithm: matrix[i, addColumn] += scalar * matrix[i, multiColumn], (i = 0,1,2...n)</p>
*
* @param scalar scalar value
* @param multiColumn multiply target column number
* @param addColumn add target column number
*/
public void multiAndAddColumn(E scalar, int multiColumn, int addColumn) {
Matrix<E> matrix;
final IElementInitializer<E> INI = this.getInitializer();
final E[][] tmpTable = INI.table(1, this.getColumn(multiColumn).length);
tmpTable[0] = this.getColumn(multiColumn);
matrix = new Matrix<>(tmpTable, INI, this.getOp(), this.getRop());
final Matrix<E> multiMatrix = matrix.multi(scalar);
tmpTable[0] = this.getColumn(addColumn);
matrix = new Matrix<>(tmpTable, INI, this.getOp(), this.getRop());
final Matrix<E> addMatrix = multiMatrix.add(matrix);
final E[] columnData = addMatrix.getRow(0);
this.putColumn(addColumn, columnData);
}
/**
* {@inheritDoc}
*/
@Override
protected void putRow(int row, E[] rowData) {
if (rowData.length != this.getColumnSize()) {
throw new IllegalArgumentException("rowData-size-check failed.");
}
int i = 0;
for (E cell : rowData)
this.putCell(row, i++, cell);
}
/**
* {@inheritDoc}
*/
@Override
protected void putColumn(int column, E[] columnData) {
if (columnData.length != this.getRowSize()) {
throw new IllegalArgumentException("columnData-size-check failed.");
}
int i = 0;
for (E cell : columnData)
this.putCell(i++, column, cell);
}
/**
* {@inheritDoc}
*/
@Override
public void putCell(int row, int column, E cell) {
this.getTable()[row][column] = cell;
}
/**
* セル更新メソッド
* <p>
* 更新対象行列番号のセルデータを更新データに置き換える。
* </p>
*
* @param point 更新データ
*/
private void putCell(Triple<Integer, Integer, E> point) {
this.putCell(point.getLeft(), point.getMiddle(), point.getRight());
}
/**
* セル更新メソッド
* <p>
* 更新対象行列番号のセルデータを更新データに置き換える。
* </p>
*
* @param points 更新データ
*/
public void putCells(Set<Triple<Integer, Integer, E>> points) {
for (Triple<Integer, Integer, E> point : points)
this.putCell(point);
}
/**
* 行合計
*
* @return 計算結果行列
*/
public Matrix<E> sumOfRow() {
final IElementInitializer<E> INI = this.getInitializer();
final E[] ary = this.sumArrayOfRow();
final E[][] table = INI.table(this.getRowSize(), 1);
for (int i = 0; i < this.getRowSize(); i++)
table[i][0] = ary[i];
return new Matrix<>(table, INI, this.getOp(), this.getRop());
}
/**
* 行平均
*
* @return 計算結果行列
*/
public Matrix<E> averageOfRow() {
final IElementInitializer<E> INI = this.getInitializer();
final E[] ary = this.averageArrayOfRow();
final E[][] table = INI.table(this.getRowSize(), 1);
for (int i = 0; i < this.getRowSize(); i++)
table[i][0] = ary[i];
return new Matrix<>(table, INI, this.getOp(), this.getRop());
}
/**
* 列合計
*
* @return 計算結果行列
*/
public Matrix<E> sumOfColumn() {
final IElementInitializer<E> INI = this.getInitializer();
final E[] ary = this.sumArrayOfColumn();
final E[][] table = INI.table(1, this.getColumnSize());
System.arraycopy(ary, 0, table[0], 0, this.getColumnSize());
return new Matrix<>(table, INI, this.getOp(), this.getRop());
}
/**
* 列平均
*
* @return 計算結果行列
*/
public Matrix<E> averageOfColumn() {
final IElementInitializer<E> INI = this.getInitializer();
final E[] ary = this.averageArrayOfColumn();
final E[][] table = INI.table(1, this.getColumnSize());
System.arraycopy(ary, 0, table[0], 0, this.getColumnSize());
return new Matrix<>(table, INI, this.getOp(), this.getRop());
}
}
| 29.774451 | 125 | 0.608165 |
15c07a4d5fd33ecc67eeca4f847b90858e64bd6c | 939 | package truedei;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
public class MyTest {
private static SqlSessionFactory sqlSessionFactory;
public static void main(String[] args) throws IOException {
//1、创建SqlSessionFactory
String resource = "mybatis-config.xml";
final Reader reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
//2、获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//3、获取mapper
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//4、执行数据库操作,并处理结果集
Student goods = mapper.selectById("1");
System.out.println(goods);
}
}
| 30.290323 | 71 | 0.736954 |
34b7ce977deb019197024e0229a6b956ae8a547d | 115 | package com.chesapeaketechnology.salute;
public class FileProvider extends androidx.core.content.FileProvider
{
}
| 19.166667 | 68 | 0.843478 |
dca84f14cda495d14eda548e81fcb00fac1ad37b | 1,266 | package tryan.inq.state;
import tryan.inq.mobility.QDirection;
import tryan.inq.mobility.QMoverSystem;
import tryan.inq.mobility.QMoverType;
public class QPlayerState extends QDynamicActorState implements QMoveable, QControllable {
public QPlayerState(int x, int y, int width, int height, int speed, int id) {
super(x, y, width, height, speed, id);
attachMoverSystem(new QMoverSystem(this));
}
@Override
public void onCommand(long tickTime, QDirection direction) {}
@Override
public void move(QDirection direction) {}
public void walk(QDirection direction) {
if(getMoverSystem().move(QMoverType.WALK ,direction)) {
setCurrentAnimState(QAnimState.WALK);
}
}
public void jump(QDirection direction) {
if(getMoverSystem().move(QMoverType.JUMP, direction)) {
setCurrentAnimState(QAnimState.JUMP);
}
}
@Override
public boolean fall() {
boolean isFalling = false;
if(getMoverSystem().getMoverModule(QMoverType.FALL) != null) {
if(getMoverSystem().move(QMoverType.FALL ,QDirection.S)) {
// Note: Could flag onGround here to reset double jump, etc
// Note: This doesn't work right now because animation states
isFalling = true;
setCurrentAnimState(QAnimState.FALL);
}
}
return isFalling;
}
}
| 25.836735 | 90 | 0.730648 |
d755ddb64d1c30d737b8a655c946f9adbfd16bc6 | 7,658 | /*
* Copyright 2018 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.fulltodo;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;
import io.realm.ObjectServerError;
import io.realm.PermissionManager;
import io.realm.Progress;
import io.realm.ProgressListener;
import io.realm.ProgressMode;
import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.SyncConfiguration;
import io.realm.SyncManager;
import io.realm.SyncSession;
import io.realm.SyncUser;
import io.realm.log.RealmLog;
import io.realm.permissions.Permission;
import io.realm.fulltodo.model.Project;
import io.realm.fulltodo.ui.ProjectsRecyclerAdapter;
public class ProjectsActivity extends AppCompatActivity {
private Realm realm;
private RecyclerView recyclerView;
private TextView statusView;
private PermissionManager pm;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_items);
setSupportActionBar(findViewById(R.id.toolbar));
recyclerView = findViewById(R.id.recycler_view);
statusView = findViewById(R.id.status);
findViewById(R.id.fab).setOnClickListener(view -> {
View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_task, null);
((EditText) dialogView.findViewById(R.id.task)).setHint(R.string.project_description);
EditText taskText = dialogView.findViewById(R.id.task);
new AlertDialog.Builder(ProjectsActivity.this)
.setTitle("Add a new project")
.setView(dialogView)
.setPositiveButton("Add", (dialog, which) -> {
String projectName = taskText.getText().toString();
if (!isValidProjectName(projectName)) {
Toast.makeText(ProjectsActivity.this, "Invalid project name. It must only contain " +
"the characters a-z and 0-9", Toast.LENGTH_SHORT).show();
} else {
String path = "/~/project-" + projectName;
String url = Constants.REALM_URL + path;
SyncConfiguration config = SyncUser.current().createConfiguration(url)
.fullSynchronization()
.initialData(realm -> {
Project project = new Project();
String userId = SyncUser.current().getIdentity();
String name = taskText.getText().toString();
project.setOwner(userId);
project.setName(name);
project.setTimestamp(new Date());
realm.insert(project);
})
.build();
RealmLog.info("Connecting to " + config.getServerUrl().toString());
Realm.getInstanceAsync(config, new Realm.Callback() {
@Override
public void onSuccess(Realm realm) {
SyncSession session = SyncManager.getSession((SyncConfiguration) realm.getConfiguration());
session.addUploadProgressListener(ProgressMode.CURRENT_CHANGES, new ProgressListener() {
@Override
public void onChange(Progress progress) {
if (progress.isTransferComplete()) {
session.removeProgressListener(this);
runOnUiThread(() -> realm.close());
}
}
});
}
});
}
})
.setNegativeButton("Cancel", null)
.create()
.show();
});
// Using the current SyncUser identity, we create a subscription for projects created by that user.
setStatus("Loading...");
pm = SyncUser.current().getPermissionManager();
pm.getPermissions(new PermissionManager.PermissionsCallback() {
@Override
public void onSuccess(RealmResults<Permission> permissions) {
RealmResults<Permission> filteredPermissions = permissions.where().contains("path", "/project-").findAllAsync();
final ProjectsRecyclerAdapter itemsRecyclerAdapter = new ProjectsRecyclerAdapter(ProjectsActivity.this, filteredPermissions);
recyclerView.setLayoutManager(new LinearLayoutManager(ProjectsActivity.this));
recyclerView.setAdapter(itemsRecyclerAdapter);
if (permissions.isEmpty()) {
setStatus("Press + to add a new project");
} else {
setStatus("");
}
}
@Override
public void onError(ObjectServerError error) {
showMessage(error.getErrorMessage());
}
});
}
private boolean isValidProjectName(String projectName) {
return projectName.matches("[a-z0-9]*");
}
private void setStatus(String str) {
statusView.setText(str);
}
private void showMessage(String msg) {
Toast.makeText(ProjectsActivity.this, msg, Toast.LENGTH_LONG).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
pm.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_items, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_logout) {
SyncUser syncUser = SyncUser.current();
if (syncUser != null) {
syncUser.logOut();
Intent intent = new Intent(this, WelcomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 41.846995 | 141 | 0.574171 |
14b3d05ca76ea5275c784b76ff326372bc1273bc | 2,811 | /*
* 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.geode.management.internal.web.controllers;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.geode.internal.lang.SystemUtils;
import org.apache.geode.internal.util.IOUtils;
import org.springframework.web.multipart.MultipartFile;
/**
* The AbstractMultiPartCommandsController class is a abstract base class encapsulating all common
* functionality for handling multi-part (file upload) HTTP requests.
* <p/>
*
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @since GemFire 8.0
*/
@SuppressWarnings("unused")
public class AbstractMultiPartCommandsController extends AbstractCommandsController {
protected static final String RESOURCES_REQUEST_PARAMETER = "resources";
/**
* Saves an array of File objects to this system's file system.
* <p/>
*
* @param files an array of MultipartFile objects to persist to the file system.
* @throws IOException if I/O error occurs while saving the Files to the file system.
* @see org.springframework.web.multipart.MultipartFile
*/
protected static void save(final MultipartFile... files) throws IOException {
if (files != null) {
for (final MultipartFile file : files) {
save(file);
}
}
}
/**
* Saves a multi-part File to this system's file system.
* <p/>
*
* @param file the MultipartFile object to persist to the file system.
* @throws IOException if I/O error occurs while saving the File to the file system.
* @see org.springframework.web.multipart.MultipartFile
*/
protected static void save(final MultipartFile file) throws IOException {
final File saveFile = new File(SystemUtils.CURRENT_DIRECTORY, file.getOriginalFilename());
FileOutputStream fileWriter = null;
try {
fileWriter = new FileOutputStream(saveFile, false);
fileWriter.write(file.getBytes());
fileWriter.flush();
} finally {
IOUtils.close(fileWriter);
}
}
}
| 36.038462 | 100 | 0.739594 |
c2bf3329495fc7a8eb6b531c84cd456e7a843738 | 2,953 | package com.manywho.services.mdm.actions.mdmplatform.getGoldenRecordForSourceEntity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.dom4j.Node;
import com.manywho.sdk.api.ContentType;
import com.manywho.sdk.services.types.Type;
//<mdm:Record endDate="02-05-2014T11:33:27.000-0400" updatedDate="02-05-2014T08:44:47.000-0400" createdDate="04-23-2012T14:30:26.000-0400"
//recordId="d5742c16-5318-4ba7-8815-3267a7a55358" xmlns:mdm="http://mdm.api.platform.boomi.com/"
//xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
// <mdm:data>
// <contact>
// <id>d5742c16-5318-4ba7-8815-3267a7a55358</id>
// <name>bob</name>
// <city>berwyn</city>
// <email>bob@gmail.com</email>
// </contact>
// </mdm:data>
//</mdm:Record>
@Type.Element(name = "GoldenRecord")
public class GoldenRecord implements Type{
@Type.Identifier
private String guid;
@Type.Property(name = "End Date", contentType = ContentType.DateTime)
private Date endDate;
@Type.Property(name = "Created Date", contentType = ContentType.DateTime)
private Date createdDate;
@Type.Property(name = "Updated Date", contentType = ContentType.DateTime)
private Date updatedDate;
@Type.Property(name = "Record ID", contentType = ContentType.String)
private String recordId;
@Type.Property(name = "Data", contentType = ContentType.String)
private String data;
public GoldenRecord()
{
}
public GoldenRecord(Node document)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
document = document.selectSingleNode("mdm:Record");
this.guid=UUID.randomUUID().toString();
try {
Node date = document.selectSingleNode("@createdDate");
if (date!=null)
this.createdDate = sdf.parse(date.getText());
} catch (ParseException e) {
throw new RuntimeException(e);
}
try {
Node date = document.selectSingleNode("@endDate");
if (date!=null)
this.endDate = sdf.parse(date.getText());
} catch (ParseException e) {
throw new RuntimeException(e);
}
try {
Node date = document.selectSingleNode("@updatedDate");
if (date!=null)
this.updatedDate = sdf.parse(date.getText());
} catch (ParseException e) {
throw new RuntimeException(e);
}
this.recordId = document.selectSingleNode("@recordId").getText();
this.data = document.selectSingleNode("mdm:data").selectSingleNode("*").asXML();
}
public String getGuid() {
return guid;
}
public Date getEndDate() {
return endDate;
}
public Date getCreatedDate() {
return createdDate;
}
public Date getUpdatedDate() {
return updatedDate;
}
public String getRecordId() {
return recordId;
}
public String getData() {
return data;
}
}
| 27.342593 | 140 | 0.681002 |
e94f142896680e32b78c114a69a53f252529aad6 | 2,640 | package com.mero.wyt_register.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.mero.wyt_register.MainActivity;
import com.mero.wyt_register.R;
import com.mero.wyt_register.adapter.ViewPagerAdapter;
/**
*@项目名称: 简易通注册助手
*@文件名称: GuideCty.java
*@Date: 2016-7-15
*@Copyright: 2016 Technology Mero Inc. All rights reserved.
*注意:由Mero开发,禁止外泄以及使用本程序于其他的商业目的 。
*/
public class GuideAty extends Activity implements OnPageChangeListener{
private List<View> views;
private int ids[] = {R.id.iv1,R.id.iv2,R.id.iv3};//3个导航点
private ImageView dots[];
private ImageButton go;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private View view1,view2,view3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.guide_view_page);
init();
initDots();
}
private void init() {
LayoutInflater inflater=LayoutInflater.from(this);
views = new ArrayList<View>();
view1 = inflater.inflate(R.layout.viewpager_01, null);//实例化3个view
view2 = inflater.inflate(R.layout.viewpager_02, null);
view3 = inflater.inflate(R.layout.viewpager_03, null);
views.add(view1);
views.add(view2);
views.add(view3);
viewPagerAdapter = new ViewPagerAdapter(this, views);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(viewPagerAdapter);
go = (ImageButton) views.get(2).findViewById(R.id.go);
go.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GuideAty.this,MainActivity.class);
startActivity(intent);
finish();
}
});
viewPager.setOnPageChangeListener(this);
}
private void initDots() {
dots = new ImageView[views.size()];
for(int i=0;i<dots.length;i++){
dots[i] = (ImageView) findViewById(ids[i]);
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int position) {
for(int i = 0;i<ids.length;i++){
if(position==i){
dots[i].setImageResource(R.drawable.dot_selected_shape);
}else{
dots[i].setImageResource(R.drawable.dot_no_selected_shape);
}
}
}
}
| 25.882353 | 71 | 0.741667 |
75585076e49315b8386d51fea50d3a312db363ab | 713 | package com.steel9.MCAlerty;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
public class MyListener implements Listener {
private Plugin mPlugin;
public MyListener(Plugin plugin) {
mPlugin = plugin;
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
String msg = Main.getAlertsString(event.getPlayer().getUniqueId(), "Welcome!", true);
if (!msg.equalsIgnoreCase("")) {
event.getPlayer().sendMessage(msg);
//Main.updateAlertsRead(mPlugin, event.getPlayer().getUniqueId());
}
}
}
| 26.407407 | 93 | 0.692847 |
1b3a6c2ff2ed8d0d2b1eb620e31c9e5a89e8638d | 2,263 | package com.me.map;
import java.util.HashMap;
import java.util.Map;
/**
* 请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
* 实现 LRUCache 类:
* LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存
* int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
* void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
* 函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/lru-cache
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author qiankun
* @version 2021/12/28
*/
public class LRUCache {
private int capacity;
Map<Integer, DataNode> map = new HashMap<>();
DataNode head, tail;
public LRUCache(int capacity) {
this.capacity = capacity;
head = new DataNode(-1, -1);
tail = new DataNode(-1, -1);
tail.pre = tail.next = head;
head.pre = head.next = tail;
}
public int get(int key) {
DataNode dataNode = map.get(key);
if (dataNode == null) {
return -1;
}
moveToHead(dataNode);
return dataNode.val;
}
public void put(int key, int value) {
if (map.get(key) != null) {
map.get(key).val = value;
DataNode dataNode = map.get(key);
moveToHead(dataNode);
} else {
if (capacity == 0) { //清理tail的数据
map.put(tail.pre.key, null);
removeFromTail();
}
DataNode dataNode = new DataNode(key, value);
addToHead(dataNode);
if (capacity > 0) {
capacity--;
}
map.put(key, dataNode);
}
}
public void removeNode(DataNode dataNode) {
dataNode.pre.next = dataNode.next;
dataNode.next.pre = dataNode.pre;
}
public void addToHead(DataNode dataNode) {
dataNode.next = head.next;
dataNode.pre = head;
head.next.pre = dataNode;
head.next = dataNode;
}
public void removeFromTail() {
DataNode temp = tail.pre.pre;
temp.next = tail;
tail.pre = temp;
}
private void moveToHead(DataNode node) {
removeNode(node);
addToHead(node);
}
}
| 24.074468 | 132 | 0.566063 |
72db43711dbbf9a0f2114fe2af19d880022782dc | 2,031 | /*
* Copyright 2005 FBK-irst (http://www.fbk.eu)
*
* 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.itc.irst.tcc.sre.data;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TO DO
*
* @author Claudio Giuliano
* @version %I%, %G%
* @since 1.0
*/
public class InputFormatConverter {
static Logger logger = LoggerFactory.getLogger(InputFormatConverter.class
.getName());
public InputFormatConverter(File in) {
logger.debug("InputFormatConverter.InputFormatConverter: " + in);
try {
LineNumberReader lnr = new LineNumberReader(new FileReader(in));
String s;
while ((s = lnr.readLine()) != null) {
String[] fld = s.split("\t");
} // end while
lnr.close();
} catch (IOException e) {
logger.error("", e);
}
} // end constructor
// //
// public static void main(String args[]) throws Exception
// {
// String logConfig = System.getProperty("log-config");
// if (logConfig == null)
// logConfig = "log-config.txt";
//
// PropertyConfigurator.configure(logConfig);
//
// if (args.length != 1)
// {
// System.err.println("java -mx512M org.itc.irst.tcc.sre.data.SenteceShuffler in");
// System.exit(-1);
// }
//
//
// } // end main
} // end class InputFormatConverter
| 27.08 | 87 | 0.630724 |
a4e2bddfdf0b98b9dec14d134aef91b61b46847a | 2,027 | /*
* 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.sling.launchpad.webapp.integrationtest.servlets.resolution;
import java.util.Collections;
import org.apache.commons.httpclient.NameValuePair;
/**
* Test that a servlet registered at a particular path is still executed when a
* node at that path also exists.
*/
public class PathsServletWithNodeTest extends ResolutionTestBase {
private final static String NODE_SERVLET_URL = HTTP_BASE_URL + "/testing/PathsServletNodeServlet";
private final static String TEST_URL = HTTP_BASE_URL + "/testing/PathsServlet/foo";
@Override
protected void setUp() throws Exception {
super.setUp();
assertPostStatus(NODE_SERVLET_URL, 201, Collections.singletonList(new NameValuePair("action", "create")),
"Unable to create node at " + TEST_PATH);
}
public void testGetCorrectPath() throws Exception {
assertServlet(getContent(TEST_URL, CONTENT_TYPE_PLAIN), PATHS_SERVLET_SUFFIX);
}
@Override
protected void tearDown() throws Exception {
assertPostStatus(NODE_SERVLET_URL, 204, Collections.singletonList(new NameValuePair("action", "delete")),
"Unable to delete node at " + TEST_PATH);
super.tearDown();
}
}
| 38.980769 | 113 | 0.737543 |
e494e475d208d54d34c49f6ca8cdd1144d295f61 | 765 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package milicia;
/**
*
* @author Maiekel Vela
*/
public class UnionAmbas {
public Cuartel cuartel;
public Compania compania;
public UnionAmbas(Cuartel cuartel, Compania compania) {
this.cuartel = cuartel;
this.compania = compania;
}
public void setCuartel(Cuartel cuartel) {
this.cuartel = cuartel;
}
public void setCompania(Compania compania) {
this.compania = compania;
}
public Cuartel getCuartel() {
return cuartel;
}
public Compania getCompania() {
return compania;
}
}
| 20.675676 | 79 | 0.652288 |
643b484e43c617dbbf452dcd192eaf36823d75ed | 500 | package softuni.winelovers.data.repositories.shop;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import softuni.winelovers.data.models.shop.Address;
import java.util.Optional;
@Repository
public interface AddressRepository extends JpaRepository<Address, String> {
Optional<Address> findByCountryAndCityAndStreetAndNumber(String country, String city, String street, String number);
Optional<Address> findById(String id);
}
| 33.333333 | 120 | 0.828 |
e41a10a685f2d5a72b67393ffda29c556992d4b8 | 1,238 | // This is a generated file. Not intended for manual editing.
package com.jivesoftware.robot.intellij.plugin.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.jivesoftware.robot.intellij.plugin.parser.RobotTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.jivesoftware.robot.intellij.plugin.psi.*;
import com.jivesoftware.robot.intellij.plugin.elements.RobotImplUtil;
public class RobotMultiAssignmentLhsImpl extends ASTWrapperPsiElement implements RobotMultiAssignmentLhs {
public RobotMultiAssignmentLhsImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof RobotVisitor) ((RobotVisitor)visitor).visitMultiAssignmentLhs(this);
else super.accept(visitor);
}
@Override
@Nullable
public RobotAssignment getAssignment() {
return findChildByClass(RobotAssignment.class);
}
@Override
@NotNull
public List<RobotVariable> getVariableList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, RobotVariable.class);
}
}
| 31.74359 | 106 | 0.798061 |
0488a679eadb3bd3219d54d1a1238c6f604d26bb | 3,682 | /*! ******************************************************************************
*
* Hop : The Hop Orchestration Platform
*
* http://www.project-hop.org
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.apache.hop.ui.core.widget;
import org.apache.hop.ui.core.PropsUi;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* Adds a line of text with a label and a variable to a composite (like a dialog shell)
*
* @author Matt
* @since 17-may-2006
*/
public class LabelText extends Composite {
private static final PropsUi props = PropsUi.getInstance();
private Label wLabel;
private Text wText;
public LabelText( Composite composite, String labelText, String toolTipText ) {
this(
composite, SWT.SINGLE | SWT.LEFT | SWT.BORDER, labelText, toolTipText, props.getMiddlePct(), props.getMargin() );
}
public LabelText( Composite composite, String labelText, String toolTipText, int middle, int margin ) {
this( composite, SWT.SINGLE | SWT.LEFT | SWT.BORDER, labelText, toolTipText, middle, margin );
}
public LabelText( Composite composite, int textStyle, String labelText, String toolTipText, int middle,
int margin ) {
super( composite, SWT.NONE );
props.setLook( this );
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 0;
formLayout.marginHeight = 0;
this.setLayout( formLayout );
wText = new Text( this, textStyle );
FormData fdText = new FormData();
fdText.left = new FormAttachment( middle, margin );
fdText.right = new FormAttachment( 100, 0 );
wText.setLayoutData( fdText );
wText.setToolTipText( toolTipText );
wLabel = new Label( this, SWT.RIGHT );
props.setLook( wLabel );
wLabel.setText( labelText );
FormData fdLabel = new FormData();
fdLabel.left = new FormAttachment( 0, 0 );
fdLabel.right = new FormAttachment( middle, 0 );
fdLabel.top = new FormAttachment( wText, 0, SWT.CENTER );
wLabel.setLayoutData( fdLabel );
wLabel.setToolTipText( toolTipText );
}
public String getText() {
return wText.getText();
}
public void setText( String string ) {
wText.setText( string );
}
public Text getTextWidget() {
return wText;
}
public void addModifyListener( ModifyListener lsMod ) {
wText.addModifyListener( lsMod );
}
public void addSelectionListener( SelectionListener lsDef ) {
wText.addSelectionListener( lsDef );
}
public void setEnabled( boolean flag ) {
wText.setEnabled( flag );
wLabel.setEnabled( flag );
}
public void selectAll() {
wText.selectAll();
}
public boolean setFocus() {
return wText.setFocus();
}
}
| 31.20339 | 119 | 0.659696 |
3d2630331a018c4f529da5270b08d6f77b9276e1 | 3,352 | /*******************************************************************************
* Copyright (c) 2014 Chaupal.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0.html
*******************************************************************************/
package org.chaupal.jp2p.ui.jxta.property;
import net.jp2p.container.IJp2pContainer;
import net.jxta.document.Advertisement;
import net.jxta.peergroup.PeerGroup;
import net.jxta.platform.NetworkConfigurator;
import net.jxta.platform.NetworkManager;
import net.jxta.rendezvous.RendezVousService;
import org.chaupal.jp2p.ui.adapter.Jp2pAdapterFactory;
import org.chaupal.jp2p.ui.jxta.advertisement.property.AdvertisementPropertySource;
import org.chaupal.jp2p.ui.jxta.network.NetworkManagerPropertySource;
import org.chaupal.jp2p.ui.jxta.network.configurator.NetworkConfiguratorPropertySource;
import org.chaupal.jp2p.ui.jxta.peergroup.PeerGroupUIPropertySource;
import org.chaupal.jp2p.ui.jxta.rendezvous.RendezVousUIPropertySource;
import org.chaupal.jp2p.ui.property.SimpleUIPropertySource;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.ui.views.properties.IPropertySource;
public class Jp2pJxseAdapterFactory extends Jp2pAdapterFactory implements IAdapterFactory {
@SuppressWarnings({ "rawtypes" })
@Override
public Object getAdapter(Object adaptableObject, Class adapterType) {
if(adapterType != IPropertySource.class )
return null;
if( adaptableObject instanceof IJp2pContainer )
return this.getContainerPropertySource(( IJp2pContainer )adaptableObject );
IPropertySource source = this.getPropertySource(adaptableObject);
if( source != null )
return source;
return super.getAdapter(adaptableObject, adapterType);
}
/**
* Get the correct property source
* @param adaptableObject
* @return
*/
protected IPropertySource getPropertySource( Object adaptableObject ){
if( adaptableObject instanceof NetworkManager )
return new NetworkManagerPropertySource(( NetworkManager )adaptableObject );
if( adaptableObject instanceof NetworkConfigurator )
return new NetworkConfiguratorPropertySource(( NetworkConfigurator )adaptableObject);
if( adaptableObject instanceof Advertisement )
return new AdvertisementPropertySource(( Advertisement )adaptableObject);
if( adaptableObject instanceof PeerGroup )
return new PeerGroupUIPropertySource(( PeerGroup )adaptableObject);
if( adaptableObject instanceof RendezVousService )
return new RendezVousUIPropertySource( (RendezVousService) adaptableObject);
if( adaptableObject instanceof RendezVousService )
return new RendezVousUIPropertySource( (RendezVousService) adaptableObject);
return new SimpleUIPropertySource( adaptableObject );
}
/**
* Get the correct property source
* @param adaptableObject
* @return
*/
protected IPropertySource getContainerPropertySource( IJp2pContainer<?> component ){
Object module = component.getModule();
return this.getPropertySource( module );
}
@SuppressWarnings("rawtypes")
@Override
public Class[] getAdapterList() {
return new Class[]{IPropertySource.class };
}
}
| 41.9 | 91 | 0.755668 |
df724c47e80b5cb700434049435427ffda0830a8 | 4,961 | package com.nankai.exchange.biz.impl;
import java.util.ArrayList;
import java.util.List;
import com.nankai.exchange.biz.IMatchBiz;
import com.nankai.exchange.dao.IAudiosDao;
import com.nankai.exchange.dao.IBagsDao;
import com.nankai.exchange.dao.ICosmeticsDao;
import com.nankai.exchange.dao.IDailyprosDao;
import com.nankai.exchange.dao.IDecorationsDao;
import com.nankai.exchange.dao.IDigitsDao;
import com.nankai.exchange.dao.IElectricsDao;
import com.nankai.exchange.dao.IEntertainmentsDao;
import com.nankai.exchange.dao.IExtrabooksDao;
import com.nankai.exchange.dao.IFemalesDao;
import com.nankai.exchange.dao.IInstrumentsDao;
import com.nankai.exchange.dao.IMalesDao;
import com.nankai.exchange.dao.IOthersDao;
import com.nankai.exchange.dao.IPcDao;
import com.nankai.exchange.dao.IPhonesDao;
import com.nankai.exchange.dao.ISpprosDao;
import com.nankai.exchange.dao.ISptastsDao;
import com.nankai.exchange.dao.ISpteqptsDao;
import com.nankai.exchange.dao.ITextbooksDao;
import com.nankai.exchange.dao.IVirtualsDao;
import com.nankai.exchange.dao.impl.AudiosDaoImpl;
import com.nankai.exchange.dao.impl.BagsDaoImpl;
import com.nankai.exchange.dao.impl.CosmeticsDaoImpl;
import com.nankai.exchange.dao.impl.DailyprosDaoImpl;
import com.nankai.exchange.dao.impl.DecorationsDaoImpl;
import com.nankai.exchange.dao.impl.DigitsDaoImpl;
import com.nankai.exchange.dao.impl.ElectricsDaoImpl;
import com.nankai.exchange.dao.impl.EntertainmentsDaoImpl;
import com.nankai.exchange.dao.impl.ExtralbooksDaoImpl;
import com.nankai.exchange.dao.impl.FemalesDaoImpl;
import com.nankai.exchange.dao.impl.InstrumentsDaoImpl;
import com.nankai.exchange.dao.impl.MalesDaoImpl;
import com.nankai.exchange.dao.impl.OthersDaoImpl;
import com.nankai.exchange.dao.impl.PcDaoImpl;
import com.nankai.exchange.dao.impl.PhonesDaoImpl;
import com.nankai.exchange.dao.impl.SpprosDaoImpl;
import com.nankai.exchange.dao.impl.SptastsDaoImpl;
import com.nankai.exchange.dao.impl.SpteqptsDaoImpl;
import com.nankai.exchange.dao.impl.TextbooksDaoImpl;
import com.nankai.exchange.dao.impl.VirtualsDaoImpl;
public class MatchBizImpl implements IMatchBiz {
@Override
public List<List<?>> findMatch(String sexc, String iexcthing) {
// TODO Auto-generated method stub
List<List<?>> lstItems = new ArrayList<List<?>>();
switch(sexc) {
case "books":
// 图书:教科书、课外书、音像
ITextbooksDao textbooksDao = new TextbooksDaoImpl();
IExtrabooksDao extrabooksDao = new ExtralbooksDaoImpl();
IAudiosDao audiosDao = new AudiosDaoImpl();
lstItems.add(textbooksDao.selectByName(iexcthing));
lstItems.add(extrabooksDao.selectByName(iexcthing));
lstItems.add(audiosDao.selectByName(iexcthing));
break;
case "eles":
// 电子:电脑、手机、数码
IPcDao pcDao = new PcDaoImpl();
IPhonesDao phonesDao = new PhonesDaoImpl();
IDigitsDao digitsDao = new DigitsDaoImpl();
lstItems.add(pcDao.selectByName(iexcthing));
lstItems.add(phonesDao.selectByName(iexcthing));
lstItems.add(digitsDao.selectByName(iexcthing));
break;
case "spts":
// 体育:体育辅助、体育用品
ISptastsDao sptastsDao = new SptastsDaoImpl();
ISpteqptsDao spteqptsDao = new SpteqptsDaoImpl();
lstItems.add(sptastsDao.selectByName(iexcthing));
lstItems.add(spteqptsDao.selectByName(iexcthing));
break;
case "lifes":
// 生活:日常、电器、娱乐、化妆品、特产
IDailyprosDao dailyprosDao = new DailyprosDaoImpl();
IElectricsDao electricsDao = new ElectricsDaoImpl();
IEntertainmentsDao entertainmentsDao = new EntertainmentsDaoImpl();
ICosmeticsDao cosmeticsDao = new CosmeticsDaoImpl();
ISpprosDao spprosDao = new SpprosDaoImpl();
lstItems.add(dailyprosDao.selectByName(iexcthing));
lstItems.add(electricsDao.selectByName(iexcthing));
lstItems.add(entertainmentsDao.selectByName(iexcthing));
lstItems.add(cosmeticsDao.selectByName(iexcthing));
lstItems.add(spprosDao.selectByName(iexcthing));
break;
case "clothes":
// 服装
IFemalesDao femalesDao = new FemalesDaoImpl();
IMalesDao malesDao = new MalesDaoImpl();
lstItems.add(femalesDao.selectByName(iexcthing));
lstItems.add(malesDao.selectByName(iexcthing));
break;
case "decs":
// 饰品
IDecorationsDao decorationsDao = new DecorationsDaoImpl();
lstItems.add(decorationsDao.selectByName(iexcthing));
break;
case "bags":
// 箱包
IBagsDao bagsDao = new BagsDaoImpl();
lstItems.add(bagsDao.selectByName(iexcthing));
break;
case "ins":
// 乐器
IInstrumentsDao instrumentsDao = new InstrumentsDaoImpl();
lstItems.add(instrumentsDao.selectByName(iexcthing));
break;
case "vis":
// 虚拟
IVirtualsDao virtualsDao = new VirtualsDaoImpl();
lstItems.add(virtualsDao.selectByName(iexcthing));
break;
case "others":
// 其他
IOthersDao othersDao = new OthersDaoImpl();
lstItems.add(othersDao.selectByName(iexcthing));
break;
}
return lstItems;
}
}
| 31.201258 | 70 | 0.761137 |
4b658424742cb22b4c949fec4e9976ef2176ed41 | 7,370 | /*
* Copyright 2021 Google 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
*
* 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.google.api.servicecontrol.v1.stub;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.api.servicecontrol.v1.CheckRequest;
import com.google.api.servicecontrol.v1.CheckResponse;
import com.google.api.servicecontrol.v1.ReportRequest;
import com.google.api.servicecontrol.v1.ReportResponse;
import com.google.common.collect.ImmutableMap;
import com.google.longrunning.stub.GrpcOperationsStub;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC stub implementation for the ServiceController service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class GrpcServiceControllerStub extends ServiceControllerStub {
private static final MethodDescriptor<CheckRequest, CheckResponse> checkMethodDescriptor =
MethodDescriptor.<CheckRequest, CheckResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicecontrol.v1.ServiceController/Check")
.setRequestMarshaller(ProtoUtils.marshaller(CheckRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(CheckResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<ReportRequest, ReportResponse> reportMethodDescriptor =
MethodDescriptor.<ReportRequest, ReportResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicecontrol.v1.ServiceController/Report")
.setRequestMarshaller(ProtoUtils.marshaller(ReportRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(ReportResponse.getDefaultInstance()))
.build();
private final UnaryCallable<CheckRequest, CheckResponse> checkCallable;
private final UnaryCallable<ReportRequest, ReportResponse> reportCallable;
private final BackgroundResource backgroundResources;
private final GrpcOperationsStub operationsStub;
private final GrpcStubCallableFactory callableFactory;
public static final GrpcServiceControllerStub create(ServiceControllerStubSettings settings)
throws IOException {
return new GrpcServiceControllerStub(settings, ClientContext.create(settings));
}
public static final GrpcServiceControllerStub create(ClientContext clientContext)
throws IOException {
return new GrpcServiceControllerStub(
ServiceControllerStubSettings.newBuilder().build(), clientContext);
}
public static final GrpcServiceControllerStub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcServiceControllerStub(
ServiceControllerStubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of GrpcServiceControllerStub, using the given settings. This is
* protected so that it is easy to make a subclass, but otherwise, the static factory methods
* should be preferred.
*/
protected GrpcServiceControllerStub(
ServiceControllerStubSettings settings, ClientContext clientContext) throws IOException {
this(settings, clientContext, new GrpcServiceControllerCallableFactory());
}
/**
* Constructs an instance of GrpcServiceControllerStub, using the given settings. This is
* protected so that it is easy to make a subclass, but otherwise, the static factory methods
* should be preferred.
*/
protected GrpcServiceControllerStub(
ServiceControllerStubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<CheckRequest, CheckResponse> checkTransportSettings =
GrpcCallSettings.<CheckRequest, CheckResponse>newBuilder()
.setMethodDescriptor(checkMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("service_name", String.valueOf(request.getServiceName()));
return params.build();
})
.build();
GrpcCallSettings<ReportRequest, ReportResponse> reportTransportSettings =
GrpcCallSettings.<ReportRequest, ReportResponse>newBuilder()
.setMethodDescriptor(reportMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("service_name", String.valueOf(request.getServiceName()));
return params.build();
})
.build();
this.checkCallable =
callableFactory.createUnaryCallable(
checkTransportSettings, settings.checkSettings(), clientContext);
this.reportCallable =
callableFactory.createUnaryCallable(
reportTransportSettings, settings.reportSettings(), clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
@Override
public UnaryCallable<CheckRequest, CheckResponse> checkCallable() {
return checkCallable;
}
@Override
public UnaryCallable<ReportRequest, ReportResponse> reportCallable() {
return reportCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
| 38.789474 | 96 | 0.746133 |
18f43ddbc63d6b98f660eb42254d198efdb99c09 | 513 | package myservice.mynamespace.model;
import java.io.Serializable;
import javax.persistence.Column;
public class OrderDetailId implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "OrderID")
private int orderId;
@Column(name = "ProductID")
private int productId;
public OrderDetailId(){
super();
}
public OrderDetailId(int orderId, int productId) {
this.orderId = orderId;
this.productId = productId;
}
} | 19.730769 | 54 | 0.676413 |
35d159667d434511e3078bba1cb0f07e11e76298 | 2,720 | package com.flagsmith.flagengine.unit.segments;
import com.flagsmith.flagengine.identities.IdentityModel;
import com.flagsmith.flagengine.identities.traits.TraitModel;
import com.flagsmith.flagengine.segments.SegmentEvaluator;
import com.flagsmith.flagengine.segments.SegmentModel;
import static com.flagsmith.flagengine.unit.segments.IdentitySegmentFixtures.*;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
@Test(groups = "unit")
public class SegmentEvaluatorTest {
@DataProvider(name = "identitiesInSegments")
public Object[][] identitiesInSegments() {
return new Object[][] {
new Object[] {emptySegment(), emptyIdentityTraits(), Boolean.FALSE},
new Object[] {segmentSingleCondition(), emptyIdentityTraits(), Boolean.FALSE},
new Object[] {segmentSingleCondition(), oneIdentityTrait(), Boolean.TRUE},
new Object[] {segmentMultipleConditionsAll(), emptyIdentityTraits(), Boolean.FALSE},
new Object[] {segmentMultipleConditionsAll(), oneIdentityTrait(), Boolean.FALSE},
new Object[] {segmentMultipleConditionsAll(), twoIdentityTraits(), Boolean.TRUE},
new Object[] {segmentMultipleConditionsAny(), emptyIdentityTraits(), Boolean.FALSE},
new Object[] {segmentMultipleConditionsAny(), Arrays.asList(secondIdentityTrait()),
Boolean.TRUE},
new Object[] {segmentMultipleConditionsAny(), oneIdentityTrait(), Boolean.TRUE},
new Object[] {segmentMultipleConditionsAny(), twoIdentityTraits(), Boolean.TRUE},
new Object[] {segmentNestedRules(), emptyIdentityTraits(), Boolean.FALSE},
new Object[] {segmentNestedRules(), oneIdentityTrait(), Boolean.FALSE},
new Object[] {segmentNestedRules(), threeIdentityTraits(), Boolean.TRUE},
new Object[] {segmentConditionsAndNestedRules(), emptyIdentityTraits(), Boolean.FALSE},
new Object[] {segmentConditionsAndNestedRules(), oneIdentityTrait(), Boolean.FALSE},
new Object[] {segmentConditionsAndNestedRules(), threeIdentityTraits(), Boolean.TRUE},
};
}
@Test(dataProvider = "identitiesInSegments")
public void testIdentityInSegment(SegmentModel segment, List<TraitModel> identityTraits,
Boolean expectedResponse) {
IdentityModel mockIdentity = new IdentityModel();
mockIdentity.setIdentifier("foo");
mockIdentity.setIdentityTraits(identityTraits);
mockIdentity.setEnvironmentApiKey("api-key");
Boolean actualResult = SegmentEvaluator.evaluateIdentityInSegment(mockIdentity, segment, null);
Assert.assertTrue(actualResult.equals(expectedResponse));
}
}
| 48.571429 | 99 | 0.740809 |
6da77e65cb7017daec8400543ef07a2e30652e52 | 1,949 | /*
* 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.geode_examples.colocation;
import java.io.Serializable;
public class OrderKey implements Serializable {
private static final long serialVersionUID = 60372860L;
private Integer customerId;
private Integer orderId;
public OrderKey() {}
public OrderKey(Integer orderId, Integer customerId) {
this.orderId = orderId;
this.customerId = customerId;
}
public Integer getCustomerId() {
return customerId;
}
public Integer getOrderId() {
return orderId;
}
@Override
public int hashCode() {
int result = orderId.hashCode();
result = 31 * result + customerId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OrderKey other = (OrderKey) obj;
if (!orderId.equals(other.getOrderId()))
return false;
if (!customerId.equals(other.getCustomerId()))
return false;
return true;
}
@Override
public String toString() {
return "OrderKey [orderId=" + orderId + ", customerId=" + customerId + "]";
}
}
| 28.661765 | 100 | 0.704464 |
d6653ec9c59289111cdd568d6d37505004b60b8c | 870 | package de.wwag.hackathon.team2.domain;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import de.wwag.hackathon.team2.web.rest.TestUtil;
public class DailyReservationTest {
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(DailyReservation.class);
DailyReservation dailyReservation1 = new DailyReservation();
dailyReservation1.setId(1L);
DailyReservation dailyReservation2 = new DailyReservation();
dailyReservation2.setId(dailyReservation1.getId());
assertThat(dailyReservation1).isEqualTo(dailyReservation2);
dailyReservation2.setId(2L);
assertThat(dailyReservation1).isNotEqualTo(dailyReservation2);
dailyReservation1.setId(null);
assertThat(dailyReservation1).isNotEqualTo(dailyReservation2);
}
}
| 37.826087 | 70 | 0.752874 |
d32a88ffcaaa98f2630b70480299d38eb7d72ef4 | 1,753 | package com.frank.sso.service;
import com.frank.sso.model.UserLogin;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 类:
* 内容:
* 创建人:付帅
* 时间:2019/11/18
*/
@Component
public class SSOUserDetailsService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserLoginService userLoginService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if(StringUtils.isEmpty(username)){
throw new UsernameNotFoundException("the username is not null");
}
UserLogin userLogin = userLoginService.getUserLoginByName(username);
if(null==userLogin){
throw new UsernameNotFoundException("the user is not found");
}
String password = passwordEncoder.encode(userLogin.getPassword());
// 用户角色也应在数据库中获取
String role = "ROLE_ADMIN";
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(role));
// 返回自定义的
User user = new User(username,password,authorities);
return user;
}
}
| 34.372549 | 93 | 0.752424 |
69f0e75a92d1c6bbfb14c9aceeba2e2815af44f3 | 539 | package com.nitya.accounter.taxreturn.vat.request;
import net.n3.nanoxml.XMLElement;
public class Principal {
private ContactDetailsStructure contact;
public ContactDetailsStructure getContact() {
return contact;
}
public void setContact(ContactDetailsStructure contact) {
this.contact = contact;
}
public void toXML(XMLElement iRheaderElement) {
XMLElement principalElement = new XMLElement("Principal");
iRheaderElement.addChild(principalElement);
if (contact != null) {
contact.toXML(principalElement);
}
}
}
| 22.458333 | 60 | 0.7718 |
4fc78ce189d34b9ce9f3da1dcc50ccc48ccbf1f6 | 13,766 | /*
* Copyright 2015 Trento Rise.
*
* 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 eu.trentorise.opendata.jackan.test.ckan;
import static eu.trentorise.opendata.commons.validation.Preconditions.checkNotEmpty;
import eu.trentorise.opendata.jackan.exceptions.CkanException;
import eu.trentorise.opendata.jackan.exceptions.CkanNotFoundException;
import eu.trentorise.opendata.jackan.exceptions.JackanException;
import eu.trentorise.opendata.jackan.model.*;
import eu.trentorise.opendata.jackan.test.JackanTestConfig;
import static eu.trentorise.opendata.jackan.test.ckan.ReadCkanIT.PRODOTTI_CERTIFICATI_RESOURCE_ID;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import junitparams.Parameters;
import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Test;
/**
*
* @author David Leoni
* @since 0.4.1
*/
public class WriteCkanResourceIT extends WriteCkanTest {
private static final Logger LOG = Logger.getLogger(WriteCkanResourceIT.class.getName());
@Test
public void testCreateMinimal() {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase(JACKAN_URL, dataset.getId());
CkanResource retRes = client.createResource(resource);
checkNotEmpty(retRes.getId(), "Invalid created resource id!");
assertEquals(resource.getUrl(), retRes.getUrl());
// latest ckan gives back packageId!
// assertEquals(null, retRes.getPackageId());
LOG.log(Level.INFO, "Created resource with id {0} in catalog {1}", new Object[]{retRes.getId(), JackanTestConfig.of().getOutputCkan()});
}
@Test
public void testCreate() {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase(JACKAN_URL, dataset.getId());
resource.putOthers("x", "y");
CkanResource retRes = client.createResource(resource);
checkNotEmpty(retRes.getId(), "Invalid created resource id!");
assertEquals(resource.getUrl(), retRes.getUrl());
// Checking inclusion, as i.e. from demo.ckan.org we might get extra gifts like 'datastore_active=false'
CkanClientTests.checkIsIncluded(resource.getOthers(), retRes.getOthers());
LOG.log(Level.INFO, "Created resource with id {0} in catalog {1}", new Object[]{retRes.getId(), JackanTestConfig.of().getOutputCkan()});
}
/**
* @since 0.4.3
*/
@Test
public void testCreateWithFile() {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase("upload", dataset.getId());
resource.setUpload(new File(JackanTestConfig.of().getResourceFile()), true);
assertEquals("CSV", resource.getFormat());
assertEquals("text/csv", resource.getMimetype());
CkanResource retRes = client.createResource(resource);
checkNotEmpty(retRes.getId(), "Invalid created resource id!");
assertNotEquals("upload", retRes.getUrl());
assertTrue(retRes.getUrl().startsWith("http"));
assertEquals(resource.getMimetype(), retRes.getMimetype());
assertEquals(resource.getFormat().toLowerCase(), retRes.getFormat().toLowerCase());
assertEquals(resource.getSize(), retRes.getSize());
LOG.log(Level.INFO, "Created resource with id {0} in catalog {1}", new Object[]{retRes.getId(), JackanTestConfig.of().getOutputCkan()});
client.deleteResource(retRes.getId());
client.deleteDataset(dataset.getId());
}
/**
* @since 0.4.3
*/
@Test
public void testCreateWithLargeFile() {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase("upload", dataset.getId());
File file = null;
try {
file = tempFolder.newFile(CkanClientTests.JACKAN_TEST_PREFIX + "largefile.txt");
RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
randomFile.setLength(10000000);
} catch (java.io.IOException e) {
LOG.log(Level.SEVERE, "Could not set size of random access file", e);
fail("Could not set size of random access file");
}
resource.setUpload(file, false);
CkanResource retRes;
try {
retRes = client.createResource(resource);
client.deleteResource(retRes.getId());
} catch (CkanException e) {
LOG.log(Level.SEVERE, "Could not write large file", e);
fail("Could not write large file !");
} finally {
client.deleteDataset(dataset.getId());
}
}
/**
* Shows it's possible to force an id in a resource.
*/
@Test
public void testCreateWithId() {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase(JACKAN_URL, dataset.getId());
resource.setId(UUID.randomUUID().toString());
CkanResource retRes = client.createResource(resource);
assertEquals(resource.getId(), retRes.getId());
}
@Test
@Parameters(method = "wrongIds")
public void testCreateWithWrongId(String wrongId) {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase(JACKAN_URL, dataset.getId());
resource.setId(wrongId);
try {
CkanResource retRes = client.createResource(resource);
Assert.fail("Shouldn't be able to create resource with ill formatted UUID '" + resource.getId() + "'");
}
catch (JackanException ex) {
}
}
@Test
public void testCreateDuplicateId() {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase(JACKAN_URL, dataset.getId());
resource.setId(UUID.randomUUID().toString());
CkanResource retRes1 = client.createResource(resource);
try {
CkanResource retRes2 = client.createResource(resource);
LOG.log(Level.FINE, "id 1: {0}", retRes1.getId());
LOG.log(Level.FINE, "id 2: {0}", retRes2.getId());
Assert.fail("Shouldn't be able to create resource with duplicate id!");
}
catch (JackanException ex) {
}
}
@Test
@Parameters(method = "wrongUrls")
public void testCreateWithWrongUrl(String url) {
CkanDataset dataset = createRandomDataset();
try {
CkanResourceBase resource = new CkanResourceBase(url, dataset.getId());
client.createResource(resource);
Assert.fail("Shouldn't be able to create resource with wrong url: " + url);
}
catch (JackanException ex) {
}
}
@Test
public void testCreateWithWrongDatasetId() {
CkanResourceBase resource = new CkanResourceBase(JACKAN_URL, UUID.randomUUID().toString());
try {
client.createResource(resource);
Assert.fail();
}
catch (JackanException ex) {
}
}
@Test
public void testCreateMirror() {
CkanDataset dataset = createRandomDataset();
CkanResource resource = datiTrentinoClient.getResource(PRODOTTI_CERTIFICATI_RESOURCE_ID);
resource.setPackageId(dataset.getId());
resource.setId(randomUUID());
CkanResource retResource = client.createResource(resource);
checkNotEmpty(retResource.getId(), "Invalid resource id!");
LOG.log(Level.INFO, "created resource with id {0} in catalog {1}", new Object[]{retResource.getId(), JackanTestConfig.of().getOutputCkan()});
}
@Test
public void testPatchUpdate() {
CkanDataset dataset = createRandomDataset();
CkanResource resource = new CkanResource(JACKAN_URL, dataset.getId());
resource.setSize("123");
resource.setOwner("acme"); // owner is not in CkanResourceBase, shouldn't be sent in update post
resource.putOthers("x", "y");
CkanResource retRes1 = client.createResource(resource);
retRes1.setDescription("abc");
retRes1.setSize(null); // so we won't send it in the post
retRes1.setOthers(null); // so we won't send it in the post and hopefully trigger client automerge feature
CkanResource retRes2 = client.patchUpdateResource(retRes1);
assertEquals(retRes1.getId(), retRes2.getId());
assertEquals(retRes1.getUrl(), retRes2.getUrl());
assertEquals("abc", retRes2.getDescription());
assertEquals("123", retRes2.getSize());
CkanClientTests.checkIsIncluded(resource.getOthers(), retRes2.getOthers());
assertEquals(null, retRes2.getOwner()); // owner is not among api docs for creation, so hopefully was jsonignored when sending retRes1
}
@Test
public void testPatchUpdateNonExistingResource() {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase(JACKAN_URL, dataset.getId());
resource.setId(randomUUID());
try {
client.patchUpdateResource(resource);
Assert.fail("Shouldn't be able to patch update non existing resource!");
}
catch (JackanException ex) {
}
}
@Test
@Parameters(method = "wrongUrls")
public void testPatchUpdatWithWrongUrl(String url) {
CkanResource resource = createRandomResource();
resource.setUrl(url);
try {
client.patchUpdateResource(resource);
Assert.fail("Shouldn't be able to patch update resource with wrong url: " + url);
}
catch (JackanException ex) {
}
}
/**
* This shows it is not possible to move a resource from one dataset to
* another by updating the resource packageId.
*/
@Test
public void testPatchUpdateWithDifferentDatasetId() {
CkanDataset dataset1 = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase(JACKAN_URL, dataset1.getId());
CkanResource retResource1 = client.createResource(resource);
CkanDataset dataset2 = createRandomDataset();
resource.setPackageId(dataset2.getId());
CkanResource retResource2 = client.patchUpdateResource(retResource1);
boolean found = false;
CkanDataset newDataset1 = client.getDataset(dataset1.getId());
for (CkanResource cr : newDataset1.getResources()) {
if (retResource1.getId().equals(cr.getId())) {
found = true;
}
}
if (!found) {
Assert.fail("In theory it sbouldn't be possible to 'move' a resource from one dataset to another by updating the resource package id!");
}
}
/**
* Shows it is not possible to mark as deleted a resource by update. For
* dataset it is different, see {@link WriteCkanDatasetIT#testPatchUpdateAsDeleted()
* }
*/
@Test
public void testPatchUpdateAsDeleted() {
CkanResource resource = createRandomResource();
resource.setState(CkanState.deleted);
CkanResource retResource1 = client.patchUpdateResource(resource);
assertEquals(CkanState.active, retResource1.getState());
}
/**
* @since 0.4.3
*/
@Test
public void testUpdateResourceData() {
CkanDataset dataset = createRandomDataset();
CkanResourceBase resource = new CkanResourceBase("upload", dataset.getId());
resource.setUpload(new File(JackanTestConfig.of().getResourceFile()), true);
CkanResource retRes = client.createResource(resource);
retRes.setUpload(new File(JackanTestConfig.of().getAlternateResourceFile()), true);
CkanResource retRes2 = client.updateResourceData(retRes);
assertNotEquals("upload", retRes2.getUrl());
assertTrue(retRes2.getUrl().startsWith("http"));
assertEquals(retRes.getMimetype(), retRes2.getMimetype());
assertEquals(retRes.getFormat().toLowerCase(), retRes2.getFormat().toLowerCase());
assertEquals(retRes.getSize(), retRes2.getSize());
LOG.log(Level.INFO, "Updated resource with id {0} in catalog {1}", new Object[]{retRes2.getId(), JackanTestConfig.of().getOutputCkan()});
client.deleteResource(retRes2.getId());
client.deleteDataset(dataset.getId());
}
/**
* Shows what happens when resources are marked as 'deleted'
*/
@Test
public void testDelete() {
CkanDataset dataset = createRandomDataset(1);
String resourceId = dataset.getResources().get(0).getId();
client.deleteResource(resourceId);
try {
nonAdminClient.getResource(resourceId);
Assert.fail("Shouldn't find a deleted resource!");
} catch (CkanNotFoundException ex){
}
}
@Test
public void testDeleteNonExisting() {
String resourceId = UUID.randomUUID().toString();
try {
client.deleteResource(resourceId);
Assert.fail("Shouldn't be possible to delete non existing resource!");
}
catch (CkanNotFoundException ex) {
}
}
}
| 34.501253 | 149 | 0.658797 |
4cafd66b876b4772995dbebb7da08a1fa75506e7 | 30,325 | package org.greenplum.pxf.plugins.hdfs;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.parquet.column.page.PageReadStore;
import org.apache.parquet.example.data.Group;
import org.apache.parquet.example.data.simple.NanoTime;
import org.apache.parquet.example.data.simple.SimpleGroup;
import org.apache.parquet.example.data.simple.convert.GroupRecordConverter;
import org.apache.parquet.format.converter.ParquetMetadataConverter;
import org.apache.parquet.hadoop.ParquetFileReader;
import org.apache.parquet.io.ColumnIOFactory;
import org.apache.parquet.io.MessageColumnIO;
import org.apache.parquet.io.RecordReader;
import org.apache.parquet.io.api.Binary;
import org.apache.parquet.pig.convert.DecimalUtils;
import org.apache.parquet.schema.DecimalMetadata;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.schema.OriginalType;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.Type;
import org.greenplum.pxf.api.OneField;
import org.greenplum.pxf.api.OneRow;
import org.greenplum.pxf.api.io.DataType;
import org.greenplum.pxf.api.model.RequestContext;
import org.greenplum.pxf.api.utilities.ColumnDescriptor;
import org.greenplum.pxf.plugins.hdfs.parquet.ParquetTypeConverter;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ParquetResolverTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private ParquetResolver resolver;
private RequestContext context;
private MessageType schema;
private String localTimestampString;
@Before
public void setup() {
resolver = new ParquetResolver();
context = new RequestContext();
schema = new MessageType("test");
context.setMetadata(schema);
context.setConfig("default");
context.setUser("test-user");
// for test cases that test conversions against server's time zone
Instant timestamp = Instant.parse("2013-07-14T04:00:05Z"); // UTC
ZonedDateTime localTime = timestamp.atZone(ZoneId.systemDefault());
localTimestampString = localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // should be "2013-07-13 21:00:05" in PST
}
@Test
public void testInitialize() {
resolver.initialize(context);
}
@Test
public void testGetFields_FailsOnMissingSchema() {
thrown.expect(RuntimeException.class);
thrown.expectMessage("No schema detected in request context");
context.setMetadata(null);
resolver.initialize(context);
resolver.getFields(new OneRow());
}
@Test
public void testSetFields_FailsOnMissingSchema() throws IOException {
thrown.expect(RuntimeException.class);
thrown.expectMessage("No schema detected in request context");
context.setMetadata(null);
resolver.initialize(context);
resolver.setFields(new ArrayList<>());
}
@Test
public void testSetFields_Primitive() throws IOException {
schema = getParquetSchemaForPrimitiveTypes(Type.Repetition.OPTIONAL, false);
// schema has changed, set metadata again
context.setMetadata(schema);
resolver.initialize(context);
context.setTupleDescription(getColumnDescriptorsFromSchema(schema));
Instant timestamp = Instant.parse("2013-07-14T04:00:05Z"); // UTC
ZonedDateTime localTime = timestamp.atZone(ZoneId.systemDefault());
String localTimestampString = localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // should be "2013-07-13 21:00:05" in PST
List<OneField> fields = new ArrayList<>();
fields.add(new OneField(DataType.TEXT.getOID(), "row1"));
fields.add(new OneField(DataType.TEXT.getOID(), "s_6"));
fields.add(new OneField(DataType.INTEGER.getOID(), 1));
fields.add(new OneField(DataType.FLOAT8.getOID(), 6.0d));
fields.add(new OneField(DataType.NUMERIC.getOID(), "1.234560000000000000"));
fields.add(new OneField(DataType.TIMESTAMP.getOID(), localTimestampString));
fields.add(new OneField(DataType.REAL.getOID(), 7.7f));
fields.add(new OneField(DataType.BIGINT.getOID(), 23456789L));
fields.add(new OneField(DataType.BOOLEAN.getOID(), false));
fields.add(new OneField(DataType.SMALLINT.getOID(), (short) 1));
fields.add(new OneField(DataType.SMALLINT.getOID(), (short) 10));
fields.add(new OneField(DataType.TEXT.getOID(), "abcd"));
fields.add(new OneField(DataType.TEXT.getOID(), "abc"));
fields.add(new OneField(DataType.BYTEA.getOID(), new byte[]{(byte) 49}));
fields.add(new OneField(DataType.TIMESTAMP_WITH_TIME_ZONE.getOID(), "2013-07-13 21:00:05-07"));
fields.add(new OneField(DataType.TIMESTAMP_WITH_TIME_ZONE.getOID(), "2013-07-14 16:45:05+12:45"));
OneRow row = resolver.setFields(fields);
assertNotNull(row);
Object data = row.getData();
assertNotNull(data);
assertTrue(data instanceof Group);
Group group = (Group) data;
// assert column values
assertEquals("row1", group.getString(0, 0));
assertEquals("s_6", group.getString(1, 0));
assertEquals(1, group.getInteger(2, 0));
assertEquals(6.0d, group.getDouble(3, 0), 0d);
assertEquals(BigDecimal.valueOf(1234560000000000000L, 18),
DecimalUtils.binaryToDecimal(group.getBinary(4, 0), 19, 18));
NanoTime nanoTime = NanoTime.fromBinary(group.getInt96(5, 0));
assertEquals(2456488, nanoTime.getJulianDay()); // 14 Jul 2013 in Julian days
assertEquals((4 * 60 * 60 + 5L) * 1000 * 1000 * 1000, nanoTime.getTimeOfDayNanos()); // 04:00:05 time
assertEquals(7.7f, group.getFloat(6, 0), 0f);
assertEquals(23456789L, group.getLong(7, 0));
assertFalse(group.getBoolean(8, 0));
assertEquals(1, group.getInteger(9, 0));
assertEquals(10, group.getInteger(10, 0));
assertEquals("abcd", group.getString(11, 0));
assertEquals("abc", group.getString(12, 0));
assertArrayEquals(new byte[]{(byte) 49}, group.getBinary(13, 0).getBytes());
nanoTime = NanoTime.fromBinary(group.getInt96(14, 0));
assertEquals(2456488, nanoTime.getJulianDay()); // 14 Jul 2013 in Julian days
assertEquals((4 * 60 * 60 + 5L) * 1000 * 1000 * 1000, nanoTime.getTimeOfDayNanos()); // 04:00:05 time
nanoTime = NanoTime.fromBinary(group.getInt96(15, 0));
assertEquals(2456488, nanoTime.getJulianDay()); // 14 Jul 2013 in Julian days
assertEquals((4 * 60 * 60 + 5L) * 1000 * 1000 * 1000, nanoTime.getTimeOfDayNanos()); // 04:00:05 time
// assert value repetition count
for (int i = 0; i < 16; i++) {
assertEquals(1, group.getFieldRepetitionCount(i));
}
}
@Test
public void testSetFields_RightTrimChar() throws IOException {
testSetFields_RightTrimCharHelper("abcd ", "abc ", "abc");
}
@Test
public void testSetFields_RightTrimCharDontTrimTabChars() throws IOException {
testSetFields_RightTrimCharHelper("abcd\t\t", "abc\t\t\t ", "abc\t\t\t");
}
@Test
public void testSetFields_RightTrimCharDontTrimNewlineChars() throws IOException {
testSetFields_RightTrimCharHelper("abcd\n\n", "abc\n\n\n ", "abc\n\n\n");
}
@Test
public void testSetFields_RightTrimCharNoLeftTrim() throws IOException {
testSetFields_RightTrimCharHelper(" abcd ", " abc ", " abc");
}
@Test
public void testSetFields_Primitive_Nulls() throws IOException {
schema = getParquetSchemaForPrimitiveTypes(Type.Repetition.OPTIONAL, false);
// schema has changed, set metadata again
context.setMetadata(schema);
context.setTupleDescription(getColumnDescriptorsFromSchema(schema));
resolver.initialize(context);
List<OneField> fields = new ArrayList<>();
fields.add(new OneField(DataType.TEXT.getOID(), null));
fields.add(new OneField(DataType.TEXT.getOID(), null));
fields.add(new OneField(DataType.INTEGER.getOID(), null));
fields.add(new OneField(DataType.FLOAT8.getOID(), null));
fields.add(new OneField(DataType.NUMERIC.getOID(), null));
fields.add(new OneField(DataType.TIMESTAMP.getOID(), null));
fields.add(new OneField(DataType.REAL.getOID(), null));
fields.add(new OneField(DataType.BIGINT.getOID(), null));
fields.add(new OneField(DataType.BOOLEAN.getOID(), null));
fields.add(new OneField(DataType.SMALLINT.getOID(), null));
fields.add(new OneField(DataType.SMALLINT.getOID(), null));
fields.add(new OneField(DataType.TEXT.getOID(), null));
fields.add(new OneField(DataType.TEXT.getOID(), null));
fields.add(new OneField(DataType.BYTEA.getOID(), null));
fields.add(new OneField(DataType.TIMESTAMP_WITH_TIME_ZONE.getOID(), null));
fields.add(new OneField(DataType.TIMESTAMP_WITH_TIME_ZONE.getOID(), null));
OneRow row = resolver.setFields(fields);
assertNotNull(row);
Object data = row.getData();
assertNotNull(data);
assertTrue(data instanceof Group);
Group group = (Group) data;
// assert value repetition count
for (int i = 0; i < 16; i++) {
assertEquals(0, group.getFieldRepetitionCount(i));
}
}
@Test
public void testGetFields_Primitive_EmptySchema() throws IOException {
resolver.initialize(context);
List<Group> groups = readParquetFile("primitive_types.parquet", 25, schema);
OneRow row1 = new OneRow(groups.get(0)); // get row 1
List<OneField> fields = resolver.getFields(row1);
assertTrue(fields.isEmpty());
}
@Test
public void testGetFields_Primitive() throws IOException {
schema = getParquetSchemaForPrimitiveTypes(Type.Repetition.OPTIONAL, true);
// schema has changed, set metadata again
context.setMetadata(schema);
context.setTupleDescription(getColumnDescriptorsFromSchema(schema));
resolver.initialize(context);
List<Group> groups = readParquetFile("primitive_types.parquet", 25, schema);
assertEquals(25, groups.size());
List<OneField> fields = assertRow(groups, 0, 16);
//s1 : "row1" : TEXT
assertField(fields, 0, "row1", DataType.TEXT);
assertField(fields, 1, "s_6", DataType.TEXT);
assertField(fields, 2, 1, DataType.INTEGER);
assertField(fields, 3, 6.0d, DataType.FLOAT8);
assertField(fields, 4, BigDecimal.valueOf(1234560000000000000L, 18), DataType.NUMERIC);
assertField(fields, 5, localTimestampString, DataType.TIMESTAMP);
assertField(fields, 6, 7.7f, DataType.REAL);
assertField(fields, 7, 23456789L, DataType.BIGINT);
assertField(fields, 8, false, DataType.BOOLEAN);
assertField(fields, 9, (short) 1, DataType.SMALLINT);
assertField(fields, 10, (short) 10, DataType.SMALLINT);
assertField(fields, 11, "abcd", DataType.TEXT);
assertField(fields, 12, "abc", DataType.TEXT);
assertField(fields, 13, new byte[]{(byte) 49}, DataType.BYTEA); // 49 is the ascii code for '1'
// Parquet only stores the Timestamp (timezone information was lost)
assertField(fields, 14, localTimestampString, DataType.TIMESTAMP);
// Parquet only stores the Timestamp (timezone information was lost)
assertField(fields, 15, localTimestampString, DataType.TIMESTAMP);
// test nulls
fields = assertRow(groups, 11, 16);
assertField(fields, 1, null, DataType.TEXT);
fields = assertRow(groups, 12, 16);
assertField(fields, 2, null, DataType.INTEGER);
fields = assertRow(groups, 13, 16);
assertField(fields, 3, null, DataType.FLOAT8);
fields = assertRow(groups, 14, 16);
assertField(fields, 4, null, DataType.NUMERIC);
fields = assertRow(groups, 15, 16);
assertField(fields, 5, null, DataType.TIMESTAMP);
fields = assertRow(groups, 16, 16);
assertField(fields, 6, null, DataType.REAL);
fields = assertRow(groups, 17, 16);
assertField(fields, 7, null, DataType.BIGINT);
fields = assertRow(groups, 18, 16);
assertField(fields, 8, null, DataType.BOOLEAN);
fields = assertRow(groups, 19, 16);
assertField(fields, 9, null, DataType.SMALLINT);
fields = assertRow(groups, 20, 16);
assertField(fields, 10, null, DataType.SMALLINT);
fields = assertRow(groups, 22, 16);
assertField(fields, 11, null, DataType.TEXT);
fields = assertRow(groups, 23, 16);
assertField(fields, 12, null, DataType.TEXT);
fields = assertRow(groups, 24, 16);
assertField(fields, 13, null, DataType.BYTEA);
}
@Test
public void testGetFields_Primitive_With_Projection() throws IOException {
schema = getParquetSchemaForPrimitiveTypes(Type.Repetition.OPTIONAL, true);
context.setTupleDescription(getColumnDescriptorsFromSchema(schema));
// set odd columns to be not projected, their values will become null
for (int i = 0; i < context.getTupleDescription().size(); i++) {
context.getTupleDescription().get(i).setProjected(i % 2 == 0);
}
MessageType readSchema = buildReadSchema(schema);
// schema has changed, set metadata again
context.setMetadata(readSchema);
resolver.initialize(context);
// use readSchema to read only specific columns from parquet file into Group
List<Group> groups = readParquetFile("primitive_types.parquet", 25, readSchema);
assertEquals(25, groups.size());
List<OneField> fields = assertRow(groups, 0, 16);
//s1 : "row1" : TEXT
assertField(fields, 0, "row1", DataType.TEXT);
assertField(fields, 1, null, DataType.TEXT);
assertField(fields, 2, 1, DataType.INTEGER);
assertField(fields, 3, null, DataType.FLOAT8);
assertField(fields, 4, BigDecimal.valueOf(1234560000000000000L, 18), DataType.NUMERIC);
assertField(fields, 5, null, DataType.TIMESTAMP);
assertField(fields, 6, 7.7f, DataType.REAL);
assertField(fields, 7, null, DataType.BIGINT);
assertField(fields, 8, false, DataType.BOOLEAN);
assertField(fields, 9, null, DataType.SMALLINT);
assertField(fields, 10, (short) 10, DataType.SMALLINT);
assertField(fields, 11, null, DataType.TEXT);
assertField(fields, 12, "abc", DataType.TEXT);
assertField(fields, 13, null, DataType.BYTEA); // 49 is the ascii code for '1'
// Parquet only stores the Timestamp (timezone information was lost)
assertField(fields, 14, localTimestampString, DataType.TIMESTAMP);
// Parquet only stores the Timestamp (timezone information was lost)
assertField(fields, 15, null, DataType.TIMESTAMP);
// test nulls
fields = assertRow(groups, 11, 16);
assertField(fields, 1, null, DataType.TEXT);
fields = assertRow(groups, 12, 16);
assertField(fields, 2, null, DataType.INTEGER);
fields = assertRow(groups, 13, 16);
assertField(fields, 3, null, DataType.FLOAT8);
fields = assertRow(groups, 14, 16);
assertField(fields, 4, null, DataType.NUMERIC);
fields = assertRow(groups, 15, 16);
assertField(fields, 5, null, DataType.TIMESTAMP);
fields = assertRow(groups, 16, 16);
assertField(fields, 6, null, DataType.REAL);
fields = assertRow(groups, 17, 16);
assertField(fields, 7, null, DataType.BIGINT);
fields = assertRow(groups, 18, 16);
assertField(fields, 8, null, DataType.BOOLEAN);
fields = assertRow(groups, 19, 16);
assertField(fields, 9, null, DataType.SMALLINT);
fields = assertRow(groups, 20, 16);
assertField(fields, 10, null, DataType.SMALLINT);
fields = assertRow(groups, 22, 16);
assertField(fields, 11, null, DataType.TEXT);
fields = assertRow(groups, 23, 16);
assertField(fields, 12, null, DataType.TEXT);
fields = assertRow(groups, 24, 16);
assertField(fields, 13, null, DataType.BYTEA);
}
@Test
public void testGetFields_Primitive_RepeatedString() throws IOException {
List<Type> columns = new ArrayList<>();
columns.add(new PrimitiveType(Type.Repetition.REPEATED, PrimitiveTypeName.BINARY, "myString", OriginalType.UTF8));
schema = new MessageType("TestProtobuf.StringArray", columns);
context.setMetadata(schema);
context.setTupleDescription(getColumnDescriptorsFromSchema(schema));
resolver.initialize(context);
List<Group> groups = readParquetFile("proto-repeated-string.parquet", 3, schema);
List<OneField> fields;
// row 0
fields = assertRow(groups, 0, 1);
assertEquals(DataType.TEXT.getOID(), fields.get(0).type);
assertEquals("[\"hello\",\"world\"]", fields.get(0).val);
// row 1
fields = assertRow(groups, 1, 1);
assertEquals(DataType.TEXT.getOID(), fields.get(0).type);
assertEquals("[\"good\",\"bye\"]", fields.get(0).val);
// row 2
fields = assertRow(groups, 2, 1);
assertEquals(DataType.TEXT.getOID(), fields.get(0).type);
assertEquals("[\"one\",\"two\",\"three\"]", fields.get(0).val);
}
@Test
public void testGetFields_Primitive_Repeated_Synthetic() {
// this test does not read the actual Parquet file, but rather construct Group object synthetically
schema = getParquetSchemaForPrimitiveTypes(Type.Repetition.REPEATED, true);
// schema has changed, set metadata again
context.setMetadata(schema);
context.setTupleDescription(getColumnDescriptorsFromSchema(schema));
resolver.initialize(context);
/*
Corresponding DB column types are:
TEXT,TEXT,INTEGER, DOUBLE PRECISION,NUMERIC,TIMESTAMP,REAL,BIGINT,BOOLEAN,SMALLINT,SMALLINT,VARCHAR(5),CHAR(3),BYTEA
*/
Group group = new SimpleGroup(schema);
group.add(0, "row1-1");
group.add(0, "row1-2");
// leave column 1 (t2) unset as part fo the test
group.add(2, 1);
group.add(2, 2);
group.add(2, 3);
group.add(3, 6.0d);
group.add(3, -16.34d);
BigDecimal value = new BigDecimal("12345678.9012345987654321"); // place of dot doesn't matter
byte fillByte = (byte) (value.signum() < 0 ? 0xFF : 0x00);
byte[] unscaled = value.unscaledValue().toByteArray();
byte[] bytes = new byte[16];
int offset = bytes.length - unscaled.length;
for (int i = 0; i < bytes.length; i += 1) {
bytes[i] = (i < offset) ? fillByte : unscaled[i - offset];
}
group.add(4, Binary.fromReusedByteArray(bytes));
group.add(5, ParquetTypeConverter.getBinaryFromTimestamp("2019-03-14 14:10:28"));
group.add(5, ParquetTypeConverter.getBinaryFromTimestamp("1969-12-30 05:42:23.211211"));
group.add(6, 7.7f);
group.add(6, -12345.35354646f);
group.add(7, 23456789L);
group.add(7, -123456789012345L);
group.add(8, true);
group.add(8, false);
group.add(9, (short) 1);
group.add(9, (short) -3);
group.add(10, (short) 269);
group.add(10, (short) -313);
group.add(11, Binary.fromString("Hello"));
group.add(11, Binary.fromString("World"));
group.add(12, Binary.fromString("foo"));
group.add(12, Binary.fromString("bar"));
byte[] byteArray1 = new byte[]{(byte) 49, (byte) 50, (byte) 51};
group.add(13, Binary.fromReusedByteArray(byteArray1, 0, 3));
byte[] byteArray2 = new byte[]{(byte) 52, (byte) 53, (byte) 54};
group.add(13, Binary.fromReusedByteArray(byteArray2, 0, 3));
group.add(14, ParquetTypeConverter.getBinaryFromTimestampWithTimeZone("2019-03-14 14:10:28+07"));
OffsetDateTime offsetDateTime1 = OffsetDateTime.parse("2019-03-14T14:10:28+07:00");
ZonedDateTime localDateTime1 = offsetDateTime1.atZoneSameInstant(ZoneId.systemDefault());
String localDateTimeString1 = localDateTime1.format(DateTimeFormatter.ofPattern("[yyyy-MM-dd HH:mm:ss]"));
group.add(15, ParquetTypeConverter.getBinaryFromTimestampWithTimeZone("2019-03-14 14:10:28-07:30"));
OffsetDateTime offsetDateTime2 = OffsetDateTime.parse("2019-03-14T14:10:28-07:30");
ZonedDateTime localDateTime2 = offsetDateTime2.atZoneSameInstant(ZoneId.systemDefault());
String localDateTimeString2 = localDateTime2.format(DateTimeFormatter.ofPattern("[yyyy-MM-dd HH:mm:ss]"));
List<Group> groups = new ArrayList<>();
groups.add(group);
List<OneField> fields = assertRow(groups, 0, 16);
assertField(fields, 0, "[\"row1-1\",\"row1-2\"]", DataType.TEXT);
assertField(fields, 1, "[]", DataType.TEXT);
assertField(fields, 2, "[1,2,3]", DataType.TEXT);
assertField(fields, 3, "[6.0,-16.34]", DataType.TEXT);
assertField(fields, 4, "[123456.789012345987654321]", DataType.TEXT); // scale fixed to 18 in schema
assertField(fields, 5, "[\"2019-03-14 14:10:28\",\"1969-12-30 05:42:23.211211\"]", DataType.TEXT);
assertField(fields, 6, "[7.7,-12345.354]", DataType.TEXT); // rounded to the precision of 8
assertField(fields, 7, "[23456789,-123456789012345]", DataType.TEXT);
assertField(fields, 8, "[true,false]", DataType.TEXT);
assertField(fields, 9, "[1,-3]", DataType.TEXT);
assertField(fields, 10, "[269,-313]", DataType.TEXT);
assertField(fields, 11, "[\"Hello\",\"World\"]", DataType.TEXT);
assertField(fields, 12, "[\"foo\",\"bar\"]", DataType.TEXT); // 3 chars only
Base64.Encoder encoder = Base64.getEncoder(); // byte arrays are Base64 encoded into strings
String expectedByteArrays = "[\"" + encoder.encodeToString(byteArray1) + "\",\"" + encoder.encodeToString(byteArray2) + "\"]";
assertField(fields, 13, expectedByteArrays, DataType.TEXT);
assertField(fields, 14, "[\"" + localDateTimeString1 + "\"]", DataType.TEXT);
assertField(fields, 15, "[\"" + localDateTimeString2 + "\"]", DataType.TEXT);
}
@Test
public void testGetFields_Primitive_RepeatedInt() throws IOException {
List<Type> columns = new ArrayList<>();
columns.add(new PrimitiveType(Type.Repetition.REPEATED, PrimitiveTypeName.INT32, "repeatedInt"));
schema = new MessageType("TestProtobuf.RepeatedIntMessage", columns);
context.setMetadata(schema);
context.setTupleDescription(getColumnDescriptorsFromSchema(schema));
resolver.initialize(context);
List<Group> groups = readParquetFile("old-repeated-int.parquet", 1, schema);
List<OneField> fields = assertRow(groups, 0, 1);
assertEquals(DataType.TEXT.getOID(), fields.get(0).type);
assertEquals("[1,2,3]", fields.get(0).val);
}
private List<OneField> assertRow(List<Group> groups, int desiredRow, int numFields) {
OneRow row = new OneRow(groups.get(desiredRow)); // get row
List<OneField> fields = resolver.getFields(row);
assertEquals(numFields, fields.size());
return fields;
}
private void assertField(List<OneField> fields, int index, Object value, DataType type) {
assertEquals(type.getOID(), fields.get(index).type);
if (type == DataType.BYTEA) {
assertArrayEquals((byte[]) value, (byte[]) fields.get(index).val);
} else {
assertEquals(value, fields.get(index).val);
}
}
private MessageType getParquetSchemaForPrimitiveTypes(Type.Repetition repetition, boolean readCase) {
List<Type> fields = new ArrayList<>();
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.BINARY, "s1", OriginalType.UTF8));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.BINARY, "s2", OriginalType.UTF8));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.INT32, "n1", null));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.DOUBLE, "d1", null));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY, 16, "dc1", OriginalType.DECIMAL, new DecimalMetadata(38, 18), null));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.INT96, "tm", null));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.FLOAT, "f", null));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.INT64, "bg", null));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.BOOLEAN, "b", null));
// GPDB only has int16 and not int8 type, so for write tiny numbers int8 are still treated as shorts in16
OriginalType tinyType = readCase ? OriginalType.INT_8 : OriginalType.INT_16;
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.INT32, "tn", tinyType));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.INT32, "sml", OriginalType.INT_16));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.BINARY, "vc1", OriginalType.UTF8));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.BINARY, "c1", OriginalType.UTF8));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.BINARY, "bin", null));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.INT96, "tmtz", null));
fields.add(new PrimitiveType(repetition, PrimitiveTypeName.INT96, "tmtz2", null));
return new MessageType("hive_schema", fields);
}
@SuppressWarnings("deprecation")
private List<Group> readParquetFile(String file, long expectedSize, MessageType schema) throws IOException {
List<Group> result = new ArrayList<>();
String parquetFile = Objects.requireNonNull(getClass().getClassLoader().getResource("parquet/" + file)).getPath();
Path path = new Path(parquetFile);
ParquetFileReader fileReader = new ParquetFileReader(new Configuration(), path, ParquetMetadataConverter.NO_FILTER);
PageReadStore rowGroup;
while ((rowGroup = fileReader.readNextRowGroup()) != null) {
MessageColumnIO columnIO = new ColumnIOFactory().getColumnIO(schema);
RecordReader<Group> recordReader = columnIO.getRecordReader(rowGroup, new GroupRecordConverter(schema));
long rowCount = rowGroup.getRowCount();
for (long i = 0; i < rowCount; i++) {
result.add(recordReader.read());
}
}
fileReader.close();
assertEquals(expectedSize, result.size());
return result;
}
private List<ColumnDescriptor> getColumnDescriptorsFromSchema(MessageType schema) {
return schema.getFields()
.stream()
.map(f -> {
ParquetTypeConverter converter = ParquetTypeConverter.from(f.asPrimitiveType());
return new ColumnDescriptor(f.getName(), converter.getDataType(f).getOID(), 1, "", new Integer[]{});
})
.collect(Collectors.toList());
}
private MessageType buildReadSchema(MessageType originalSchema) {
List<Type> originalFields = originalSchema.getFields();
List<Type> projectedFields = new ArrayList<>();
for (int i = 0; i < context.getTupleDescription().size(); i++) {
if (context.getTupleDescription().get(i).isProjected()) {
projectedFields.add(originalFields.get(i));
}
}
return new MessageType(originalSchema.getName(), projectedFields);
}
private void testSetFields_RightTrimCharHelper(String varchar, String inputChar, String expectedChar) throws IOException {
List<Type> typeFields = new ArrayList<>();
typeFields.add(new PrimitiveType(Type.Repetition.OPTIONAL, PrimitiveTypeName.BINARY, "vc1", OriginalType.UTF8));
typeFields.add(new PrimitiveType(Type.Repetition.OPTIONAL, PrimitiveTypeName.BINARY, "c1", OriginalType.UTF8));
schema = new MessageType("hive_schema", typeFields);
context.setMetadata(schema);
List<ColumnDescriptor> columnDescriptors = new ArrayList<>();
columnDescriptors.add(new ColumnDescriptor("vc1", DataType.VARCHAR.getOID(), 0, "varchar", null));
columnDescriptors.add(new ColumnDescriptor("c1", DataType.BPCHAR.getOID(), 1, "char", null));
context.setTupleDescription(columnDescriptors);
resolver.initialize(context);
List<OneField> fields = new ArrayList<>();
fields.add(new OneField(DataType.TEXT.getOID(), varchar));
// the whitespace on the after 'abc ' needs to be trimmed
fields.add(new OneField(DataType.TEXT.getOID(), inputChar));
OneRow row = resolver.setFields(fields);
assertNotNull(row);
Object data = row.getData();
assertNotNull(data);
assertTrue(data instanceof Group);
Group group = (Group) data;
// assert column values
assertEquals(varchar, group.getString(0, 0));
assertEquals(expectedChar, group.getString(1, 0));
// assert value repetition count
for (int i = 0; i < 2; i++) {
assertEquals(1, group.getFieldRepetitionCount(i));
}
}
}
| 47.382813 | 158 | 0.667106 |
b4d2c0e4be90411be822b235cd079acf675755a1 | 1,838 | /*
* Copyright 2007-2012 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
*
* 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.springbyexample.integration.shoppingCart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springbyexample.integration.book.BookOrder;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.Router;
/**
* Routes order based on order type.
*
* @author David Winterfeldt
*/
@MessageEndpoint
public class OrderRouter {
final Logger logger = LoggerFactory.getLogger(OrderRouter.class);
/**
* Process order. Routes based on whether or
* not the order is a delivery or pickup.
*/
@Router(inputChannel="processOrder")
public String processOrder(BookOrder order) {
String result = null;
logger.debug("In OrderRouter. title='{}' quantity={} orderType={}",
new Object[] { order.getTitle(),
order.getQuantity(),
order.getOrderType() });
switch (order.getOrderType()) {
case DELIVERY:
result = "delivery";
break;
case PICKUP:
result = "pickup";
break;
}
return result;
}
}
| 30.131148 | 76 | 0.650707 |
778cfb0870ffdfb1e98e60b01127a9185695aa9f | 508 | package com.so.team.service;
import java.util.List;
import com.so.team.bean.Message;
import com.so.utils.Page;
/**
* 留言板DAO接口
* @author admin
* @version 2018-03-26
*/
public interface MessageService {
//添加
public int add(Message message);
//删除
public int delete(String id);
//修改
public int update(Message message);
//查询分页
public Page<Message> page(Message message,Page<Message> page);
//根据ID查询
public Message getById(String id);
//查询所有
public List<Message> findAll(Message message);
} | 18.142857 | 63 | 0.716535 |
755fbcb23cea45d8f83d4e56a9e3c4e8ad0d1371 | 9,514 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_import
import|import
name|com
operator|.
name|feth
operator|.
name|play
operator|.
name|module
operator|.
name|pa
operator|.
name|service
operator|.
name|AbstractUserService
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|play
operator|.
name|Application
import|;
end_import
begin_import
import|import
name|play
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|play
operator|.
name|mvc
operator|.
name|Call
import|;
end_import
begin_import
import|import
name|play
operator|.
name|mvc
operator|.
name|Http
import|;
end_import
begin_import
import|import
name|play
operator|.
name|mvc
operator|.
name|Http
operator|.
name|RequestBuilder
import|;
end_import
begin_import
import|import
name|play
operator|.
name|mvc
operator|.
name|Result
import|;
end_import
begin_import
import|import
name|providers
operator|.
name|TestUsernamePasswordAuthProvider
import|;
end_import
begin_import
import|import
name|service
operator|.
name|TestUserService
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Optional
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|fest
operator|.
name|assertions
operator|.
name|Assertions
operator|.
name|assertThat
import|;
end_import
begin_import
import|import static
name|play
operator|.
name|mvc
operator|.
name|Http
operator|.
name|Status
operator|.
name|OK
import|;
end_import
begin_import
import|import static
name|play
operator|.
name|mvc
operator|.
name|Http
operator|.
name|Status
operator|.
name|SEE_OTHER
import|;
end_import
begin_import
import|import static
name|play
operator|.
name|test
operator|.
name|Helpers
operator|.
name|*
import|;
end_import
begin_class
specifier|public
class|class
name|JavaControllerTest
block|{
annotation|@
name|Test
specifier|public
name|void
name|redirectsWhenNotLoggedIn
parameter_list|()
block|{
name|Application
name|app
init|=
name|fakeApplication
argument_list|()
decl_stmt|;
name|running
argument_list|(
name|app
argument_list|,
parameter_list|()
lambda|->
block|{
name|assertThat
argument_list|(
name|userService
argument_list|(
name|app
argument_list|)
argument_list|)
operator|.
name|isNotNull
argument_list|()
expr_stmt|;
name|Result
name|result
init|=
name|route
argument_list|(
name|controllers
operator|.
name|routes
operator|.
name|JavaController
operator|.
name|index
argument_list|()
argument_list|)
decl_stmt|;
name|assertThat
argument_list|(
name|result
operator|.
name|status
argument_list|()
argument_list|)
operator|.
name|isEqualTo
argument_list|(
name|SEE_OTHER
argument_list|)
expr_stmt|;
block|}
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|okWhenLoggedIn
parameter_list|()
block|{
name|Application
name|app
init|=
name|fakeApplication
argument_list|()
decl_stmt|;
name|running
argument_list|(
name|app
argument_list|,
parameter_list|()
lambda|->
block|{
name|assertThat
argument_list|(
name|userService
argument_list|(
name|app
argument_list|)
argument_list|)
operator|.
name|isNotNull
argument_list|()
expr_stmt|;
name|Http
operator|.
name|Session
name|session
init|=
name|signupAndLogin
argument_list|(
name|app
argument_list|)
decl_stmt|;
name|Result
name|result
init|=
name|route
argument_list|(
operator|new
name|RequestBuilder
argument_list|()
operator|.
name|uri
argument_list|(
name|controllers
operator|.
name|routes
operator|.
name|JavaController
operator|.
name|index
argument_list|()
operator|.
name|url
argument_list|()
argument_list|)
operator|.
name|session
argument_list|(
name|session
argument_list|)
argument_list|)
decl_stmt|;
name|assertThat
argument_list|(
name|result
operator|.
name|status
argument_list|()
argument_list|)
operator|.
name|isEqualTo
argument_list|(
name|OK
argument_list|)
expr_stmt|;
block|}
argument_list|)
expr_stmt|;
block|}
specifier|private
name|Http
operator|.
name|Session
name|signupAndLogin
parameter_list|(
name|Application
name|app
parameter_list|)
block|{
name|String
name|email
init|=
literal|"user@example.com"
decl_stmt|;
name|String
name|password
init|=
literal|"PaSSW0rd"
decl_stmt|;
block|{
comment|// Signup with a username/password
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|data
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
name|data
operator|.
name|put
argument_list|(
literal|"email"
argument_list|,
name|email
argument_list|)
expr_stmt|;
name|data
operator|.
name|put
argument_list|(
literal|"password"
argument_list|,
name|password
argument_list|)
expr_stmt|;
specifier|final
name|Call
name|doSignup
init|=
name|controllers
operator|.
name|routes
operator|.
name|ApplicationController
operator|.
name|doSignup
argument_list|()
decl_stmt|;
name|Result
name|result
init|=
name|route
argument_list|(
operator|new
name|RequestBuilder
argument_list|()
operator|.
name|method
argument_list|(
name|doSignup
operator|.
name|method
argument_list|()
argument_list|)
operator|.
name|uri
argument_list|(
name|doSignup
operator|.
name|url
argument_list|()
argument_list|)
operator|.
name|bodyForm
argument_list|(
name|data
argument_list|)
argument_list|)
decl_stmt|;
name|assertThat
argument_list|(
name|result
operator|.
name|status
argument_list|()
argument_list|)
operator|.
name|isEqualTo
argument_list|(
name|SEE_OTHER
argument_list|)
expr_stmt|;
block|}
block|{
comment|// Validate the token
name|String
name|token
init|=
name|upAuthProvider
argument_list|(
name|app
argument_list|)
operator|.
name|getVerificationToken
argument_list|(
name|email
argument_list|)
decl_stmt|;
name|assertThat
argument_list|(
name|token
argument_list|)
operator|.
name|isNotNull
argument_list|()
expr_stmt|;
name|Logger
operator|.
name|info
argument_list|(
literal|"Verifying token: "
operator|+
name|token
argument_list|)
expr_stmt|;
name|Result
name|result
init|=
name|route
argument_list|(
name|controllers
operator|.
name|routes
operator|.
name|ApplicationController
operator|.
name|verify
argument_list|(
name|token
argument_list|)
argument_list|)
decl_stmt|;
name|assertThat
argument_list|(
name|result
operator|.
name|status
argument_list|()
argument_list|)
operator|.
name|isEqualTo
argument_list|(
name|SEE_OTHER
argument_list|)
expr_stmt|;
name|assertThat
argument_list|(
name|upAuthProvider
argument_list|(
name|app
argument_list|)
operator|.
name|getVerificationToken
argument_list|(
name|email
argument_list|)
argument_list|)
operator|.
name|isNull
argument_list|()
expr_stmt|;
comment|// We should actually be logged in here, but let's ignore that
comment|// as we want to test login too.
name|assertThat
argument_list|(
name|result
operator|.
name|redirectLocation
argument_list|()
argument_list|)
operator|.
name|isEqualTo
argument_list|(
name|Optional
operator|.
name|of
argument_list|(
literal|"/"
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|{
comment|// Log the user in
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|data
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
name|data
operator|.
name|put
argument_list|(
literal|"email"
argument_list|,
name|email
argument_list|)
expr_stmt|;
name|data
operator|.
name|put
argument_list|(
literal|"password"
argument_list|,
name|password
argument_list|)
expr_stmt|;
specifier|final
name|Call
name|doLogin
init|=
name|controllers
operator|.
name|routes
operator|.
name|ApplicationController
operator|.
name|doLogin
argument_list|()
decl_stmt|;
name|Result
name|result
init|=
name|route
argument_list|(
operator|new
name|RequestBuilder
argument_list|()
operator|.
name|method
argument_list|(
name|doLogin
operator|.
name|method
argument_list|()
argument_list|)
operator|.
name|uri
argument_list|(
name|doLogin
operator|.
name|url
argument_list|()
argument_list|)
operator|.
name|bodyForm
argument_list|(
name|data
argument_list|)
argument_list|)
decl_stmt|;
name|assertThat
argument_list|(
name|result
operator|.
name|status
argument_list|()
argument_list|)
operator|.
name|isEqualTo
argument_list|(
name|SEE_OTHER
argument_list|)
expr_stmt|;
name|assertThat
argument_list|(
name|result
operator|.
name|redirectLocation
argument_list|()
argument_list|)
operator|.
name|isEqualTo
argument_list|(
name|Optional
operator|.
name|of
argument_list|(
literal|"/"
argument_list|)
argument_list|)
expr_stmt|;
comment|// Create a Java session from the Scala session
return|return
name|result
operator|.
name|session
argument_list|()
return|;
block|}
block|}
specifier|private
name|TestUsernamePasswordAuthProvider
name|upAuthProvider
parameter_list|(
name|Application
name|app
parameter_list|)
block|{
return|return
name|app
operator|.
name|injector
argument_list|()
operator|.
name|instanceOf
argument_list|(
name|TestUsernamePasswordAuthProvider
operator|.
name|class
argument_list|)
return|;
block|}
specifier|private
name|AbstractUserService
name|userService
parameter_list|(
name|Application
name|app
parameter_list|)
block|{
return|return
name|app
operator|.
name|injector
argument_list|()
operator|.
name|instanceOf
argument_list|(
name|TestUserService
operator|.
name|class
argument_list|)
return|;
block|}
block|}
end_class
end_unit
| 13.213889 | 70 | 0.803658 |
05cb5b45004f2c596843a5bceb248b4a5ca81c1f | 15,614 | /*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.cellbots.directcontrol;
import com.cellbots.R;
import com.cellbots.local.CellDroidManager;
import com.cellbots.remote.AccelerometerView;
import com.cellbots.remote.DpadView;
import com.cellbots.remote.HeadPanControl;
import com.cellbots.remote.HeadPanControl.PanAction;
import com.cellbots.remote.JoystickView;
import com.cellbots.remote.UiView;
import com.cellbots.remote.UiView.UiEventListener;
import com.cellbots.remote.VoiceView;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
/**
* Turns your Cellbot into a pet robot that can obey basic commands and track
* faces. TODO (clchen, css, bendavies): Work out where this should go in the
* workflow.
*
* @author clchen@google.com (Charles L. Chen)
*/
public class CellbotPetActivity extends Activity implements UiEventListener, Callback {
public static final String TAG = "Cellbot Pet";
public static final int VOICE_RECO_CODE = 42;
public static final String PERSONA_IDLE =
"http://personabots.appspot.com/personas/tuby/idle.png";
public static final String PERSONA_READY =
"http://personabots.appspot.com/personas/tuby/ready.png";
public int state = 0;
private LinearLayout mControlsLayout;
private UiView mUiView;
private int previewHeight = 0;
private int previewWidth = 0;
private int previewFormat = 0;
private byte[] mCallbackBuffer;
private ByteArrayOutputStream out;
private WakeLock mWakeLock;
private SurfaceHolder mHolder;
private FrameLayout mFrame;
private WebView mWebView;
private ImageView mImageView;
private SurfaceView mPreview;
private Camera mCamera;
private Rect r;
private TextToSpeech mTts;
private VoiceView mVoiceView;
private Face[] faces = new Face[1];
private FaceDetector fd;
private byte[] imageBytes;
private Bitmap previewImage;
private boolean userWasVisible = false;
private boolean voiceControlsActive = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTts = new TextToSpeech(this, new OnInitListener() {
@Override
public void onInit(int arg0) {
mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String arg0) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (voiceControlsActive) {
mVoiceView.startListening();
}
}
});
}
});
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "foo");
mTts.speak("Shall we play a game?", 0, hashMap);
}
});
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "Cellbot Eyes");
mWakeLock.acquire();
out = new ByteArrayOutputStream();
setContentView(R.layout.eyes_main);
mPreview = (SurfaceView) findViewById(R.id.eyes_preview);
mHolder = mPreview.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mFrame = (FrameLayout) findViewById(R.id.eyes_frame);
Display disp = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
mVoiceView = new VoiceView(this, this, false, disp.getWidth(), disp.getHeight());
mVoiceView.setClickable(false);
mFrame.addView(mVoiceView);
mImageView = new ImageView(this);
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
LayoutParams params = new LayoutParams(width, height);
mImageView.setLayoutParams(params);
mImageView.setScaleType(ScaleType.FIT_CENTER);
mImageView.setImageResource(R.drawable.persona_tuby_ready);
mImageView.setBackgroundColor(Color.BLACK);
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (voiceControlsActive) {
mVoiceView.stopListening();
onStopRequested();
mImageView.setImageResource(R.drawable.persona_tuby_idle);
voiceControlsActive = false;
} else {
mVoiceView.startListening();
mImageView.setImageResource(R.drawable.persona_tuby_ready);
voiceControlsActive = true;
}
}
});
mFrame.addView(mImageView);
voiceControlsActive = true;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mWakeLock != null) {
mWakeLock.release();
}
if (mTts != null) {
mTts.shutdown();
}
if (mVoiceView != null) {
mVoiceView.stopListening();
}
}
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
mHolder.setFixedSize(w, h);
// Start the preview
Parameters params = mCamera.getParameters();
previewHeight = params.getPreviewSize().height;
previewWidth = params.getPreviewSize().width;
previewFormat = params.getPreviewFormat();
// Crop the edges of the picture to reduce the image size
r = new Rect(80, 30, previewWidth - 80, previewHeight - 30);
mCallbackBuffer = new byte[460800];
mCamera.setParameters(params);
mCamera.setPreviewCallbackWithBuffer(new PreviewCallback() {
public void onPreviewFrame(byte[] imageData, Camera arg1) {
trackface(imageData);
if (mCamera != null) {
mCamera.addCallbackBuffer(mCallbackBuffer);
}
}
});
mCamera.addCallbackBuffer(mCallbackBuffer);
mCamera.startPreview();
}
private void trackface(byte[] imageData) {
YuvImage yuvImage = new YuvImage(
imageData, previewFormat, previewWidth, previewHeight, null);
yuvImage.compressToJpeg(r, 50, out); // Tweak the quality here - 50 for
// detection
imageBytes = out.toByteArray();
previewImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
if (fd == null) {
fd = new FaceDetector(previewImage.getWidth(), previewImage.getHeight(), 1);
}
int faceCount = fd.findFaces(previewImage, faces);
if (faceCount > 0) {
if (!userWasVisible) {
userWasVisible = true;
speak("Peek a boo, I see you!");
}
PointF p = new PointF();
faces[0].getMidPoint(p);
if (p.x < 150) {
CellDroidManager.sendDirectCommand("w -5 5");
} else if (p.x > 350) {
CellDroidManager.sendDirectCommand("w 5 -5");
} else {
CellDroidManager.sendDirectCommand("s");
}
} else {
if (userWasVisible) {
userWasVisible = false;
speak("Hey, where did you go?");
CellDroidManager.sendDirectCommand("s");
}
}
out.reset();
previewImage.recycle();
}
private void speak(String text) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mVoiceView.stopListening();
}
});
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "foo");
mTts.speak(text, 0, hashMap);
}
public void switchToAccelerometerControl() {
mControlsLayout.removeAllViews();
Display disp = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
mUiView = new AccelerometerView(this, this, false, disp.getWidth(), disp.getHeight());
mControlsLayout.addView(mUiView);
}
public void switchToDpadControl() {
mControlsLayout.removeAllViews();
Display disp = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
mUiView = new DpadView(this, this, false, disp.getWidth(), disp.getHeight());
mControlsLayout.addView(mUiView);
}
public void switchToVoiceControl() {
mControlsLayout.removeAllViews();
Display disp = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
mUiView = new VoiceView(this, this, false, disp.getWidth(), disp.getHeight());
mControlsLayout.addView(mUiView);
}
public void switchToJoystickControl() {
mControlsLayout.removeAllViews();
Display disp = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
mUiView = new JoystickView(this, this, false, disp.getWidth(), disp.getHeight());
mControlsLayout.addView(mUiView);
// This looks weird, but if we don't do this, the joystick view will
// not draw its initial state properly.
this.openOptionsMenu();
this.closeOptionsMenu();
}
@Override
public void onWheelVelocitySetRequested(float direction, float speed) {
if (direction >= 0 && direction <= 90) {
CellDroidManager.sendDirectCommand(
"w " + (int) speed + " " + (int) (speed - direction / 90 * speed));
} else if (direction > 90) {
CellDroidManager.sendDirectCommand(
"w -" + (int) speed + " -" + (int) (speed - (180 - direction) / 90 * speed));
} else if (direction < 0 && direction >= -90) {
CellDroidManager.sendDirectCommand(
"w " + (int) (speed - Math.abs(direction) / 90 * speed) + " " + (int) speed);
} else if (direction < -90) {
CellDroidManager.sendDirectCommand(
"w -" + (int) (speed - (180 - Math.abs(direction)) / 90 * speed) + " -"
+ (int) speed);
}
}
@Override
public void onStopRequested() {
CellDroidManager.sendDirectCommand("s");
}
@Override
public void onActionRequested(int action, String values) {
switch (action) {
case UiEventListener.ACTION_FORWARD:
CellDroidManager.sendDirectCommand("f");
break;
case UiEventListener.ACTION_BACKWARD:
CellDroidManager.sendDirectCommand("b");
break;
case UiEventListener.ACTION_LEFT:
CellDroidManager.sendDirectCommand("l");
break;
case UiEventListener.ACTION_RIGHT:
CellDroidManager.sendDirectCommand("r");
break;
}
}
private HeadPanControl.HeadPanListener panListener = new HeadPanControl.HeadPanListener() {
@Override
public void onPan(PanAction action) {
if (action == PanAction.PAN_CENTER) {
CellDroidManager.sendDirectCommand("hc");
} else if (action == PanAction.PAN_LEFT) {
CellDroidManager.sendDirectCommand("hl");
} else if (action == PanAction.PAN_RIGHT) {
CellDroidManager.sendDirectCommand("hr");
} else if (action == PanAction.PAN_UP) {
CellDroidManager.sendDirectCommand("hu");
} else if (action == PanAction.PAN_DOWN) {
CellDroidManager.sendDirectCommand("hd");
} else if (action == PanAction.PAN_NONE) {
CellDroidManager.sendDirectCommand("hs");
}
}
};
/*
* (non-Javadoc)
* @see
* com.cellbots.remote.UiView.UiEventListener#onSwitchInterfaceRequested
* (int)
*/
@Override
public void onSwitchInterfaceRequested(int interfaceId) {
switch (interfaceId) {
case UiEventListener.INTERFACE_ACCELEROMETER:
switchToAccelerometerControl();
break;
case UiEventListener.INTERFACE_DPAD:
switchToDpadControl();
break;
case UiEventListener.INTERFACE_JOYSTICK:
switchToJoystickControl();
break;
case UiEventListener.INTERFACE_VOICE:
switchToVoiceControl();
break;
}
}
/*
* (non-Javadoc)
* @see com.cellbots.remote.UiView.UiEventListener#onPopupWindowRequested()
*/
@Override
public void onPopupWindowRequested() {
}
}
| 35.008969 | 97 | 0.620405 |
660b454808447853ac062e663b20e4032f30eacd | 8,555 | /*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.shared;
import dan200.shared.IComputerCraftEntity;
import dan200.shared.ItemDisk;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityItem;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.IInventory;
import net.minecraft.src.Item;
import net.minecraft.src.ItemRecord;
import net.minecraft.src.ItemStack;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.Packet;
import net.minecraft.src.Packet230ModLoader;
import net.minecraft.src.TileEntity;
import net.minecraft.src.mod_ComputerCraft;
public class TileEntityDiskDrive
extends TileEntity
implements IInventory,
IComputerCraftEntity
{
private ItemStack diskStack = null;
private boolean m_firstFrame = true;
private int m_clientDiskLight = 0;
public void func_31004_j() {
super.func_31004_j();
if (mod_ComputerCraft.isMultiplayerClient()) {
Packet230ModLoader packet = new Packet230ModLoader();
packet.packetType = 5;
packet.dataInt = new int[]{this.xCoord, this.yCoord, this.zCoord};
mod_ComputerCraft.sendToServer(packet);
}
}
public Packet getDescriptionPacket() {
return this.createDiskLightPacket();
}
@Override
public int getSizeInventory() {
return 1;
}
@Override
public ItemStack getStackInSlot(int i) {
return this.diskStack;
}
@Override
public ItemStack decrStackSize(int i, int j) {
ItemStack disk = this.diskStack;
this.setInventorySlotContents(i, null);
return disk;
}
@Override
public void setInventorySlotContents(int i, ItemStack itemstack) {
boolean hadDisk = this.hasDisk();
this.diskStack = itemstack;
if (!mod_ComputerCraft.isMultiplayerClient()) {
mod_ComputerCraft.notifyBlockChange(this.worldObj, this.xCoord, this.yCoord, this.zCoord, mod_ComputerCraft.diskDrive.blockID);
if (mod_ComputerCraft.isMultiplayerServer()) {
int newDiskLight = 0;
if (this.hasAnything()) {
int n = newDiskLight = this.hasDisk() ? 1 : 2;
}
if (newDiskLight != this.m_clientDiskLight) {
this.m_clientDiskLight = newDiskLight;
Packet230ModLoader diskLight = this.createDiskLightPacket();
mod_ComputerCraft.sendToAllPlayers(diskLight);
}
}
}
}
@Override
public String getInvName() {
return "Disk Drive";
}
public void readFromNBT(NBTTagCompound nbttagcompound) {
super.readFromNBT(nbttagcompound);
NBTTagCompound item = nbttagcompound.getCompoundTag("item");
this.diskStack = new ItemStack(item);
//System.out.println("Disk Drive Read: Item ID " + diskStack.itemID);
//if the item id is 0 we have nothing in it
if (diskStack.itemID == 0)
diskStack = null;
}
public void writeToNBT(NBTTagCompound nbttagcompound) {
super.writeToNBT(nbttagcompound);
NBTTagCompound item = new NBTTagCompound();
if (this.diskStack != null) {
//System.out.println("Disk Drive Save: Item ID " + diskStack.itemID);
item = this.diskStack.writeToNBT(item);
} else {
diskStack = new ItemStack(0, 0, 0);
//System.out.println("Disk Drive Save: Item ID " + diskStack.itemID);
item = this.diskStack.writeToNBT(item);
this.diskStack = null;
}
nbttagcompound.setCompoundTag("item", item);
}
@Override
public int getInventoryStackLimit() {
return 64;
}
@Override
public boolean canInteractWith(EntityPlayer entityplayer) {
if (this.worldObj.getBlockTileEntity(this.xCoord, this.yCoord, this.zCoord) != this) {
return false;
}
return entityplayer.getDistance((double)this.xCoord + 0.5, (double)this.yCoord + 0.5, (double)this.zCoord + 0.5) <= 64.0;
}
public boolean hasAnything() {
if (!mod_ComputerCraft.isMultiplayerClient()) {
return this.diskStack != null;
}
return this.m_clientDiskLight > 0;
}
public boolean hasDisk() {
if (!mod_ComputerCraft.isMultiplayerClient()) {
return this.getDataDiskID() >= 0 || this.getAudioDiscRecordName() != null;
}
return this.m_clientDiskLight == 1;
}
public void ejectContents(boolean destroyed) {
if (mod_ComputerCraft.isMultiplayerClient()) {
return;
}
if (this.diskStack != null) {
ItemStack disks = this.diskStack;
this.setInventorySlotContents(0, null);
int xOff = 0;
int zOff = 0;
if (!destroyed) {
int metaData = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord);
switch (metaData) {
case 2: {
zOff = -1;
break;
}
case 3: {
zOff = 1;
break;
}
case 4: {
xOff = -1;
break;
}
case 5: {
xOff = 1;
break;
}
}
}
double x = (double)this.xCoord + 0.5 + (double)xOff * 0.5;
double y = (double)this.yCoord + 0.75;
double z = (double)this.zCoord + 0.5 + (double)zOff * 0.5;
EntityItem entityitem = new EntityItem(this.worldObj, x, y, z, disks);
entityitem.motionX = (double)xOff * 0.15;
entityitem.motionY = 0.0;
entityitem.motionZ = (double)zOff * 0.15;
this.worldObj.entityJoinedWorld((Entity)entityitem);
if (!destroyed) {
this.worldObj.func_28106_e(1000, this.xCoord, this.yCoord, this.zCoord, 0);
}
}
}
public int getDataDiskID() {
if (this.diskStack != null && this.diskStack.itemID == mod_ComputerCraft.disk.shiftedIndex) {
return ItemDisk.getDiskID(this.diskStack, this.worldObj);
}
return -1;
}
public String getAudioDiscRecordName() {
Item item;
if (this.diskStack != null && (item = Item.itemsList[this.diskStack.itemID]) instanceof ItemRecord) {
ItemRecord record = (ItemRecord)item;
return record.recordName;
}
return null;
}
public void updateEntity() {
if (this.m_firstFrame) {
if (!mod_ComputerCraft.isMultiplayerClient()) {
this.m_clientDiskLight = 0;
if (this.hasAnything()) {
this.m_clientDiskLight = this.hasDisk() ? 1 : 2;
}
mod_ComputerCraft.notifyBlockChange(this.worldObj, this.xCoord, this.yCoord, this.zCoord, mod_ComputerCraft.diskDrive.blockID);
}
this.m_firstFrame = false;
}
}
private Packet230ModLoader createDiskLightPacket() {
Packet230ModLoader packet = new Packet230ModLoader();
packet.packetType = 8;
packet.dataInt = new int[]{this.xCoord, this.yCoord, this.zCoord, this.m_clientDiskLight};
return packet;
}
private void updateClient(EntityPlayer player) {
if (mod_ComputerCraft.isMultiplayerServer()) {
Packet230ModLoader diskLight = this.createDiskLightPacket();
mod_ComputerCraft.sendToPlayer(player, diskLight);
}
}
@Override
public void handlePacket(Packet230ModLoader packet, EntityPlayer player) {
if (mod_ComputerCraft.isMultiplayerServer()) {
switch (packet.packetType) {
case 5: {
this.updateClient(player);
break;
}
}
} else {
switch (packet.packetType) {
case 8: {
this.m_clientDiskLight = packet.dataInt[3];
mod_ComputerCraft.notifyBlockChange(this.worldObj, this.xCoord, this.yCoord, this.zCoord, mod_ComputerCraft.diskDrive.blockID);
break;
}
}
}
}
}
| 34.495968 | 147 | 0.585856 |
09f157c20c77c96ec3256f79df365a33890d0825 | 306 | package com.minlia.module.data.batis.event;
import org.springframework.context.ApplicationEvent;
/**
* @author will
*/
public class BeforeCreatedEvent extends ApplicationEvent{
private static final long serialVersionUID = 1L;
public BeforeCreatedEvent(Object source) {
super(source);
}
}
| 16.105263 | 57 | 0.75817 |
31b936e8146937f3bae531dc268a73988ed35ec8 | 517 | package com.tinllst.zkbackup.constant;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author tinllst
* @date 9:11 2020/1/13
*/
@PropertySource(value = {"file:zookeeper.properties"})
@Component
@ConfigurationProperties(prefix = "top.zookeeper")
@Data
public class ZkConstant {
private String serverUrl;
private String excludeNode = "";
}
| 25.85 | 75 | 0.783366 |
c4ee4a74a3697691813f25c9f9ad2354955414bd | 29,835 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: IGDBProtoFile.proto
package proto;
/**
* Protobuf type {@code proto.ListEntry}
*/
public final class ListEntry extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:proto.ListEntry)
ListEntryOrBuilder {
// Use ListEntry.newBuilder() to construct.
private ListEntry(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListEntry() {
id_ = 0L;
description_ = "";
position_ = 0;
private_ = false;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return proto.IGDBProtoFile.internal_static_proto_ListEntry_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return proto.IGDBProtoFile.internal_static_proto_ListEntry_fieldAccessorTable
.ensureFieldAccessorsInitialized(
proto.ListEntry.class, proto.ListEntry.Builder.class);
}
public static final int ID_FIELD_NUMBER = 1;
private long id_;
/**
* <code>optional uint64 id = 1;</code>
*/
public long getId() {
return id_;
}
public static final int DESCRIPTION_FIELD_NUMBER = 2;
private volatile java.lang.Object description_;
/**
* <code>optional string description = 2;</code>
*/
public java.lang.String getDescription() {
java.lang.Object ref = description_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
description_ = s;
return s;
}
}
/**
* <code>optional string description = 2;</code>
*/
public com.google.protobuf.ByteString
getDescriptionBytes() {
java.lang.Object ref = description_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
description_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int GAME_FIELD_NUMBER = 3;
private proto.Game game_;
/**
* <code>optional .proto.Game game = 3;</code>
*/
public boolean hasGame() {
return game_ != null;
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public proto.Game getGame() {
return game_ == null ? proto.Game.getDefaultInstance() : game_;
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public proto.GameOrBuilder getGameOrBuilder() {
return getGame();
}
public static final int LIST_FIELD_NUMBER = 4;
private proto.List list_;
/**
* <code>optional .proto.List list = 4;</code>
*/
public boolean hasList() {
return list_ != null;
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public proto.List getList() {
return list_ == null ? proto.List.getDefaultInstance() : list_;
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public proto.ListOrBuilder getListOrBuilder() {
return getList();
}
public static final int PLATFORM_FIELD_NUMBER = 5;
private proto.Platform platform_;
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public boolean hasPlatform() {
return platform_ != null;
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public proto.Platform getPlatform() {
return platform_ == null ? proto.Platform.getDefaultInstance() : platform_;
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public proto.PlatformOrBuilder getPlatformOrBuilder() {
return getPlatform();
}
public static final int POSITION_FIELD_NUMBER = 6;
private int position_;
/**
* <code>optional int32 position = 6;</code>
*/
public int getPosition() {
return position_;
}
public static final int PRIVATE_FIELD_NUMBER = 7;
private boolean private_;
/**
* <code>optional bool private = 7;</code>
*/
public boolean getPrivate() {
return private_;
}
public static final int USER_FIELD_NUMBER = 8;
private proto.User user_;
/**
* <code>optional .proto.User user = 8;</code>
*/
public boolean hasUser() {
return user_ != null;
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public proto.User getUser() {
return user_ == null ? proto.User.getDefaultInstance() : user_;
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public proto.UserOrBuilder getUserOrBuilder() {
return getUser();
}
public static proto.ListEntry parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static proto.ListEntry parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static proto.ListEntry parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static proto.ListEntry parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static proto.ListEntry parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static proto.ListEntry parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static proto.ListEntry parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static proto.ListEntry parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static proto.ListEntry parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static proto.ListEntry parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(proto.ListEntry prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code proto.ListEntry}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:proto.ListEntry)
proto.ListEntryOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return proto.IGDBProtoFile.internal_static_proto_ListEntry_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return proto.IGDBProtoFile.internal_static_proto_ListEntry_fieldAccessorTable
.ensureFieldAccessorsInitialized(
proto.ListEntry.class, proto.ListEntry.Builder.class);
}
// Construct using proto.ListEntry.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
id_ = 0L;
description_ = "";
if (gameBuilder_ == null) {
game_ = null;
} else {
game_ = null;
gameBuilder_ = null;
}
if (listBuilder_ == null) {
list_ = null;
} else {
list_ = null;
listBuilder_ = null;
}
if (platformBuilder_ == null) {
platform_ = null;
} else {
platform_ = null;
platformBuilder_ = null;
}
position_ = 0;
private_ = false;
if (userBuilder_ == null) {
user_ = null;
} else {
user_ = null;
userBuilder_ = null;
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return proto.IGDBProtoFile.internal_static_proto_ListEntry_descriptor;
}
public proto.ListEntry getDefaultInstanceForType() {
return proto.ListEntry.getDefaultInstance();
}
public proto.ListEntry build() {
proto.ListEntry result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public proto.ListEntry buildPartial() {
proto.ListEntry result = new proto.ListEntry(this);
result.id_ = id_;
result.description_ = description_;
if (gameBuilder_ == null) {
result.game_ = game_;
} else {
result.game_ = gameBuilder_.build();
}
if (listBuilder_ == null) {
result.list_ = list_;
} else {
result.list_ = listBuilder_.build();
}
if (platformBuilder_ == null) {
result.platform_ = platform_;
} else {
result.platform_ = platformBuilder_.build();
}
result.position_ = position_;
result.private_ = private_;
if (userBuilder_ == null) {
result.user_ = user_;
} else {
result.user_ = userBuilder_.build();
}
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
private long id_ ;
/**
* <code>optional uint64 id = 1;</code>
*/
public long getId() {
return id_;
}
/**
* <code>optional uint64 id = 1;</code>
*/
public Builder setId(long value) {
id_ = value;
onChanged();
return this;
}
/**
* <code>optional uint64 id = 1;</code>
*/
public Builder clearId() {
id_ = 0L;
onChanged();
return this;
}
private java.lang.Object description_ = "";
/**
* <code>optional string description = 2;</code>
*/
public java.lang.String getDescription() {
java.lang.Object ref = description_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
description_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string description = 2;</code>
*/
public com.google.protobuf.ByteString
getDescriptionBytes() {
java.lang.Object ref = description_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
description_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string description = 2;</code>
*/
public Builder setDescription(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
description_ = value;
onChanged();
return this;
}
/**
* <code>optional string description = 2;</code>
*/
public Builder clearDescription() {
description_ = getDefaultInstance().getDescription();
onChanged();
return this;
}
/**
* <code>optional string description = 2;</code>
*/
public Builder setDescriptionBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
description_ = value;
onChanged();
return this;
}
private proto.Game game_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
proto.Game, proto.Game.Builder, proto.GameOrBuilder> gameBuilder_;
/**
* <code>optional .proto.Game game = 3;</code>
*/
public boolean hasGame() {
return gameBuilder_ != null || game_ != null;
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public proto.Game getGame() {
if (gameBuilder_ == null) {
return game_ == null ? proto.Game.getDefaultInstance() : game_;
} else {
return gameBuilder_.getMessage();
}
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public Builder setGame(proto.Game value) {
if (gameBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
game_ = value;
onChanged();
} else {
gameBuilder_.setMessage(value);
}
return this;
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public Builder setGame(
proto.Game.Builder builderForValue) {
if (gameBuilder_ == null) {
game_ = builderForValue.build();
onChanged();
} else {
gameBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public Builder mergeGame(proto.Game value) {
if (gameBuilder_ == null) {
if (game_ != null) {
game_ =
proto.Game.newBuilder(game_).mergeFrom(value).buildPartial();
} else {
game_ = value;
}
onChanged();
} else {
gameBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public Builder clearGame() {
if (gameBuilder_ == null) {
game_ = null;
onChanged();
} else {
game_ = null;
gameBuilder_ = null;
}
return this;
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public proto.Game.Builder getGameBuilder() {
onChanged();
return getGameFieldBuilder().getBuilder();
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
public proto.GameOrBuilder getGameOrBuilder() {
if (gameBuilder_ != null) {
return gameBuilder_.getMessageOrBuilder();
} else {
return game_ == null ?
proto.Game.getDefaultInstance() : game_;
}
}
/**
* <code>optional .proto.Game game = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
proto.Game, proto.Game.Builder, proto.GameOrBuilder>
getGameFieldBuilder() {
if (gameBuilder_ == null) {
gameBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
proto.Game, proto.Game.Builder, proto.GameOrBuilder>(
getGame(),
getParentForChildren(),
isClean());
game_ = null;
}
return gameBuilder_;
}
private proto.List list_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
proto.List, proto.List.Builder, proto.ListOrBuilder> listBuilder_;
/**
* <code>optional .proto.List list = 4;</code>
*/
public boolean hasList() {
return listBuilder_ != null || list_ != null;
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public proto.List getList() {
if (listBuilder_ == null) {
return list_ == null ? proto.List.getDefaultInstance() : list_;
} else {
return listBuilder_.getMessage();
}
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public Builder setList(proto.List value) {
if (listBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
list_ = value;
onChanged();
} else {
listBuilder_.setMessage(value);
}
return this;
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public Builder setList(
proto.List.Builder builderForValue) {
if (listBuilder_ == null) {
list_ = builderForValue.build();
onChanged();
} else {
listBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public Builder mergeList(proto.List value) {
if (listBuilder_ == null) {
if (list_ != null) {
list_ =
proto.List.newBuilder(list_).mergeFrom(value).buildPartial();
} else {
list_ = value;
}
onChanged();
} else {
listBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public Builder clearList() {
if (listBuilder_ == null) {
list_ = null;
onChanged();
} else {
list_ = null;
listBuilder_ = null;
}
return this;
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public proto.List.Builder getListBuilder() {
onChanged();
return getListFieldBuilder().getBuilder();
}
/**
* <code>optional .proto.List list = 4;</code>
*/
public proto.ListOrBuilder getListOrBuilder() {
if (listBuilder_ != null) {
return listBuilder_.getMessageOrBuilder();
} else {
return list_ == null ?
proto.List.getDefaultInstance() : list_;
}
}
/**
* <code>optional .proto.List list = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
proto.List, proto.List.Builder, proto.ListOrBuilder>
getListFieldBuilder() {
if (listBuilder_ == null) {
listBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
proto.List, proto.List.Builder, proto.ListOrBuilder>(
getList(),
getParentForChildren(),
isClean());
list_ = null;
}
return listBuilder_;
}
private proto.Platform platform_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
proto.Platform, proto.Platform.Builder, proto.PlatformOrBuilder> platformBuilder_;
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public boolean hasPlatform() {
return platformBuilder_ != null || platform_ != null;
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public proto.Platform getPlatform() {
if (platformBuilder_ == null) {
return platform_ == null ? proto.Platform.getDefaultInstance() : platform_;
} else {
return platformBuilder_.getMessage();
}
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public Builder setPlatform(proto.Platform value) {
if (platformBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
platform_ = value;
onChanged();
} else {
platformBuilder_.setMessage(value);
}
return this;
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public Builder setPlatform(
proto.Platform.Builder builderForValue) {
if (platformBuilder_ == null) {
platform_ = builderForValue.build();
onChanged();
} else {
platformBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public Builder mergePlatform(proto.Platform value) {
if (platformBuilder_ == null) {
if (platform_ != null) {
platform_ =
proto.Platform.newBuilder(platform_).mergeFrom(value).buildPartial();
} else {
platform_ = value;
}
onChanged();
} else {
platformBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public Builder clearPlatform() {
if (platformBuilder_ == null) {
platform_ = null;
onChanged();
} else {
platform_ = null;
platformBuilder_ = null;
}
return this;
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public proto.Platform.Builder getPlatformBuilder() {
onChanged();
return getPlatformFieldBuilder().getBuilder();
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
public proto.PlatformOrBuilder getPlatformOrBuilder() {
if (platformBuilder_ != null) {
return platformBuilder_.getMessageOrBuilder();
} else {
return platform_ == null ?
proto.Platform.getDefaultInstance() : platform_;
}
}
/**
* <code>optional .proto.Platform platform = 5;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
proto.Platform, proto.Platform.Builder, proto.PlatformOrBuilder>
getPlatformFieldBuilder() {
if (platformBuilder_ == null) {
platformBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
proto.Platform, proto.Platform.Builder, proto.PlatformOrBuilder>(
getPlatform(),
getParentForChildren(),
isClean());
platform_ = null;
}
return platformBuilder_;
}
private int position_ ;
/**
* <code>optional int32 position = 6;</code>
*/
public int getPosition() {
return position_;
}
/**
* <code>optional int32 position = 6;</code>
*/
public Builder setPosition(int value) {
position_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 position = 6;</code>
*/
public Builder clearPosition() {
position_ = 0;
onChanged();
return this;
}
private boolean private_ ;
/**
* <code>optional bool private = 7;</code>
*/
public boolean getPrivate() {
return private_;
}
/**
* <code>optional bool private = 7;</code>
*/
public Builder setPrivate(boolean value) {
private_ = value;
onChanged();
return this;
}
/**
* <code>optional bool private = 7;</code>
*/
public Builder clearPrivate() {
private_ = false;
onChanged();
return this;
}
private proto.User user_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
proto.User, proto.User.Builder, proto.UserOrBuilder> userBuilder_;
/**
* <code>optional .proto.User user = 8;</code>
*/
public boolean hasUser() {
return userBuilder_ != null || user_ != null;
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public proto.User getUser() {
if (userBuilder_ == null) {
return user_ == null ? proto.User.getDefaultInstance() : user_;
} else {
return userBuilder_.getMessage();
}
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public Builder setUser(proto.User value) {
if (userBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
user_ = value;
onChanged();
} else {
userBuilder_.setMessage(value);
}
return this;
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public Builder setUser(
proto.User.Builder builderForValue) {
if (userBuilder_ == null) {
user_ = builderForValue.build();
onChanged();
} else {
userBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public Builder mergeUser(proto.User value) {
if (userBuilder_ == null) {
if (user_ != null) {
user_ =
proto.User.newBuilder(user_).mergeFrom(value).buildPartial();
} else {
user_ = value;
}
onChanged();
} else {
userBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public Builder clearUser() {
if (userBuilder_ == null) {
user_ = null;
onChanged();
} else {
user_ = null;
userBuilder_ = null;
}
return this;
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public proto.User.Builder getUserBuilder() {
onChanged();
return getUserFieldBuilder().getBuilder();
}
/**
* <code>optional .proto.User user = 8;</code>
*/
public proto.UserOrBuilder getUserOrBuilder() {
if (userBuilder_ != null) {
return userBuilder_.getMessageOrBuilder();
} else {
return user_ == null ?
proto.User.getDefaultInstance() : user_;
}
}
/**
* <code>optional .proto.User user = 8;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
proto.User, proto.User.Builder, proto.UserOrBuilder>
getUserFieldBuilder() {
if (userBuilder_ == null) {
userBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
proto.User, proto.User.Builder, proto.UserOrBuilder>(
getUser(),
getParentForChildren(),
isClean());
user_ = null;
}
return userBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:proto.ListEntry)
}
// @@protoc_insertion_point(class_scope:proto.ListEntry)
private static final proto.ListEntry DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new proto.ListEntry();
}
public static proto.ListEntry getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListEntry>
PARSER = new com.google.protobuf.AbstractParser<ListEntry>() {
public ListEntry parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(
builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListEntry> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListEntry> getParserForType() {
return PARSER;
}
public proto.ListEntry getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| 27.599445 | 90 | 0.608782 |
3ee5b0db4d9f77e8cf5b0b7a50296227867f925b | 517 | package utils;
import java.util.ArrayList;
public class Factorial {
private static ArrayList<Long> initFactList() {
ArrayList<Long> result = new ArrayList<Long>();
result.add(1l);
return result;
}
public static ArrayList<Long> factList = initFactList();
public static long fact(int i) {
if (i >= factList.size())
factList.add(1l * i * fact(i - 1));
return factList.get(i);
}
public static long binomialCoefficient(int n, int p) {
return n < p ? 0 : fact(n) / (fact(p) * fact(n - p));
}
}
| 19.884615 | 57 | 0.659574 |
b2b1727c21d58b7359063f4431a45ad34cb3256b | 24,877 | package com.github.ddth.dao.jdbc;
import com.github.ddth.dao.jdbc.impl.UniversalRowMapper;
import com.github.ddth.dao.utils.DaoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* An interface that provides APIs to interact with the underlying JDBC.
*
* @author Thanh Nguyen <btnguyen2k@gmail.com>
* @since 0.7.0
*/
public interface IJdbcHelper {
/**
* Name of the "default" data source.
*/
String DEFAULT_DATASOURCE = "DEFAULT";
/**
* Obtain a {@link Connection} instance from the "default" data source, without transaction
* ({@code autoCommit=false}).
*
* @return
* @throws DaoException
*/
default Connection getConnection() throws DaoException {
return getConnection(DEFAULT_DATASOURCE, false);
}
/**
* Obtain a {@link Connection} instance from the specified data source, without transaction
* ({@code autoCommit=false}).
*
* @param dsName
* @return
* @throws DaoException
* @since 0.8.1
*/
default Connection getConnection(String dsName) throws DaoException {
return getConnection(dsName, false);
}
/**
* Obtain a {@link Connection} instance from the "default" data source, starts a transaction if
* specified.
*
* @param startTransaction
* @return
* @throws DaoException
*/
default Connection getConnection(boolean startTransaction) throws DaoException {
return getConnection(DEFAULT_DATASOURCE, startTransaction);
}
/**
* Obtain a {@link Connection} instance from the specified data source, starts a transaction if
* specified.
*
* @param dsName
* @param startTransaction
* @return
* @throws DaoException
* @since 0.8.1
*/
Connection getConnection(String dsName, boolean startTransaction) throws DaoException;
/**
* Return a previously obtained {@link Connection} via
* {@link #getConnection()} or {@link #getConnection(boolean)}.
*
* @param conn
* @throws DaoException
*/
void returnConnection(Connection conn) throws DaoException;
/**
* Start a transaction. Has no effect if already in a transaction.
*
* @param conn
* @return
* @throws DaoException
*/
boolean startTransaction(Connection conn) throws DaoException;
/**
* Commit a transaction. Has no effect if not in a transaction.
*
* <p>
* Note: {@code autoCommit} is set to {@code true} after calling this
* method.
* </p>
*
* @param conn
* @return
* @throws DaoException
*/
boolean commitTransaction(Connection conn) throws DaoException;
/**
* Rollback a transaction. Has no effect if not in a transaction.
*
* <p>
* Note: {@code autoCommit} is set to {@code true} after calling this
* method.
* </p>
*
* @param conn
* @return
* @throws DaoException
*/
boolean rollbackTransaction(Connection conn) throws DaoException;
/*----------------------------------------------------------------------*/
/**
* Execute a non-SELECT statement.
*
* @param sql
* @param bindValues index-based bind values
* @return DaoException
*/
int execute(String sql, Object... bindValues) throws DaoException;
/**
* Execute a non-SELECT statement.
*
* @param sql
* @param bindValues name-based bind values
* @return DaoException
* @since 0.8.0
*/
int execute(String sql, Map<String, ?> bindValues) throws DaoException;
/**
* Execute a non-SELECT statement.
*
* @param conn
* @param sql
* @param bindValues index-based bind values
* @return number of affected rows
* @throws DaoException
*/
int execute(Connection conn, String sql, Object... bindValues) throws DaoException;
/**
* Execute a non-SELECT statement.
*
* @param conn
* @param sql
* @param bindValues name-based bind values
* @return
* @throws DaoException
*/
int execute(Connection conn, String sql, Map<String, ?> bindValues) throws DaoException;
/*----------------------------------------------------------------------*/
/**
* Execute a SELECT statement.
*
* @param rowMapper to map the {@link ResultSet} to object
* @param sql
* @param bindValues index-based bind values
* @return
* @throws DaoException
*/
<T> List<T> executeSelect(IRowMapper<T> rowMapper, String sql, Object... bindValues) throws DaoException;
/**
* Execute a SELECT statement.
*
* @param rowMapper to map the {@link ResultSet} to object
* @param sql
* @param bindValues name-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
<T> List<T> executeSelect(IRowMapper<T> rowMapper, String sql, Map<String, ?> bindValues) throws DaoException;
/**
* Execute a SELECT statement.
*
* @param rowMapper to map the {@link ResultSet} to object
* @param conn
* @param sql
* @param bindValues index-based bind values
* @return
* @throws DaoException
*/
<T> List<T> executeSelect(IRowMapper<T> rowMapper, Connection conn, String sql, Object... bindValues)
throws DaoException;
/**
* Execute a SELECT statement.
*
* @param rowMapper to map the {@link ResultSet} to object
* @param conn
* @param sql
* @param bindValues name-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
<T> List<T> executeSelect(IRowMapper<T> rowMapper, Connection conn, String sql, Map<String, ?> bindValues)
throws DaoException;
/*----------------------------------------------------------------------*/
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, String sql, Object... bindValues)
throws DaoException {
return executeSelectAsStream(rowMapper, -1, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, int fetchSize, String sql,
Object... bindValues) throws DaoException {
return executeSelectAsStream(rowMapper, getConnection(), true, fetchSize, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param conn
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, Connection conn, String sql,
Object... bindValues) throws DaoException {
return executeSelectAsStream(rowMapper, conn, false, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param conn
* @param autoCloseConnection if {@code true} the supplied {@link Connection} will be automatically closed when
* the returned {@link Stream} closes.
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.5.1
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, Connection conn, boolean autoCloseConnection,
String sql, Object... bindValues) throws DaoException {
return executeSelectAsStream(rowMapper, conn, autoCloseConnection, -1, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param conn
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, Connection conn, int fetchSize, String sql,
Object... bindValues) throws DaoException {
return executeSelectAsStream(rowMapper, conn, false, fetchSize, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param conn
* @param autoCloseConnection if {@code true} the supplied {@link Connection} will be automatically closed when
* the returned {@link Stream} closes.
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.5.1
*/
<T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, Connection conn, boolean autoCloseConnection,
int fetchSize, String sql, Object... bindValues) throws DaoException;
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, String sql, Map<String, ?> bindValues)
throws DaoException {
return executeSelectAsStream(rowMapper, -1, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, int fetchSize, String sql,
Map<String, ?> bindValues) throws DaoException {
return executeSelectAsStream(rowMapper, getConnection(), true, fetchSize, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param conn
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, Connection conn, String sql,
Map<String, ?> bindValues) throws DaoException {
return executeSelectAsStream(rowMapper, conn, false, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param conn
* @param autoCloseConnection if {@code true} the supplied {@link Connection} will be automatically closed when
* the returned {@link Stream} closes.
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.5.1
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, Connection conn, boolean autoCloseConnection,
String sql, Map<String, ?> bindValues) throws DaoException {
return executeSelectAsStream(rowMapper, conn, autoCloseConnection, -1, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param conn
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default <T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, Connection conn, int fetchSize, String sql,
Map<String, ?> bindValues) throws DaoException {
return executeSelectAsStream(rowMapper, conn, false, fetchSize, sql, bindValues);
}
/**
* Execute a SELECT statement and return result as a {@link Stream}.
*
* @param rowMapper
* @param conn
* @param autoCloseConnection if {@code true} the supplied {@link Connection} will be automatically closed when
* the returned {@link Stream} closes.
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.5.1
*/
<T> Stream<T> executeSelectAsStream(IRowMapper<T> rowMapper, Connection conn, boolean autoCloseConnection,
int fetchSize, String sql, Map<String, ?> bindValues) throws DaoException;
/*----------------------------------------------------------------------*/
/**
* Execute a SELECT statement.
*
* @param sql
* @param bindValues index-based bind values
* @return
* @throws DaoException
*/
default List<Map<String, Object>> executeSelect(String sql, Object... bindValues) throws DaoException {
return executeSelect(UniversalRowMapper.INSTANCE, sql, bindValues);
}
/**
* Execute a SELECT statement.
*
* @param sql
* @param bindValues name-based bind value
* @return
* @throws DaoException
* @since 0.8.0
*/
default List<Map<String, Object>> executeSelect(String sql, Map<String, ?> bindValues) throws DaoException {
return executeSelect(UniversalRowMapper.INSTANCE, sql, bindValues);
}
/**
* Execute a SELECT statement.
*
* @param conn
* @param sql
* @param bindValues index-based bind values
* @return
* @throws DaoException
*/
default List<Map<String, Object>> executeSelect(Connection conn, String sql, Object... bindValues)
throws DaoException {
return executeSelect(UniversalRowMapper.INSTANCE, conn, sql, bindValues);
}
/**
* Execute a SELECT statement.
*
* @param conn
* @param sql
* @param bindValues name-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
default List<Map<String, Object>> executeSelect(Connection conn, String sql, Map<String, ?> bindValues)
throws DaoException {
return executeSelect(UniversalRowMapper.INSTANCE, conn, sql, bindValues);
}
/*----------------------------------------------------------------------*/
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default Stream<Map<String, Object>> executeSelectAsStream(String sql, Object... bindValues) throws DaoException {
return executeSelectAsStream(UniversalRowMapper.INSTANCE, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default Stream<Map<String, Object>> executeSelectAsStream(int fetchSize, String sql, Object... bindValues)
throws DaoException {
return executeSelectAsStream(UniversalRowMapper.INSTANCE, fetchSize, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param conn
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default Stream<Map<String, Object>> executeSelectAsStream(Connection conn, String sql, Object... bindValues)
throws DaoException {
return executeSelectAsStream(conn, false, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param conn
* @param autoCloseConnection if {@code true} the supplied {@link Connection} will be automatically closed when
* the returned {@link Stream} closes.
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.5.1
*/
default Stream<Map<String, Object>> executeSelectAsStream(Connection conn, boolean autoCloseConnection, String sql,
Object... bindValues) throws DaoException {
return executeSelectAsStream(UniversalRowMapper.INSTANCE, conn, autoCloseConnection, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param conn
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default Stream<Map<String, Object>> executeSelectAsStream(Connection conn, int fetchSize, String sql,
Object... bindValues) throws DaoException {
return executeSelectAsStream(conn, false, fetchSize, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param conn
* @param autoCloseConnection if {@code true} the supplied {@link Connection} will be automatically closed when
* the returned {@link Stream} closes.
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.5.1
*/
default Stream<Map<String, Object>> executeSelectAsStream(Connection conn, boolean autoCloseConnection,
int fetchSize, String sql, Object... bindValues) throws DaoException {
return executeSelectAsStream(UniversalRowMapper.INSTANCE, conn, autoCloseConnection, fetchSize, sql,
bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default Stream<Map<String, Object>> executeSelectAsStream(String sql, Map<String, ?> bindValues)
throws DaoException {
return executeSelectAsStream(UniversalRowMapper.INSTANCE, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default Stream<Map<String, Object>> executeSelectAsStream(int fetchSize, String sql, Map<String, ?> bindValues)
throws DaoException {
return executeSelectAsStream(UniversalRowMapper.INSTANCE, fetchSize, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param conn
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default Stream<Map<String, Object>> executeSelectAsStream(Connection conn, String sql, Map<String, ?> bindValues)
throws DaoException {
return executeSelectAsStream(conn, false, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param conn
* @param autoCloseConnection if {@code true} the supplied {@link Connection} will be automatically closed when
* the returned {@link Stream} closes.
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.5.1
*/
default Stream<Map<String, Object>> executeSelectAsStream(Connection conn, boolean autoCloseConnection, String sql,
Map<String, ?> bindValues) throws DaoException {
return executeSelectAsStream(UniversalRowMapper.INSTANCE, conn, autoCloseConnection, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param conn
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.3
*/
default Stream<Map<String, Object>> executeSelectAsStream(Connection conn, int fetchSize, String sql,
Map<String, ?> bindValues) throws DaoException {
return executeSelectAsStream(conn, false, fetchSize, sql, bindValues);
}
/**
* Execute a SELECT statement and return the result as a {@link Stream}.
*
* @param conn
* @param autoCloseConnection if {@code true} the supplied {@link Connection} will be automatically closed when
* the returned {@link Stream} closes.
* @param fetchSize
* @param sql
* @param bindValues
* @return
* @throws DaoException
* @since 0.8.5.1
*/
default Stream<Map<String, Object>> executeSelectAsStream(Connection conn, boolean autoCloseConnection,
int fetchSize, String sql, Map<String, ?> bindValues) throws DaoException {
return executeSelectAsStream(UniversalRowMapper.INSTANCE, conn, autoCloseConnection, fetchSize, sql,
bindValues);
}
/*----------------------------------------------------------------------*/
/**
* Execute a SELECT statement and fetch one row.
*
* @param rowMapper to map the {@link ResultSet} to object
* @param sql
* @param bindValues index-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
<T> T executeSelectOne(IRowMapper<T> rowMapper, String sql, Object... bindValues) throws DaoException;
/**
* Execute a SELECT statement and fetch one row.
*
* @param rowMapper to map the {@link ResultSet} to object
* @param sql
* @param bindValues name-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
<T> T executeSelectOne(IRowMapper<T> rowMapper, String sql, Map<String, ?> bindValues) throws DaoException;
/**
* Execute a SELECT statement and fetch one row.
*
* @param rowMapper to map the {@link ResultSet} to object
* @param conn
* @param sql
* @param bindValues index-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
default <T> T executeSelectOne(IRowMapper<T> rowMapper, Connection conn, String sql, Object... bindValues)
throws DaoException {
try (Stream<T> stream = executeSelectAsStream(rowMapper, conn, 1, sql, bindValues)) {
return stream.findFirst().orElse(null);
}
}
/**
* Execute a SELECT statement and fetch one row.
*
* @param rowMapper to map the {@link ResultSet} to object
* @param conn
* @param sql
* @param bindValues name-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
default <T> T executeSelectOne(IRowMapper<T> rowMapper, Connection conn, String sql, Map<String, ?> bindValues)
throws DaoException {
try (Stream<T> stream = executeSelectAsStream(rowMapper, conn, 1, sql, bindValues)) {
return stream.findFirst().orElse(null);
}
}
/**
* Execute a SELECT statement and fetch one row.
*
* @param sql
* @param bindValues index-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
default Map<String, Object> executeSelectOne(String sql, Object... bindValues) throws DaoException {
return executeSelectOne(UniversalRowMapper.INSTANCE, sql, bindValues);
}
/**
* Execute a SELECT statement and fetch one row.
*
* @param sql
* @param bindValues name-based bind value
* @return
* @throws DaoException
* @since 0.8.0
*/
default Map<String, Object> executeSelectOne(String sql, Map<String, ?> bindValues) throws DaoException {
return executeSelectOne(UniversalRowMapper.INSTANCE, sql, bindValues);
}
/**
* Execute a SELECT statement and fetch one row.
*
* @param conn
* @param sql
* @param bindValues index-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
default Map<String, Object> executeSelectOne(Connection conn, String sql, Object... bindValues)
throws DaoException {
return executeSelectOne(UniversalRowMapper.INSTANCE, conn, sql, bindValues);
}
/**
* Execute a SELECT statement and fetch one row.
*
* @param conn
* @param sql
* @param bindValues name-based bind values
* @return
* @throws DaoException
* @since 0.8.0
*/
default Map<String, Object> executeSelectOne(Connection conn, String sql, Map<String, ?> bindValues)
throws DaoException {
return executeSelectOne(UniversalRowMapper.INSTANCE, conn, sql, bindValues);
}
}
| 31.89359 | 119 | 0.612493 |
ceb2e1b67aff76e784852ebb297704c0b7feb2fc | 7,516 | package vip.gadfly.tiktok.core.util;
import org.apache.commons.lang3.StringUtils;
import vip.gadfly.tiktok.core.exception.TikTokException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
/**
* 字符串处理工具类
*
* @author OF
*/
public class StringUtil extends StringUtils {
public static final int LITERAL = 0x10;
/**
* 默认编码级别
*/
public static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
/**
* 获取报文头头长度
*
* @param msg 报文信息
* @param len 报文头长度
* @param encoding 编码集
* @return
* @throws TikTokException
*/
public static String getMsgHead(String msg, int len, String encoding)
throws TikTokException {
if (isBlank(encoding)) {
throw new TikTokException("msg is blank!");
}
if (len <= 0) {
throw new TikTokException("len is must be bigger than 0 !");
}
try {
String head = String.format("%0" + len + "d",
msg.getBytes(encoding).length);
return head + msg;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return msg;
}
/**
* 字符串中字符替换
*
* @param source
* @param oldStr
* @param newStr
* @return
*/
public static String replace(String source, String oldStr, String newStr) {
return Pattern.compile(oldStr, Pattern.LITERAL).matcher(source)
.replaceAll(quoteReplacement(newStr));
}
/**
* 去除字符串前四个字符
*
* @param msg
* @return
*/
public static String remove4First(String msg) {
String message = "";
if (msg == null || msg.equals("")) {
message = null;
} else {
message = msg.substring(4);
}
return message;
}
/**
* 判断数组strs中是否有str这个值
*
* @param strs
* @param str
* @return 有true 没有false
*/
public static boolean hasInArray(String[] strs, String str) {
for (String tmp : strs) {
if (tmp.equals(str)) {
return true;
}
}
return false;
}
/**
* 逐个判断字符变量是否为null或""
*
* @param names
* @return 有一个为空true 都不为空 false
*/
public static boolean isEmpty(String names) {
return names == null || "".equals(names.trim());
}
public static boolean isEmpty(Object name) {
if (name == null) {
return true;
}
if (name instanceof String) {
if ("".equals(name.toString().trim())) {
return true;
}
}
if (name instanceof Double) {
return (Double) name == 0.0;
}
return false;
}
/**
* @param time
* @return
*/
public static int getTime(String time) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
String str = sdf.format(date);
String times = time.substring(0, 2);
String timef = time.substring(2, 4);
String nowtimes = str.substring(0, 2);
String nowtimef = str.substring(2, 4);
int newtime;
if (Integer.parseInt(times) > Integer.parseInt(nowtimes)) {
newtime = (Integer.parseInt(times) - Integer.parseInt(nowtimes)) * 60;
newtime = newtime + Integer.parseInt(timef)
- Integer.parseInt(nowtimef);
} else if (Integer.parseInt(times) == Integer.parseInt(nowtimes)) {
if (Integer.parseInt(timef) >= Integer.parseInt(nowtimef)) {
newtime = Integer.parseInt(timef) - Integer.parseInt(nowtimef);
} else {
newtime = 24 * 60 - Integer.parseInt(nowtimef)
+ Integer.parseInt(timef);
}
} else {
newtime = (24 - Integer.parseInt(nowtimes) + Integer
.parseInt(times)) * 60;
newtime = newtime + Integer.parseInt(timef)
- Integer.parseInt(nowtimef);
}
return newtime;
}
public static String quoteReplacement(String s) {
if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) {
return s;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\') {
sb.append('\\');
sb.append('\\');
} else if (c == '$') {
sb.append('\\');
sb.append('$');
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* @param sour
* @param fillStr
* @param len
* @return
*/
public static String lpad(String sour, String fillStr, int len) {
StringBuilder blank = new StringBuilder();
for (int index = sour.length(); index < len; ++index) {
blank.append(fillStr);
}
return blank.append(sour).toString();
}
/**
* 以字节为单位进行截取
*/
public static String subbyte(String str, int beginIndex, int endIndex,
String encoding) throws UnsupportedEncodingException {
byte[] bts = str.getBytes(encoding);
int len = endIndex - beginIndex;
return new String(bts, beginIndex, len, encoding);
}
/**
* 以字节为单位进行截取
*/
public static String subbyte(String str, int beginIndex, int endIndex)
throws UnsupportedEncodingException {
byte[] bts = str.getBytes(DEFAULT_ENCODING);
int len = endIndex - beginIndex;
return new String(bts, beginIndex, len, DEFAULT_ENCODING);
}
/**
* @param str
* @param beginIndex
* @param len
* @return
* @throws UnsupportedEncodingException
*/
public static String subbyteByLen(String str, int beginIndex, int len)
throws UnsupportedEncodingException {
byte[] bts = str.getBytes(DEFAULT_ENCODING);
return new String(bts, beginIndex, len, DEFAULT_ENCODING);
}
/**
* HTML字符转义
*
* @return String 过滤后的字符串
* <p>对输入参数中的敏感字符进行过滤替换,防止用户利用JavaScript等方式输入恶意代码</p>
* <p>{@code String input = <img src='http://t1.baidu.com/it/fm=0&gp=0.jpg'/>}</p>
* <p>{@code HtmlUtils.htmlEscape(input); //from spring.jar}</p>
* <p>{@code StringEscapeUtils.escapeHtml(input); //from commons-lang.jar}</p>
* <p>尽管Spring和Apache都提供了字符转义的方法,但Apache的StringEscapeUtils功能要更强大一些</p>
* <p>StringEscapeUtils提供了对HTML,Java,JavaScript,SQL,XML等字符的转义和反转义</p>
* <p>但二者在转义HTML字符时,都不会对单引号和空格进行转义,而本方法则提供了对它们的转义</p>
*/
public static String htmlEscape(String input) {
if (isEmpty(input)) {
return input;
}
input = input.replaceAll("&", "&");
input = input.replaceAll("<", "<");
input = input.replaceAll(">", ">");
input = input.replaceAll(" ", " ");
input = input.replaceAll("'", "'"); // IE暂不支持单引号的实体名称,而支持单引号的实体编号,故单引号转义成实体编号,其它字符转义成实体名称
input = input.replaceAll("\"", """); // 双引号也需要转义,所以加一个斜线对其进行转义
input = input.replaceAll("\n", "<br/>"); // 不能把\n的过滤放在前面,因为还要对<和>过滤,这样就会导致<br/>失效了
return input;
}
}
| 28.907692 | 101 | 0.544572 |
6343b536afa8b2c62ea9129f43ba5dc2f4e63317 | 10,190 | package Vista;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import BD.Bd;
import javax.swing.JLabel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
public class Gestion_Global_Estadisticas extends JFrame {
private JPanel contentPane;
private JTextField tCodPiezaMax;
private JTextField tCodPiezaMaxProy;
private JTextField tNumPiezaMax;
private JTextField tNumPiezaMaxProy;
private JTextField tproveedorPiezasNombre;
private JTextField tproveedorPiezasNumero;
private JTextField tproyectoNombre;
private JTextField tproyectoNumero;
private JTextField tcodigoProveedor;
private JTextField tnombrepieza;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gestion_Global_Estadisticas frame = new Gestion_Global_Estadisticas();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* @throws ClassNotFoundException
*/
public Gestion_Global_Estadisticas() throws ClassNotFoundException {
setTitle("Gestion estadisticas");
setBounds(100, 100, 698, 342);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JLabel lblNewLabel = new JLabel("RESUMENES ESTADISTICOS - PIEZAS PROYECTOS Y PROVEEDORES");
lblNewLabel.setFont(new Font("Segoe UI", Font.BOLD, 20));
JButton btnPcpsp1 = new JButton("N\u00BA DE PIEZAS Y CANTIDAD DE PIEZAS SUMINISTRADAS EN PROYECTOS");
btnPcpsp1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Gestion_Global_Estadisticas_Proyectos ggep=new Gestion_Global_Estadisticas_Proyectos();
ggep.setVisible(true);
} catch (ClassNotFoundException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
JButton btnPcpsp2 = new JButton("N\u00BA PIEZAS Y CANTIDAD DE PIEZAS SUMINISTRADAS POR PROVEEDOR");
btnPcpsp2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Gestion_Global_Estadisticas_Proveedor ggepo=new Gestion_Global_Estadisticas_Proveedor();
ggepo.setVisible(true);
} catch (ClassNotFoundException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
JLabel lblNewLabel_1 = new JLabel("Pieza de la que se ha suministrado mas cantidad");
tCodPiezaMax = new JTextField();
tCodPiezaMax.setColumns(10);
JLabel lblNewLabel_2 = new JLabel("Pieza que se ha suministrado a mas proyectos:");
tCodPiezaMaxProy = new JTextField();
tCodPiezaMaxProy.setColumns(10);
tNumPiezaMax = new JTextField();
tNumPiezaMax.setColumns(10);
tNumPiezaMaxProy = new JTextField();
tNumPiezaMaxProy.setColumns(10);
JLabel lblP = new JLabel("Proveedor que ha suministrado mas cantidad de piezas");
tproveedorPiezasNombre = new JTextField();
tproveedorPiezasNombre.setColumns(10);
tproveedorPiezasNumero = new JTextField();
tproveedorPiezasNumero.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("Proveedor que ha suministrado a mas proyectos/n poryectos");
tproyectoNombre = new JTextField();
tproyectoNombre.setColumns(10);
tproyectoNumero = new JTextField();
tproyectoNumero.setColumns(10);
JLabel lblNewLabel_4 = new JLabel("Proveedor que ha suministrado mas piezas / n\u00BA piezas");
tcodigoProveedor = new JTextField();
tcodigoProveedor.setColumns(10);
tnombrepieza = new JTextField();
tnombrepieza.setColumns(10);
Bd.estadistica_max_piezas(tCodPiezaMax,tNumPiezaMax);
Bd.estadistica_max_pieza_proyectos(tCodPiezaMaxProy,tNumPiezaMaxProy);
Bd.estadistica_num_pieza_proveedor(tproveedorPiezasNombre,tproveedorPiezasNumero);
Bd.estadistica_num_pieza_proyectos(tproyectoNombre,tproyectoNumero);
Bd.estadistica_num_provveedor_suministro_piezas(tcodigoProveedor,tnombrepieza);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(85)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(btnPcpsp1)
.addComponent(btnPcpsp2)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(lblNewLabel_1)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(tCodPiezaMax, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(tNumPiezaMax, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(lblNewLabel_2)
.addGap(18)
.addComponent(tCodPiezaMaxProy, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(tNumPiezaMaxProy, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING, false)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(lblNewLabel_4)
.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tcodigoProveedor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(lblP)
.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tproveedorPiezasNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
.addComponent(lblNewLabel_3)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(tproyectoNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(tproyectoNumero, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(tproveedorPiezasNumero, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(tnombrepieza, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))))
.addContainerGap())
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(lblNewLabel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(55))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(lblNewLabel)
.addGap(31)
.addComponent(btnPcpsp1)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_1)
.addComponent(tCodPiezaMax, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(tNumPiezaMax, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_2)
.addComponent(tNumPiezaMaxProy, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(tCodPiezaMaxProy, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(13)
.addComponent(btnPcpsp2)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblP)
.addComponent(tproveedorPiezasNumero, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(tproveedorPiezasNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_3)
.addComponent(tproyectoNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(tproyectoNumero, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(lblNewLabel_4)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(tnombrepieza, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(tcodigoProveedor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(26, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
}
| 43.733906 | 131 | 0.776742 |
b77ca1530791fe9a44cfb7339e1c0a0f4d1f048b | 852 | package alobha.chatapp.model;
public class MapModel {
private String latitude;
private String longitude;
private String place_name;
public MapModel() {
}
public MapModel(String latitude, String longitude, String place_name) {
this.latitude = latitude;
this.longitude = longitude;
this.place_name=place_name;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getPlace_name() {
return place_name;
}
public void setPlace_name(String place_name) {
this.place_name = place_name;
}
}
| 18.521739 | 75 | 0.637324 |
1ac9a992d7f0d4a6f3f0d37c8d69b7976cf97d06 | 821 | package org.opendolphin.demo.data;
public class Address {
private String first;
private String last;
private String city;
private String phone;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return String.format("%s %s, %s: %s", first, last, city, phone);
}
}
| 17.468085 | 72 | 0.571255 |
870fafac2ed5e8b8db33c9340d2ac9dcc3adbbdc | 955 | package houzm.game.springboot.common;
/**
* Package: houzm.game.springboot.common
* Author: hzm_dream@163.com
* Date: Created in 2018/11/14 18:11
* Copyright: Copyright (c) 2018
* Version: 0.0.1
* Modified By:
* Description: ResultGenerater
*/
public class ResultGenerater {
public static Result success(Object data) {
return new Result()
.setCode(ResultCode.SUCCESS.getCode())
.setSuccess(true)
.setMessage("SUCCESS")
.setData(data);
}
public static Result success() {
return new Result()
.setCode(ResultCode.SUCCESS.getCode())
.setSuccess(true)
.setMessage("SUCCESS");
}
public static Result fail(String message) {
return new Result()
.setCode(ResultCode.INTERNAL_SERVER_ERROR.getCode())
.setSuccess(false)
.setMessage(message);
}
}
| 26.527778 | 68 | 0.583246 |
5bd075970dff8aa5d3bb67024eb1e0bf5a64c087 | 1,470 | /*
* Copyright 2020 赖柄沣 bingfengdev@aliyun.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package pers.lbf.yeju.provider.encryption.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* TODO
*
* @author 赖柄沣 bingfengdev@aliyun.com
* @version 1.0
* @date 2021/4/29 21:20
*/
@Component
@RefreshScope
@ConfigurationProperties(prefix = "yeju.encryption.aes")
public class EncryptionAesConfig {
private Integer keyTimeout;
private String keyPrefix;
public Integer getKeyTimeout() {
return keyTimeout;
}
public void setKeyTimeout(Integer keyTimeout) {
this.keyTimeout = keyTimeout;
}
public String getKeyPrefix() {
return keyPrefix;
}
public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix;
}
}
| 26.727273 | 75 | 0.729932 |
633d8ecbe042044cd1da75d8d83dc49a119af271 | 1,466 | /**
* PerfRepo
* <p>
* Copyright (C) 2015 the original author or authors.
* <p>
* 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
* <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 org.perfrepo.web.dao;
import org.perfrepo.model.Alert;
import org.perfrepo.model.Metric;
import org.perfrepo.model.Test;
import javax.inject.Named;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* DAO for {@link org.perfrepo.model.Alert}
*
* @author Jiri Holusa (jholusa@redhat.com)
*/
@Named
public class AlertDAO extends DAO<Alert, Long> {
/**
* Retrieves all alerts associated with specified test and metric.
*
* @param test
* @param metric
* @return
*/
public List<Alert> getByTestAndMetric(Test test, Metric metric) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("testId", test.getId());
params.put("metricId", metric.getId());
return findByNamedQuery(Alert.GET_BY_TEST_AND_METRIC, params);
}
}
| 29.918367 | 118 | 0.709413 |
d8ea47f4afe576f066e722eda493265635292d1b | 811 | package arraylist01;
import java.util.ArrayList;
public class ArrayList02 {
public static void main(String[] args) {
ArrayList<String> lista = new ArrayList<String>();
lista.add("Shape Santa cruz");
lista.add("Shape flip");
lista.add("Roda Speedfire");
lista.add("Truck Strong");
String x = lista.get(1);
//System.out.println(x);
//Descobrir posição do elemento
Integer y = lista.indexOf("Roda Speedfire");
//System.out.println(y);
//Sobrepor uma informação dentro do vetor
lista.set(1, "Parafusos diamond");
String j = lista.get(1);
//System.out.println(j);
lista.remove("Truck Strong");
for (String k : lista) {
System.out.println(k);
}
}
}
| 21.918919 | 58 | 0.573366 |
ebe1fbd53561b2711abb3102df6dc493860a6c61 | 1,280 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.databox.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/** Defines values for KekType. */
public enum KekType {
/** Enum value MicrosoftManaged. */
MICROSOFT_MANAGED("MicrosoftManaged"),
/** Enum value CustomerManaged. */
CUSTOMER_MANAGED("CustomerManaged");
/** The actual serialized value for a KekType instance. */
private final String value;
KekType(String value) {
this.value = value;
}
/**
* Parses a serialized value to a KekType instance.
*
* @param value the serialized value to parse.
* @return the parsed KekType object, or null if unable to parse.
*/
@JsonCreator
public static KekType fromString(String value) {
KekType[] items = KekType.values();
for (KekType item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
}
return null;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
}
| 26.666667 | 69 | 0.647656 |
c37d4269f8f2e508ca7624f033f79383576c3147 | 2,371 | package blackjack;
/** TwentyOne.java - A program that allows the user to play the card game 21
* against the computer "dealer".
*
* Written 3/2006 by Wayne Pollock, Tampa Florida USA.
*/
import java.util.*;
import javax.swing.JOptionPane;
class BlackJack{
private static final String title = "BlackJack";
private static int STAND_PAT_POINT = 17;
private static final Shoe shoe = new Shoe();
public static void main ( String [] args ){
int rc = 0; // The return code from the showConfirmDialog
do{
playGame();
rc = JOptionPane.showConfirmDialog( null, "Play Again?",
title, JOptionPane.YES_NO_OPTION );
} while ( rc == JOptionPane.YES_OPTION );
}
private static void playGame (){
int rc = 0; // The return code from the showConfirmDialog
Hand dealersHand = new Hand( shoe ),
playersHand = new Hand( shoe );
StringBuilder initMsg = new StringBuilder( "Dealer shows : " );
initMsg.append( dealersHand.firstCard() );
initMsg.append( "\n\nPlayer's Hand: " );
while ( playersHand.value() < 21 )
{
StringBuilder msg = new StringBuilder( initMsg );
msg.append( playersHand.toString() );
msg.append( "\n\nDo you want another card?" );
rc = JOptionPane.showConfirmDialog( null, msg, title,
JOptionPane.YES_NO_CANCEL_OPTION );
if ( rc != JOptionPane.YES_OPTION )
break;
playersHand.hit();
}
if ( rc == JOptionPane.CANCEL_OPTION )
return;
// Determine who won, and display appropriate message:
String msg = null;
if ( playersHand.value() > 21 )
{
msg = "Sorry, you lost!\n\n";
} else
{
while ( dealersHand.value() < STAND_PAT_POINT )
dealersHand.hit();
if ( dealersHand.value() > 21 ||
playersHand.value() > dealersHand.value() )
msg = "Congratulations, you won!\n\n";
else
msg = "Sorry, you lost!\n\n";
}
msg += "Dealers Hand: " + dealersHand.toString() + "\n\n" +
"Players Hand: " + playersHand.toString();
JOptionPane.showMessageDialog( null, msg, title,
JOptionPane.PLAIN_MESSAGE );
}
} | 30.012658 | 77 | 0.568958 |
e14e9ac0bca2ef017e653223246ac82b8e6fdd0e | 1,160 | package mont.gonzalo.phiuba.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Gonzalo Montiel on 1/22/17.
*/
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String USER_TABLE_CREATE =
"CREATE TABLE user " +
"id INTEGER, " +
"name TEXT, " +
"lastName TEXT " +
"planCode TEXT";
private static final String USER_COURSE_TABLE_CREATE =
"CREATE TABLE userCourse " +
"userId INTEGERm, " +
"courseCode TEXT, " +
"status INTEGER";
public DatabaseOpenHelper(Context context) {
super(context, "data", null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_TABLE_CREATE + " " + USER_COURSE_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
| 29 | 79 | 0.607759 |
4fdd1f40696f3a68a9f02d51315292be40ac90fd | 13,260 | /*
* Copyright 2019 Patrik Karlström.
*
* 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 se.trixon.jota.client.ui_swing;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import se.trixon.almond.util.AlmondOptions;
import se.trixon.almond.util.AlmondUI;
import se.trixon.almond.util.Dict;
import se.trixon.almond.util.SystemHelper;
import se.trixon.almond.util.icons.material.MaterialIcon;
import se.trixon.jota.client.ConnectionListener;
import se.trixon.jota.client.Manager;
import se.trixon.jota.shared.ProcessEvent;
import se.trixon.jota.shared.ServerEvent;
import se.trixon.jota.shared.ServerEventListener;
import se.trixon.jota.shared.job.Job;
import se.trixon.jota.shared.task.Task;
/**
*
* @author Patrik Karlström
*/
public class TabHolder extends JTabbedPane implements ConnectionListener, ServerEventListener {
private Action mCloseAction;
private SpeedDialPanel mSpeedDialPanel;
private HashMap<Long, TabItem> mJobMap = new HashMap<>();
private final Manager mManager = Manager.getInstance();
private MouseAdapter mMenuMouseAdapter;
private Action mSaveAction;
private final AlmondOptions mAlmondOptions = AlmondOptions.getInstance();
private final ActionManager mActionManager = ActionManager.getInstance();
/**
* Creates new form ProgressPane
*/
public TabHolder() {
initComponents();
init();
}
public SpeedDialPanel getSpeedDialPanel() {
return mSpeedDialPanel;
}
@Override
public void onConnectionConnect() {
// nvm
}
@Override
public void onConnectionDisconnect() {
setSelectedComponent(mSpeedDialPanel);
mJobMap.entrySet().stream().forEach((entry) -> {
remove(entry.getValue());
});
mJobMap = new HashMap<>();
}
@Override
public void onProcessEvent(ProcessEvent processEvent, Job job, Task task, Object object) {
TabItem tabItem = getTabItem(job);
switch (processEvent) {
case STARTED:
tabItem.start();
setSelectedComponent(tabItem);
updateTitle(job, "b");
updateActionStates();
break;
case OUT:
case ERR:
tabItem.log(processEvent, (String) object);
break;
case CANCELED:
tabItem.log(ProcessEvent.OUT, String.format("\n\n%s", Dict.JOB_INTERRUPTED.toString()));
tabItem.enableSave();
updateTitle(job, "i");
updateActionStates();
break;
case FAILED:
tabItem.log(ProcessEvent.OUT, String.format("\n\n%s", Dict.JOB_FAILED.toString()));
tabItem.enableSave();
updateTitle(job, "strike");
updateActionStates();
break;
case FINISHED:
if (object != null) {
tabItem.log(ProcessEvent.OUT, (String) object);
}
tabItem.enableSave();
updateTitle(job, "normal");
updateActionStates();
break;
default:
break;
}
}
@Override
public void onServerEvent(ServerEvent serverEvent) {
}
private void displayTab(int index) {
try {
setSelectedIndex(index);
} catch (IndexOutOfBoundsException e) {
// nvm
}
}
private synchronized void updateTitle(Job job, String format) {
SwingUtilities.invokeLater(() -> {
int index = indexOfComponent(getTabItem(job));
try {
setTitleAt(index, String.format("<html><%s>%s</%s></html>", format, job.getName(), format));
} catch (Exception e) {
}
});
}
void closeTab() {
if (getSelectedComponent() instanceof TabItem) {
TabItem tabItem = (TabItem) getSelectedComponent();
if (tabItem.isClosable()) {
close(tabItem.getJob());
}
}
}
void saveTab() {
if (getSelectedComponent() instanceof TabItem) {
TabItem tabItem = (TabItem) getSelectedComponent();
if (tabItem.isClosable()) {
tabItem.save();
}
}
}
void initActions() {
InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getRootPane().getActionMap();
int commandMask = SystemHelper.getCommandMask();
mCloseAction = mActionManager.getAction(ActionManager.CLOSE_TAB);
mSaveAction = mActionManager.getAction(ActionManager.SAVE_TAB);
for (int i = 0; i < 10; i++) {
KeyStroke keyStroke = KeyStroke.getKeyStroke(0x31 + i, commandMask);
String key = "key_" + i;
final int tabIndex = i;
AbstractAction action = new AbstractAction("Tab") {
@Override
public void actionPerformed(ActionEvent e) {
displayTab(tabIndex);
}
};
inputMap.put(keyStroke, key);
actionMap.put(key, action);
}
AbstractAction action = new AbstractAction("TabNext") {
@Override
public void actionPerformed(ActionEvent e) {
displayTab(getSelectedIndex() + 1);
}
};
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, commandMask);
String key = "nextTab";
inputMap.put(keyStroke, key);
actionMap.put(key, action);
action = new AbstractAction("TabPrev") {
@Override
public void actionPerformed(ActionEvent e) {
displayTab(Math.max(getSelectedIndex() - 1, 0));
}
};
keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, commandMask + InputEvent.SHIFT_MASK);
key = "prevTab";
inputMap.put(keyStroke, key);
actionMap.put(key, action);
mActionManager.addAppListener(new ActionManager.AppAdapter() {
@Override
public void onCancel(ActionEvent actionEvent) {
if (getSelectedComponent() instanceof TabItem) {
TabItem tabItem = (TabItem) getSelectedComponent();
if (tabItem.isCancelable()) {
tabItem.cancel();
}
}
}
@Override
public void onMenu(ActionEvent actionEvent) {
mMenuMouseAdapter.mousePressed(null);
}
});
}
void close(Job job) {
TabItem panel = getTabItem(job);
mJobMap.remove(job.getId());
remove(panel);
setSelectedIndex(0);
}
private synchronized TabItem getTabItem(Job job) {
TabItem tabItem;
if (mJobMap.containsKey(job.getId())) {
tabItem = mJobMap.get(job.getId());
} else {
tabItem = new TabItem(job);
tabItem.getMenuButton().addMouseListener(mMenuMouseAdapter);
add(tabItem, job.getName());
TabCloser tabCloser = new TabCloser(this);
tabCloser.getButton().addActionListener((ActionEvent e) -> {
close(job);
});
tabCloser.postSetAction();
tabItem.setCloser(tabCloser);
setTabComponentAt(getTabCount() - 1, tabCloser);
mJobMap.put(job.getId(), tabItem);
setSelectedComponent(tabItem);
}
return tabItem;
}
private void init() {
setFocusTraversalKeysEnabled(false);
mSpeedDialPanel = new SpeedDialPanel();
add(mSpeedDialPanel, MaterialIcon._Action.HOME.getImageIcon(AlmondUI.ICON_SIZE_NORMAL));
setIconAt(0, MaterialIcon._Action.HOME.getImageIcon(AlmondUI.ICON_SIZE_NORMAL));
HistoryPanel historyPanel = new HistoryPanel();
add(historyPanel, MaterialIcon._Action.HISTORY.getImageIcon(AlmondUI.ICON_SIZE_NORMAL));
setIconAt(1, MaterialIcon._Action.HISTORY.getImageIcon(AlmondUI.ICON_SIZE_NORMAL));
mJobMap.values().stream().forEach((tabItem) -> {
tabItem.updateIcons();
});
mManager.addConnectionListeners(this);
mManager.getClient().addServerEventListener(this);
mMenuMouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e == null || e.getButton() == MouseEvent.BUTTON1) {
Component component = ((TabListener) getSelectedComponent()).getMenuButton();
JPopupMenu popupMenu = MainFrame.getPopupMenu();
InputMap inputMap = popupMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = popupMenu.getActionMap();
Action action = new AbstractAction("HideMenu") {
@Override
public void actionPerformed(ActionEvent e) {
popupMenu.setVisible(false);
}
};
String key = "HideMenu";
actionMap.put(key, action);
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
inputMap.put(keyStroke, key);
if (popupMenu.isVisible()) {
popupMenu.setVisible(false);
} else {
popupMenu.show(component, component.getWidth() - popupMenu.getWidth(), component.getHeight());
int x = component.getLocationOnScreen().x + component.getWidth() - popupMenu.getWidth();
int y = component.getLocationOnScreen().y + component.getHeight();
popupMenu.setLocation(x, y);
}
}
}
};
mSpeedDialPanel.getMenuButton().addMouseListener(mMenuMouseAdapter);
//FIXME Why is this necessary?
setTabLayoutPolicy(SCROLL_TAB_LAYOUT);
setTabLayoutPolicy(WRAP_TAB_LAYOUT);
}
private void updateActionStates() {
try {
mCloseAction.setEnabled(false);
mSaveAction.setEnabled(false);
if (getSelectedComponent() instanceof TabItem) {
TabItem tabItem = (TabItem) getSelectedComponent();
if (tabItem.isClosable()) {
mCloseAction.setEnabled(true);
mSaveAction.setEnabled(true);
}
}
} catch (NullPointerException e) {
}
}
/**
* 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() {
setBorder(javax.swing.BorderFactory.createEmptyBorder(8, 0, 0, 0));
setFont(getFont().deriveFont((getFont().getStyle() & ~java.awt.Font.ITALIC) & ~java.awt.Font.BOLD));
addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
formStateChanged(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 292, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void formStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_formStateChanged
updateActionStates();
}//GEN-LAST:event_formStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| 34.986807 | 183 | 0.599849 |
4b820935e51a2cb7d64b11259d0de4ec8ca46f89 | 786 | // https://www.interviewbit.com/problems/simplify-directory-path/
public class Solution {
public String simplifyPath(String A) {
if (A == null || A.length() == 0) {
return "/";
}
String[] s = A.split("[/]");
StringBuilder path = new StringBuilder();
int i = 0;
String[] stack = new String[s.length];
for (int j = 0; j < s.length; j++) {
if (s[j].equals(".") || s[j].equals("")) {
continue;
}
if (s[j].equals("..")) {
if (i > 0) {
i--;
}
}else{
stack[i++] = s[j];
}
}
for (int j = 0; j < i; j++){
path.append("/" + stack[j]);
}
return i == 0 ? "/" : path.toString();
}
}
| 23.818182 | 65 | 0.40458 |
ffbe11ca285c66e36f5469e81bccaae01acfd95b | 2,166 | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'caesarCipher' function below.
*
* The function is expected to return a STRING.
* The function accepts following parameters:
* 1. STRING s
* 2. INTEGER k
*/
public static String caesarCipher(String s, int k) {
// Write your code here
char[] arr = s.toCharArray();
for(int i=0; i< arr.length; i++){
boolean check = Character.isAlphabetic(arr[i]);
boolean isUpper = Character.isUpperCase(arr[i]);
if(check){
k = k % 26;
if(Character.isAlphabetic((char)((int)arr[i]) + k)){
if(isUpper && !Character.isUpperCase((char) (((int) arr[i]) + k))){
arr[i] = (char) (((int) arr[i]) + k - 26);
}else{
arr[i] = (char) (((int) arr[i]) + k);
}
}else{
arr[i] = (char) (((int) arr[i]) + k - 26);
}
}
}
String result = String.valueOf(arr);
return result;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
String s = bufferedReader.readLine();
int k = Integer.parseInt(bufferedReader.readLine().trim());
String result = Result.caesarCipher(s, k);
bufferedWriter.write(result);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
| 30.083333 | 105 | 0.550323 |
0fe30aeee32cc211b5f85cd342fc7f0676ce152e | 930 | package de.dercoder.football.core;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
final class FootballPlayerSessionTest {
private FootballPlayerSession playerSession;
@BeforeEach
void initialize() {
var player = FootballPlayer.withId(UUID.randomUUID());
playerSession = FootballPlayerSession.of(player,
0,
FootballPunishment.UNPUNISHED
);
}
@Test
void testPlayerPunishment() {
playerSession.punish(FootballPunishment.YELLOW_CARD);
assertEquals(FootballPunishment.YELLOW_CARD, playerSession.punishment());
playerSession.punish(FootballPunishment.YELLOW_CARD);
assertEquals(FootballPunishment.RED_CARD, playerSession.punishment());
}
@Test
void testPlayerGoalShooting() {
playerSession.shootAGoal();
assertEquals(1, playerSession.goals());
}
}
| 25.833333 | 77 | 0.76129 |
ac6e112715cb5ebaad4caded72e8ffce31f3e181 | 1,715 | package net.tazer.createliftoff.common.content.heat_exchanger;
import com.simibubi.create.foundation.data.SpecialBlockStateGen;
import com.simibubi.create.repack.registrate.providers.DataGenContext;
import com.simibubi.create.repack.registrate.providers.RegistrateBlockstateProvider;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.model.generators.ModelFile;
public class HeatExchangerBlockstateGen extends SpecialBlockStateGen {
public HeatExchangerBlockstateGen() {}
@Override
protected int getXRotation(BlockState state) {
Direction facing = state.getValue(HeatExchangerBlock.FACING);
return facing.getAxis()
.isVertical() ? facing == Direction.DOWN ? 180 : 0 : 90;
}
@Override
protected int getYRotation(BlockState state) {
Direction facing = state.getValue(HeatExchangerBlock.FACING);
return facing.getAxis()
.isVertical() ? 0 : horizontalAngle(facing) + 180;
}
@Override
public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov,
BlockState state) {
Direction facing = state.getValue(HeatExchangerBlock.FACING);
boolean axisAlongFirst = state.getValue(HeatExchangerBlock.AXIS_ALONG_FIRST_COORDINATE);
String path = "block/heat_exchanger";
String partial = facing.getAxis() == Direction.Axis.X ^ axisAlongFirst ? "block_rotated" : "block";
return prov.models()
.getExistingFile(prov.modLoc(path + "/" + partial));
}
} | 40.833333 | 112 | 0.71137 |
ad7eff49a165043beac41250b11a364d17e4a751 | 6,139 | package nablarch.common.idgenerator;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.sql.ResultSet;
import java.sql.SQLException;
import nablarch.common.idgenerator.SequenceIdGenerator.SequenceGeneratorFailedException;
import nablarch.core.db.DbAccessException;
import nablarch.core.db.connection.AppDbConnection;
import nablarch.core.db.connection.ConnectionFactory;
import nablarch.core.db.connection.DbConnectionContext;
import nablarch.core.db.connection.TransactionManagerConnection;
import nablarch.core.db.statement.ResultSetIterator;
import nablarch.core.db.statement.SqlPStatement;
import nablarch.test.support.SystemRepositoryResource;
import nablarch.test.support.db.helper.DatabaseTestRunner;
import nablarch.test.support.db.helper.TargetDb;
import nablarch.test.support.log.app.OnMemoryLogWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import mockit.Expectations;
import mockit.Mocked;
/**
* {@link SequenceIdGenerator}のテストクラス。
*
* @author hisaaki shioiri
*/
@RunWith(DatabaseTestRunner.class)
@TargetDb(exclude = TargetDb.Db.SQL_SERVER)
public class SequenceIdGeneratorTest {
/** テストで使用するコネクション名 */
private static final String CONNECTION_NAME = "connection name";
@ClassRule
public static SystemRepositoryResource repositoryResource = new SystemRepositoryResource("db-default.xml");
/** テスト対象 */
private SequenceIdGenerator sut = new SequenceIdGenerator();
@Before
public void setUp() throws Exception {
final ConnectionFactory factory = repositoryResource.getComponentByType(ConnectionFactory.class);
final TransactionManagerConnection connection = factory.getConnection(CONNECTION_NAME);
DbConnectionContext.setConnection(CONNECTION_NAME, connection);
sut.setDbTransactionName(CONNECTION_NAME);
createSequence(connection, "SEQ1", "SEQ2");
OnMemoryLogWriter.clear();
}
private void createSequence(TransactionManagerConnection connection, String... sequences) {
for (String sequence : sequences) {
final SqlPStatement drop = connection.prepareStatement("DROP SEQUENCE " + sequence);
try {
drop.execute();
} catch (Exception ignore) {
connection.rollback();
ignore.printStackTrace();
}
drop.close();
final SqlPStatement create = connection.prepareStatement("create SEQUENCE " + sequence);
create.execute();
create.close();
connection.commit();
}
}
@After
public void tearDown() throws Exception {
try {
final TransactionManagerConnection connection = DbConnectionContext.getTransactionManagerConnection(
CONNECTION_NAME);
connection.terminate();
} finally {
DbConnectionContext.removeConnection(CONNECTION_NAME);
}
}
/**
* シーケンスを用いた採番ができること。
*/
@Test
public void generateId() throws Exception {
final String first = sut.generateId("SEQ1");
final String second = sut.generateId("SEQ1");
assertThat("2回目の呼び出しで1回目から値がインクリメントされていること",
Integer.parseInt(second),
is(Integer.parseInt(first) + 1));
}
/**
* シーケンスを用いた採番が出来、フォーマットされた値が返却されること。
*/
@Test
public void generateId_withFormatter() throws Exception {
final IdFormatter formatter = new IdFormatter() {
@Override
public String format(String id, String no) {
return no + '_';
}
};
final String value = sut.generateId("SEQ1", formatter);
assertThat("最後の文字が「_」である", value.matches("\\d+_"), is(true));
final String first = sut.generateId("SEQ2", formatter);
final String second = sut.generateId("SEQ2", formatter);
assertThat("2回目の呼び出しで1回目から値がインクリメントされていること",
Integer.parseInt(second.substring(0, second.length() - 1)),
is(Integer.parseInt(first.substring(0, second.length() - 1)) + 1));
}
/**
* シーケンス採番のSQL実行でレコードが戻されない場合、
* {@link SequenceIdGenerator.SequenceGeneratorFailedException}が送出されること。
*/
@Test
public void generateId_recordNotFound(@Mocked DbConnectionContext mockContext) throws Exception {
// 採番処理中にSQLExceptionを送出するモックオブジェクトを設定する。
new Expectations() {{
final AppDbConnection connection = DbConnectionContext.getTransactionManagerConnection(anyString);
final SqlPStatement statement = connection.prepareStatement(anyString);
final ResultSetIterator rs = statement.executeQuery();
rs.next();
result = false;
}};
try {
sut.generateId("SEQ2");
fail("ここは通らない");
} catch (SequenceGeneratorFailedException e) {
assertThat(e.getMessage(), is("failed to get next value from sequence. sequence name=[SEQ2]"));
}
}
/**
* シーケンス採番時に使用する{@link ResultSet}のクローズ処理に失敗する場合、
* ワーニングログが出力されること。
*/
@Test
public void generatedId_ResultSetCloseError(@Mocked DbConnectionContext mockContext) throws Exception {
// 採番処理中にSQLExceptionを送出するモックオブジェクトを設定する。
new Expectations() {{
final AppDbConnection connection = DbConnectionContext.getTransactionManagerConnection(anyString);
final SqlPStatement statement = connection.prepareStatement(anyString);
final ResultSetIterator rs = statement.executeQuery();
rs.next();
result = true;
rs.getLong(anyInt);
result = 1L;
rs.close();
result = new DbAccessException("db close error", new SQLException("error"));
}};
final String id = sut.generateId("SEQ2");
assertThat(id, is("1"));
OnMemoryLogWriter.assertLogContains("writer.memory", "failed to ResultSetIterator#close");
}
}
| 35.281609 | 112 | 0.672259 |
c1b19bd4e5fec4c8b06744308da00c9bb605bddb | 4,172 | package net.cactusthorn.routing.delegate.uribuilder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.net.URI;
import java.util.HashMap;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriBuilderException;
import org.junit.jupiter.api.Test;
import net.cactusthorn.routing.delegate.UriBuilderImpl;
public class UriBuilderBuildTest {
@Test public void buildFromMapNull() {
UriBuilder builder = new UriBuilderImpl();
assertThrows(IllegalArgumentException.class, () -> builder.buildFromMap(null));
assertThrows(IllegalArgumentException.class, () -> builder.buildFromMap(null, true));
assertThrows(IllegalArgumentException.class, () -> builder.buildFromEncodedMap(null));
}
@Test public void buildEmpty() {
UriBuilder builder = new UriBuilderImpl();
builder.uri("http://a.com");
assertEquals("http://a.com", builder.build(new Object[0]).toString());
assertEquals("http://a.com", builder.build().toString());
assertEquals("http://a.com", builder.build(new Object[0], true).toString());
assertEquals("http://a.com", builder.buildFromEncoded(new Object[0]).toString());
}
@Test public void buildURIException() {
UriBuilder builder = new UriBuilderImpl();
builder.uri("htt p://a.com");
assertThrows(UriBuilderException.class, () -> builder.build((Object[]) null));
assertThrows(UriBuilderException.class, () -> builder.build(null, true));
assertThrows(UriBuilderException.class, () -> builder.buildFromEncoded((Object[]) null));
}
@Test public void buildMapURIException() {
UriBuilder builder = new UriBuilderImpl();
builder.uri("htt p://a.com");
assertThrows(UriBuilderException.class, () -> builder.buildFromMap(new HashMap<>()));
assertThrows(UriBuilderException.class, () -> builder.buildFromMap(new HashMap<>(), true));
assertThrows(UriBuilderException.class, () -> builder.buildFromEncodedMap(new HashMap<>()));
}
@Test public void build() {
UriBuilder builder = new UriBuilderImpl();
builder.uri("{schema}://{userinfo}@{host}:{port}/{path}?{p}={v}&{p}={port}#{f}");
URI uri = builder.build("http", "aa:bb", "a.com", 8080, "xyz", "var", "value", "fragment");
assertEquals("http://aa:bb@a.com:8080/xyz?var=value&var=8080#fragment", uri.toString());
uri = builder.build("https", "aa2:bb2", "a.com", 8080, "xyz", "var", "val%20ue", "fragment");
assertEquals("https://aa2:bb2@a.com:8080/xyz?var=val%2520ue&var=8080#fragment", uri.toString());
}
@Test public void buildSlash() {
UriBuilder builder = new UriBuilderImpl();
builder.uri("{schema}://{userinfo}@{host}:{port}/{path}?{p}={v}&{p}={port}#{f}");
Object[] vars = new Object[] { "http", "aa:bb", "a.com", 8080, "xyz/ABC", "var", "value", "fragment" };
URI uri = builder.build(vars, true);
assertEquals("http://aa:bb@a.com:8080/xyz%2FABC?var=value&var=8080#fragment", uri.toString());
}
@Test public void buildFromEncoded() {
UriBuilder builder = new UriBuilderImpl();
builder.uri("{schema}://{userinfo}@{host}:{port}/{path}?{p}={v}&{p}={port}#{f}");
URI uri = builder.buildFromEncoded("https", "aa@2:bb2", "a.com", 8080, "xyz", "var", "val%20ue", "fragment");
assertEquals("https://aa%402:bb2@a.com:8080/xyz?var=val%20ue&var=8080#fragment", uri.toString());
}
@Test public void buildNotEnoughValues() {
UriBuilder builder = new UriBuilderImpl();
builder.uri("{schema}://{userinfo}@{host}:{port}/{path}?{p}={v}&{p}={port}#{f}");
assertThrows(IllegalArgumentException.class, () -> builder.build("http", "aa:bb", "a.com", 8080, "xyz", "var", "value"));
}
@Test public void buildWithNullValue() {
UriBuilder builder = new UriBuilderImpl();
builder.uri("{schema}://{userinfo}@{host}:{port}/{path}?{p}={v}&{p}={port}#{f}");
assertThrows(IllegalArgumentException.class, () -> builder.build("http", null, "a.com"));
}
}
| 48.511628 | 129 | 0.642378 |
074406d2503cc098f658c19bdfc592b24ea7d7b3 | 36,365 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.domain.suites;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_CONTROL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONTENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DIRECTORY_GROUPING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXCEPTIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_MAJOR_VERSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_RESOURCES_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_TYPES_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNNING_SERVER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.URL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.PropertyPermission;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.operations.global.ReadResourceDescriptionHandler;
import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil;
import org.jboss.as.test.integration.domain.management.util.DomainTestSupport;
import org.jboss.as.test.integration.domain.management.util.DomainTestUtils;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.Property;
import org.jboss.msc.service.ServiceActivator;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test of various scenarios involving composite operations in a domain.
*
* @author Brian Stansberry (c) 2015 Red Hat Inc.
*/
public class CompositeOperationTestCase {
private static String DEPLOYMENT_NAME = "deployment.jar";
private static final PathElement DEPLOYMENT_PATH = PathElement.pathElement(DEPLOYMENT, DEPLOYMENT_NAME);
protected static final PathAddress SERVER_GROUP_MAIN_SERVER_GROUP = PathAddress.pathAddress(SERVER_GROUP, "main-server-group");
private static final PathElement HOST_MASTER = PathElement.pathElement(HOST, "master");
private static final PathElement HOST_SLAVE = PathElement.pathElement(HOST, "slave");
private static final PathElement SERVER_ONE = PathElement.pathElement(RUNNING_SERVER, "main-one");
private static final PathElement SERVER_TWO = PathElement.pathElement(RUNNING_SERVER, "main-two");
private static final PathElement SERVER_THREE = PathElement.pathElement(RUNNING_SERVER, "main-three");
private static final PathElement SERVER_FOUR = PathElement.pathElement(RUNNING_SERVER, "main-four");
private static final PathElement SYS_PROP_ELEMENT = PathElement.pathElement(SYSTEM_PROPERTY, "composite-op");
private static final PathElement HOST_SYS_PROP_ELEMENT = PathElement.pathElement(SYSTEM_PROPERTY, "composite-op-host");
private static DomainTestSupport testSupport;
private static DomainLifecycleUtil domainMasterLifecycleUtil;
private static DomainClient masterClient;
private int sysPropVal = 0;
private static File tmpDir;
private static File deployment;
@BeforeClass
public static void setupDomain() throws Exception {
testSupport = DomainTestSuite.createSupport(CompositeOperationTestCase.class.getSimpleName());
domainMasterLifecycleUtil = testSupport.getDomainMasterLifecycleUtil();
masterClient = domainMasterLifecycleUtil.getDomainClient();
}
@AfterClass
public static void tearDownDomain() throws Exception {
testSupport = null;
domainMasterLifecycleUtil = null;
DomainTestSuite.stopSupport();
}
@Before
public void setup() throws IOException {
sysPropVal = 0;
ModelNode op = Util.createAddOperation(PathAddress.pathAddress(SYS_PROP_ELEMENT));
op.get(VALUE).set(sysPropVal);
domainMasterLifecycleUtil.getDomainClient().execute(op);
op = Util.createAddOperation(PathAddress.pathAddress(HOST_MASTER, HOST_SYS_PROP_ELEMENT));
op.get(VALUE).set(sysPropVal);
domainMasterLifecycleUtil.getDomainClient().execute(op);
op = Util.createAddOperation(PathAddress.pathAddress(HOST_SLAVE, HOST_SYS_PROP_ELEMENT));
op.get(VALUE).set(sysPropVal);
domainMasterLifecycleUtil.getDomainClient().execute(op);
}
@After
public void tearDown() throws IOException {
try {
ModelNode op = Util.createRemoveOperation(PathAddress.pathAddress(SYS_PROP_ELEMENT));
domainMasterLifecycleUtil.getDomainClient().execute(op);
} finally {
try {
ModelNode op = Util.createRemoveOperation(PathAddress.pathAddress(HOST_MASTER, HOST_SYS_PROP_ELEMENT));
domainMasterLifecycleUtil.getDomainClient().execute(op);
} finally {
ModelNode op = Util.createRemoveOperation(PathAddress.pathAddress(HOST_SLAVE, HOST_SYS_PROP_ELEMENT));
domainMasterLifecycleUtil.getDomainClient().execute(op);
}
}
}
/**
* Test of a composite operation that reads from multiple processes.
*
* @throws IOException
* @throws MgmtOperationException
*/
@Test
public void testMultipleProcessReadOnlyComposite() throws IOException, MgmtOperationException {
final ModelNode composite = new ModelNode();
composite.get(OP).set(COMPOSITE);
final ModelNode steps = composite.get(STEPS);
final ModelNode address = new ModelNode();
address.setEmptyList();
// host=slave
address.add(HOST, "slave");
steps.add().set(createReadResourceOperation(address));
// host=slave,server=main-three
address.add(RUNNING_SERVER, "main-three");
steps.add().set(createReadResourceOperation(address));
// host=slave,server=main-three,subsystem=io
address.add(SUBSYSTEM, "io");
steps.add().set(createReadResourceOperation(address));
// add steps involving a different host
address.setEmptyList();
// host=master
address.add(HOST, "master");
steps.add().set(createReadResourceOperation(address));
// host=master,server=main-one
address.add(RUNNING_SERVER, "main-one");
steps.add().set(createReadResourceOperation(address));
// host=master,server=main-one,subsystem=io
address.add(SUBSYSTEM, "io");
steps.add().set(createReadResourceOperation(address));
// Now repeat the whole thing, but nested
final ModelNode nested = steps.add();
nested.get(OP).set(COMPOSITE);
final ModelNode nestedSteps = nested.get(STEPS);
address.setEmptyList();
// host=slave
address.add(HOST, "slave");
nestedSteps.add().set(createReadResourceOperation(address));
// host=slave,server=main-three
address.add(RUNNING_SERVER, "main-three");
nestedSteps.add().set(createReadResourceOperation(address));
// host=slave,server=main-three,subsystem=io
address.add(SUBSYSTEM, "io");
nestedSteps.add().set(createReadResourceOperation(address));
// add steps involving a different host
address.setEmptyList();
// host=master
address.add(HOST, "master");
nestedSteps.add().set(createReadResourceOperation(address));
// host=master,server=main-one
address.add(RUNNING_SERVER, "main-one");
nestedSteps.add().set(createReadResourceOperation(address));
// host=master,server=main-one,subsystem=io
address.add(SUBSYSTEM, "io");
nestedSteps.add().set(createReadResourceOperation(address));
final ModelNode response = domainMasterLifecycleUtil.getDomainClient().execute(composite);
assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
assertTrue(response.toString(), response.hasDefined(RESULT));
assertFalse(response.toString(), response.has(SERVER_GROUPS));
validateCompositeReadonlyResponse(response, true);
}
private void validateCompositeReadonlyResponse(ModelNode response, boolean allowNested) {
int i = 0;
for (Property property : response.get(RESULT).asPropertyList()) {
assertEquals(property.getName() + " from " + response, "step-" + (++i), property.getName());
ModelNode item = property.getValue();
assertEquals(property.getName() + " from " + response, ModelType.OBJECT, item.getType());
assertEquals(property.getName() + " from " + response, SUCCESS, item.get(OUTCOME).asString());
assertTrue(property.getName() + " from " + response, item.hasDefined(RESULT));
ModelNode itemResult = item.get(RESULT);
assertEquals(property.getName() + " result " + itemResult, ModelType.OBJECT, itemResult.getType());
switch (i) {
case 1:
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(MANAGEMENT_MAJOR_VERSION));
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(RUNNING_SERVER));
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(DIRECTORY_GROUPING));
assertEquals(property.getName() + " result " + itemResult, "slave", itemResult.get(NAME).asString());
break;
case 2:
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(MANAGEMENT_MAJOR_VERSION));
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(SUBSYSTEM));
assertEquals(property.getName() + " result " + itemResult, "main-three", itemResult.get(NAME).asString());
assertEquals(property.getName() + " result " + itemResult, "slave", itemResult.get(HOST).asString());
break;
case 3:
case 6:
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined("buffer-pool"));
break;
case 4:
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(MANAGEMENT_MAJOR_VERSION));
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(RUNNING_SERVER));
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(DIRECTORY_GROUPING));
assertEquals(property.getName() + " result " + itemResult, "master", itemResult.get(NAME).asString());
break;
case 5:
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(MANAGEMENT_MAJOR_VERSION));
assertTrue(property.getName() + " result " + itemResult, itemResult.hasDefined(SUBSYSTEM));
assertEquals(property.getName() + " result " + itemResult, "main-one", itemResult.get(NAME).asString());
assertEquals(property.getName() + " result " + itemResult, "master", itemResult.get(HOST).asString());
break;
case 7:
if (allowNested) {
// recurse
validateCompositeReadonlyResponse(item, false);
break;
} // else fall through
default:
throw new IllegalStateException();
}
}
}
/**
* Test of a composite operation that writes to and reads from multiple processes.
*/
@Test
public void testMultipleProcessReadWriteOperation() throws IOException {
final ModelNode composite = new ModelNode();
composite.get(OP).set(COMPOSITE);
final ModelNode steps = composite.get(STEPS);
// Modify the domain-wide prop
steps.add().set(Util.getWriteAttributeOperation(PathAddress.pathAddress(SYS_PROP_ELEMENT), VALUE, ++sysPropVal));
steps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_MASTER, SERVER_ONE, SYS_PROP_ELEMENT), VALUE));
steps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_SLAVE, SERVER_THREE, SYS_PROP_ELEMENT), VALUE));
// Modify the host=master prop
steps.add().set(Util.getWriteAttributeOperation(PathAddress.pathAddress(HOST_MASTER, HOST_SYS_PROP_ELEMENT), VALUE, ++sysPropVal));
steps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_MASTER, SERVER_ONE, HOST_SYS_PROP_ELEMENT), VALUE));
steps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_SLAVE, SERVER_THREE, HOST_SYS_PROP_ELEMENT), VALUE));
// Modify the host=slave prop
steps.add().set(Util.getWriteAttributeOperation(PathAddress.pathAddress(HOST_SLAVE, HOST_SYS_PROP_ELEMENT), VALUE, ++sysPropVal));
steps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_MASTER, SERVER_ONE, HOST_SYS_PROP_ELEMENT), VALUE));
steps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_SLAVE, SERVER_THREE, HOST_SYS_PROP_ELEMENT), VALUE));
// Now repeat the whole thing, but nested
final ModelNode nested = steps.add();
nested.get(OP).set(COMPOSITE);
final ModelNode nestedSteps = nested.get(STEPS);
// Domain wide
nestedSteps.add().set(Util.getWriteAttributeOperation(PathAddress.pathAddress(SYS_PROP_ELEMENT), VALUE, ++sysPropVal));
nestedSteps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_MASTER, SERVER_ONE, SYS_PROP_ELEMENT), VALUE));
nestedSteps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_SLAVE, SERVER_THREE, SYS_PROP_ELEMENT), VALUE));
// host=master
nestedSteps.add().set(Util.getWriteAttributeOperation(PathAddress.pathAddress(HOST_MASTER, HOST_SYS_PROP_ELEMENT), VALUE, ++sysPropVal));
nestedSteps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_MASTER, SERVER_ONE, HOST_SYS_PROP_ELEMENT), VALUE));
nestedSteps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_SLAVE, SERVER_THREE, HOST_SYS_PROP_ELEMENT), VALUE));
// host=slave
nestedSteps.add().set(Util.getWriteAttributeOperation(PathAddress.pathAddress(HOST_SLAVE, HOST_SYS_PROP_ELEMENT), VALUE, ++sysPropVal));
nestedSteps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_MASTER, SERVER_ONE, HOST_SYS_PROP_ELEMENT), VALUE));
nestedSteps.add().set(Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_SLAVE, SERVER_THREE, HOST_SYS_PROP_ELEMENT), VALUE));
final ModelNode response = domainMasterLifecycleUtil.getDomainClient().execute(composite);
assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
assertTrue(response.toString(), response.hasDefined(RESULT));
assertTrue(response.toString(), response.has(SERVER_GROUPS));
validateCompositeReadWriteResponse(response, true);
assertTrue(response.toString(), response.hasDefined(SERVER_GROUPS, "main-server-group", HOST, "master", "main-one", "response"));
ModelNode serverResp = response.get(SERVER_GROUPS, "main-server-group", HOST, "master", "main-one", "response");
validateBasicServerResponse(serverResp, null, 1, null, 2, 2, -1, null, 4, null, 5, 5);
assertTrue(response.toString(), response.hasDefined(SERVER_GROUPS, "main-server-group", HOST, "slave", "main-three", "response"));
serverResp = response.get(SERVER_GROUPS, "main-server-group", HOST, "slave", "main-three", "response");
validateBasicServerResponse(serverResp, null, 1, 0, null, 3, -1, null, 4, 3, null, 6);
assertTrue(response.toString(), response.hasDefined(SERVER_GROUPS, "other-server-group", HOST, "slave", "other-two", "response"));
serverResp = response.get(SERVER_GROUPS, "other-server-group", HOST, "slave", "other-two", "response");
validateBasicServerResponse(serverResp, null, null, -1, null, null);
}
private void validateCompositeReadWriteResponse(ModelNode response, boolean allowNested) {
int i = 0;
int baseValue = allowNested ? 0 : 3;
for (Property property : response.get(RESULT).asPropertyList()) {
assertEquals(property.getName() + " from " + response, "step-" + (++i), property.getName());
ModelNode item = property.getValue();
if (i != 4 && i != 7) {
assertEquals(property.getName() + " from " + response, ModelType.OBJECT, item.getType());
assertEquals(property.getName() + " from " + response, SUCCESS, item.get(OUTCOME).asString());
}
ModelNode itemResult = item.get(RESULT);
switch (i) {
case 1:
assertFalse(property.getName() + " result " + itemResult, itemResult.isDefined());
break;
case 2:
case 3:
assertEquals(property.getName() + " result " + itemResult, ModelType.STRING, itemResult.getType());
assertEquals(property.getName() + " result " + itemResult, baseValue + 1, itemResult.asInt());
break;
case 4:
//assertFalse(property.getName() + " result " + itemResult, itemResult.isDefined());
break;
case 5:
case 8:
assertEquals(property.getName() + " result " + itemResult, ModelType.STRING, itemResult.getType());
assertEquals(property.getName() + " result " + itemResult, baseValue + 2, itemResult.asInt());
break;
case 6:
assertEquals(property.getName() + " result " + itemResult, ModelType.STRING, itemResult.getType());
assertEquals(property.getName() + " result " + itemResult, baseValue, itemResult.asInt());
break;
case 7:
//assertFalse(property.getName() + " result " + itemResult, itemResult.isDefined());
break;
case 9:
assertEquals(property.getName() + " result " + itemResult, ModelType.STRING, itemResult.getType());
assertEquals(property.getName() + " result " + itemResult, baseValue + 3, itemResult.asInt());
break;
case 10:
if (allowNested) {
// recurse
validateCompositeReadWriteResponse(item, false);
break;
} // else fall through
default:
throw new IllegalStateException();
}
}
}
private static void validateBasicServerResponse(ModelNode serverResponse, Integer... values) {
assertEquals(serverResponse.toString(), ModelType.OBJECT, serverResponse.getType());
assertEquals(serverResponse.toString(), SUCCESS, serverResponse.get(OUTCOME).asString());
assertTrue(serverResponse.toString(), serverResponse.hasDefined(RESULT));
ModelNode serverResult = serverResponse.get(RESULT);
assertEquals(serverResponse.toString(), ModelType.OBJECT, serverResult.getType());
List<Property> list = serverResult.asPropertyList();
assertTrue(list.size() <= values.length);
for (int i = 0; i < list.size(); i++) {
ModelNode node = list.get(i).getValue();
assertTrue(serverResult.toString(), node.isDefined());
assertEquals(serverResult.toString(), ModelType.OBJECT, node.getType());
assertEquals(serverResult.toString(), SUCCESS, node.get(OUTCOME).asString());
Integer val = values[i];
if (val == null) {
assertFalse(serverResult.toString(), node.hasDefined(RESULT));
} else {
assertTrue(serverResult.toString() + " node " + i, node.hasDefined(RESULT));
int valInt = val.intValue();
if (valInt < 0) {
assertTrue(values.length > i + 1);
Integer[] sub = new Integer[values.length - i];
System.arraycopy(values, i + 1, sub, 0, values.length - i - 1);
validateBasicServerResponse(node, sub);
} else {
assertEquals(ModelType.STRING, node.get(RESULT).getType());
assertEquals(String.valueOf(valInt), node.get(RESULT).asString());
}
}
}
}
/** Test for https://issues.jboss.org/browse/WFCORE-998 */
@Test
public void testReadResourceDescriptionWithStoppedServer() throws IOException {
final ModelNode composite = new ModelNode();
composite.get(OP).set(COMPOSITE);
final ModelNode steps = composite.get(STEPS);
// First an operation that just has a single step calling r-r-d on the stopped server resource
ModelNode step = Util.createEmptyOperation(READ_RESOURCE_DESCRIPTION_OPERATION, PathAddress.pathAddress(HOST_SLAVE, SERVER_FOUR));
step.get(ACCESS_CONTROL).set(ReadResourceDescriptionHandler.AccessControl.COMBINED_DESCRIPTIONS.toString());
steps.add(step);
ModelNode response = domainMasterLifecycleUtil.getDomainClient().execute(composite);
validateRRDResponse(response, 1);
// Now include a step reading a stopped server on master
step = Util.createEmptyOperation(READ_RESOURCE_DESCRIPTION_OPERATION, PathAddress.pathAddress(HOST_MASTER, SERVER_TWO));
step.get(ACCESS_CONTROL).set(ReadResourceDescriptionHandler.AccessControl.COMBINED_DESCRIPTIONS.toString());
steps.add(step);
response = domainMasterLifecycleUtil.getDomainClient().execute(composite);
validateRRDResponse(response, 2);
// Now add steps for some running servers too
step = Util.createEmptyOperation(READ_RESOURCE_DESCRIPTION_OPERATION, PathAddress.pathAddress(HOST_MASTER, SERVER_ONE));
step.get(ACCESS_CONTROL).set(ReadResourceDescriptionHandler.AccessControl.COMBINED_DESCRIPTIONS.toString());
steps.add(step);
step = Util.createEmptyOperation(READ_RESOURCE_DESCRIPTION_OPERATION, PathAddress.pathAddress(HOST_SLAVE, SERVER_THREE));
step.get(ACCESS_CONTROL).set(ReadResourceDescriptionHandler.AccessControl.COMBINED_DESCRIPTIONS.toString());
steps.add(step);
response = domainMasterLifecycleUtil.getDomainClient().execute(composite);
validateRRDResponse(response, 4);
}
private static void validateRRDResponse(ModelNode response, int stepCount) {
String responseString = response.toString();
assertEquals(responseString, SUCCESS, response.get(OUTCOME).asString());
assertTrue(responseString, response.hasDefined(RESULT));
ModelNode result = response.get(RESULT);
assertEquals(responseString, ModelType.OBJECT, result.getType());
List<Property> list = result.asPropertyList();
assertEquals(responseString, stepCount, list.size());
for (Property prop : list) {
ModelNode stepResp = prop.getValue();
assertEquals(responseString, SUCCESS, stepResp.get(OUTCOME).asString());
assertTrue(responseString, stepResp.hasDefined(RESULT, ATTRIBUTES));
ModelNode stepResult = stepResp.get(RESULT);
Set<String> keys = stepResult.get(ATTRIBUTES).keys();
assertTrue(responseString, keys.contains("launch-type"));
assertTrue(responseString, keys.contains("server-state"));
assertTrue(responseString, keys.contains("runtime-configuration-state"));
assertTrue(responseString, stepResult.hasDefined(ACCESS_CONTROL, "default", ATTRIBUTES));
Set<String> accessKeys = stepResult.get(ACCESS_CONTROL, "default", ATTRIBUTES).keys();
assertTrue(responseString, accessKeys.contains("launch-type"));
assertTrue(responseString, accessKeys.contains("server-state"));
assertTrue(responseString, accessKeys.contains("runtime-configuration-state"));
assertTrue(responseString, stepResult.hasDefined(ACCESS_CONTROL, EXCEPTIONS));
assertEquals(responseString, 0, stepResult.get(ACCESS_CONTROL, EXCEPTIONS).asInt());
switch (prop.getName()) {
case "step-1":
case "step-2":
assertEquals(responseString, 3, keys.size());
assertEquals(responseString, 3, accessKeys.size());
break;
case "step-3":
case "step-4":
assertTrue(responseString, keys.size() > 2);
assertEquals(responseString, keys.size(), accessKeys.size());
break;
default:
fail(responseString);
}
}
}
private static ModelNode createReadResourceOperation(final ModelNode address) {
final ModelNode operation = new ModelNode();
operation.get(OP).set(READ_RESOURCE_OPERATION);
operation.get(OP_ADDR).set(address);
return operation;
}
/**
* Tests reads in composite operations when the DC exclusive lock is acquired by another operation.
*/
@Test
public void testCompositeOperationsWriteLockAcquired() throws Exception {
ModelNode result, op;
op = Util.createEmptyOperation(READ_CHILDREN_TYPES_OPERATION, PathAddress.pathAddress(HOST_SLAVE));
result = DomainTestUtils.executeForResult(op, masterClient);
final List<String> slaveChildrenTypes = result.asList().stream().map(m -> m.asString()).collect(Collectors.toList());
op = Util.createEmptyOperation(READ_CHILDREN_TYPES_OPERATION, PathAddress.EMPTY_ADDRESS);
result = DomainTestUtils.executeForResult(op, masterClient);
final List<String> emptyAddressChildrenTypes = result.asList().stream().map(m -> m.asString()).collect(Collectors.toList());
createDeployment();
final ExecutorService executorService = Executors.newFixedThreadPool(1);
try {
Future<ModelNode> deploymentFuture = executorService.submit(new Callable<ModelNode>() {
@Override
public ModelNode call() throws Exception {
// Take the DC write lock
final ModelNode op = getDeploymentCompositeOp();
DomainClient client = domainMasterLifecycleUtil.createDomainClient();
return DomainTestUtils.executeForResult(op, client);
}
});
// verify reads in a composite operations
List<ModelNode> steps;
// it could ensure we have acquired the lock by the deployment operation executed before
TimeUnit.SECONDS.sleep(TimeoutUtil.adjust(1));
steps = prepareReadCompositeOperations(PathAddress.pathAddress(HOST_SLAVE), slaveChildrenTypes);
op = createComposite(steps);
DomainTestUtils.executeForResult(op, masterClient);
steps = prepareReadCompositeOperations(PathAddress.EMPTY_ADDRESS, emptyAddressChildrenTypes);
op = createComposite(steps);
DomainTestUtils.executeForResult(op, masterClient);
steps = prepareReadCompositeOperations(PathAddress.pathAddress(HOST_SLAVE), slaveChildrenTypes);
steps.addAll(prepareReadCompositeOperations(PathAddress.EMPTY_ADDRESS, emptyAddressChildrenTypes));
op = createComposite(steps);
DomainTestUtils.executeForResult(op, masterClient);
Assert.assertEquals("It is expected deployment operation is still in progress", false, deploymentFuture.isDone());
// keep the timeout in sync with SlowServiceActivator timeout
deploymentFuture.get(TimeoutUtil.adjust(60), TimeUnit.SECONDS);
} finally {
try {
cleanDeploymentFromServerGroup();
} catch (MgmtOperationException e) {
// ignored
} finally {
try {
cleanDeployment();
} catch (MgmtOperationException e) {
// ignored
}
}
executorService.shutdown();
}
}
private ModelNode getDeploymentCompositeOp() throws Exception {
ModelNode op = new ModelNode();
op.get(OP).set(COMPOSITE);
ModelNode steps = op.get(STEPS);
ModelNode depAdd = Util.createAddOperation(PathAddress.pathAddress(DEPLOYMENT_PATH));
ModelNode content = new ModelNode();
content.get(URL).set(deployment.toURI().toURL().toString());
depAdd.get(CONTENT).add(content);
steps.add(depAdd);
ModelNode sgAdd = Util.createAddOperation(PathAddress.pathAddress(SERVER_GROUP_MAIN_SERVER_GROUP, DEPLOYMENT_PATH));
sgAdd.get(ENABLED).set(true);
steps.add(sgAdd);
return op;
}
private static void createDeployment() throws Exception {
File tmpRoot = new File(System.getProperty("java.io.tmpdir"));
tmpDir = new File(tmpRoot, CompositeOperationTestCase.class.getSimpleName() + System.currentTimeMillis());
Files.createDirectory(tmpDir.toPath());
deployment = new File(tmpDir, DEPLOYMENT_NAME);
final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, DEPLOYMENT_NAME)
.addClasses(SlowServiceActivator.class, TimeoutUtil.class)
.addAsManifestResource(new StringAsset("Dependencies: org.wildfly.security.elytron-private\n"), "MANIFEST.MF")
.addAsServiceProvider(ServiceActivator.class, SlowServiceActivator.class)
.addAsManifestResource(createPermissionsXmlAsset(new PropertyPermission("ts.timeout.factor", "read")), "permissions.xml");
archive.as(ZipExporter.class).exportTo(deployment);
}
private void cleanDeploymentFromServerGroup() throws IOException, MgmtOperationException {
ModelNode op = Util.createRemoveOperation(PathAddress.pathAddress(SERVER_GROUP_MAIN_SERVER_GROUP, DEPLOYMENT_PATH));
op.get(ENABLED).set(true);
DomainTestUtils.executeForResult(op, masterClient);
}
private void cleanDeployment() throws IOException, MgmtOperationException {
ModelNode op = Util.createRemoveOperation(PathAddress.pathAddress(DEPLOYMENT_PATH));
DomainTestUtils.executeForResult(op, masterClient);
}
private ModelNode createComposite(List<ModelNode> steps) {
ModelNode composite = Util.createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS);
ModelNode stepsNode = composite.get(STEPS);
for (ModelNode step : steps) {
stepsNode.add(step);
}
return composite;
}
private List<ModelNode> prepareReadCompositeOperations(PathAddress address, List<String> childTypes) {
final List<ModelNode> steps = new ArrayList<>();
ModelNode step;
step = Util.createEmptyOperation(READ_RESOURCE_OPERATION, address);
addCommonReadOperationAttributes(step);
steps.add(step);
for(String childType : childTypes) {
step = Util.createEmptyOperation(READ_CHILDREN_RESOURCES_OPERATION, address);
addCommonReadOperationAttributes(step);
step.get("child-type").set(childType);
steps.add(step);
}
return steps;
}
private void addCommonReadOperationAttributes(ModelNode op) {
String operation = op.get(OP).asString();
switch (operation) {
case READ_RESOURCE_OPERATION: {
op.get("include-aliases").set(true);
op.get("include-undefined-metric-values").set(true);
}
case READ_CHILDREN_RESOURCES_OPERATION: {
op.get("include-runtime").set(true);
op.get("recursive").set(true);
op.get("include-defaults").set(true);
op.get("proxies").set(true);
}
}
}
}
| 50.020633 | 145 | 0.681809 |
9ac12b3f1e0aeb979e1b347fe99588670259b87a | 3,066 | package com.androidx.gallery;
import android.app.Application;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.androidx.gallery.config.GalleryConfig;
import com.androidx.gallery.db.GalleryDataSource;
import com.androidx.gallery.db.os.AndroidDataSource;
import com.androidx.gallery.provider.ImageLoader;
import com.androidx.gallery.provider.impl.GlideImageLoader;
import com.androidx.gallery.utils.GalleryUtils;
import com.google.gson.Gson;
import com.androidx.matisse.engine.impl.GlideEngine;
import com.androidx.matisse.internal.entity.SelectionSpec;
import java.util.Objects;
/**
* 图库管理器
* @author RAE
* @date 2022/01/18
* Copyright (c) https://github.com/raedev All rights reserved.
*/
public final class GalleryManager {
// region 初始化
private static GalleryManager sManager;
/**
* 初始化图库
* @param context ApplicationContext
*/
public static void init(Context context) {
if (!(context instanceof Application)) {
throw new IllegalArgumentException("初始化图库实例的Context应为Application");
}
if (sManager == null) {
sManager = new GalleryManager((Application) context);
}
}
/**
* 获取图库实例
* @return 图库
*/
public static GalleryManager getInstance() {
return Objects.requireNonNull(sManager, "请先初始化图库管理器");
}
// endregion
private final Application mContext;
@Nullable
private GalleryConfig mConfig;
private GalleryDataSource mDataSource;
private ImageLoader mImageLoader;
private GalleryManager(Application context) {
mContext = context;
mImageLoader = new GlideImageLoader(context);
}
/**
* 设置数据源
* @param dataSource 数据源
*/
public void setDataSource(GalleryDataSource dataSource) {
mDataSource = Objects.requireNonNull(dataSource, "图库数据源不能为空");
}
/**
* 获取数据源
* @return 数据源
*/
@NonNull
public GalleryDataSource getDataSource() {
if (mDataSource == null) {
// 如果数据源为空,默认使用APP内部的
mDataSource = new AndroidDataSource(mContext);
}
return Objects.requireNonNull(mDataSource, "图库数据源没有提供");
}
/**
* 设置配置项
*/
public void setConfig(@Nullable GalleryConfig config) {
mConfig = config;
}
/**
* 获取配置项
*/
@NonNull
public GalleryConfig getConfig() {
if (mConfig != null) {
return mConfig;
}
// 从配置文件中加载
String json = GalleryUtils.readerConfig(mContext);
if (json != null) {
mConfig = new Gson().fromJson(json, GalleryConfig.class);
}
if (mConfig == null) {
mConfig = new GalleryConfig();
}
return mConfig;
}
/**
* 设置图片加载器
*/
public void setImageLoader(ImageLoader imageLoader) {
mImageLoader = imageLoader;
}
/**
* 获取图片加载器
*/
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
| 23.767442 | 79 | 0.637965 |
057bf865caa5f2aa861d0ba45df5e99c24341c8e | 10,139 | package uk.gov.hmcts.reform.iacaseapi.domain.handlers.presubmit;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static uk.gov.hmcts.reform.iacaseapi.domain.entities.AsylumCaseFieldDefinition.UPLOAD_HOME_OFFICE_BUNDLE_ACTION_AVAILABLE;
import java.util.Arrays;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.AsylumCase;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.CaseDetails;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.Event;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.State;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.Callback;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.PreSubmitCallbackResponse;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.PreSubmitCallbackStage;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.field.YesOrNo;
@MockitoSettings(strictness = Strictness.LENIENT)
@ExtendWith(MockitoExtension.class)
@SuppressWarnings("unchecked")
class FtpaAppealStateHandlerTest {
@Mock
private Callback<AsylumCase> callback;
@Mock
private CaseDetails<AsylumCase> caseDetails;
@Mock
private AsylumCase asylumCase;
@Mock
private PreSubmitCallbackResponse<AsylumCase> callbackResponse;
private FtpaAppealStateHandler ftpaAppealStateHandler;
@BeforeEach
public void setUp() {
ftpaAppealStateHandler = new FtpaAppealStateHandler();
}
@Test
void should_return_updated_state_for_appellant_from_decided_state() {
when(callback.getCaseDetails()).thenReturn(caseDetails);
when(callback.getEvent()).thenReturn(Event.APPLY_FOR_FTPA_APPELLANT);
when(caseDetails.getCaseData()).thenReturn(asylumCase);
when(caseDetails.getState()).thenReturn(State.DECIDED);
PreSubmitCallbackResponse<AsylumCase> returnedCallbackResponse =
ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, callback, callbackResponse);
assertNotNull(returnedCallbackResponse);
Assertions.assertThat(returnedCallbackResponse.getState()).isEqualTo(State.FTPA_SUBMITTED);
assertEquals(asylumCase, returnedCallbackResponse.getData());
}
@Test
void should_return_updated_state_for_respondent_from_decided_state() {
when(callback.getCaseDetails()).thenReturn(caseDetails);
when(callback.getEvent()).thenReturn(Event.APPLY_FOR_FTPA_RESPONDENT);
when(caseDetails.getCaseData()).thenReturn(asylumCase);
when(caseDetails.getState()).thenReturn(State.DECIDED);
PreSubmitCallbackResponse<AsylumCase> returnedCallbackResponse =
ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, callback, callbackResponse);
assertNotNull(returnedCallbackResponse);
Assertions.assertThat(returnedCallbackResponse.getState()).isEqualTo(State.FTPA_SUBMITTED);
assertEquals(asylumCase, returnedCallbackResponse.getData());
}
@Test
void should_return_updated_state_for_appellant_from_ftpa_submitted_state() {
when(callback.getCaseDetails()).thenReturn(caseDetails);
when(callback.getEvent()).thenReturn(Event.APPLY_FOR_FTPA_APPELLANT);
when(caseDetails.getCaseData()).thenReturn(asylumCase);
when(caseDetails.getState()).thenReturn(State.FTPA_SUBMITTED);
PreSubmitCallbackResponse<AsylumCase> returnedCallbackResponse =
ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, callback, callbackResponse);
assertNotNull(returnedCallbackResponse);
Assertions.assertThat(returnedCallbackResponse.getState()).isEqualTo(State.FTPA_SUBMITTED);
assertEquals(asylumCase, returnedCallbackResponse.getData());
}
@Test
void should_return_updated_state_for_respondent_from_ftpa_submitted_state() {
when(callback.getCaseDetails()).thenReturn(caseDetails);
when(callback.getEvent()).thenReturn(Event.APPLY_FOR_FTPA_RESPONDENT);
when(caseDetails.getCaseData()).thenReturn(asylumCase);
when(caseDetails.getState()).thenReturn(State.FTPA_SUBMITTED);
PreSubmitCallbackResponse<AsylumCase> returnedCallbackResponse =
ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, callback, callbackResponse);
assertNotNull(returnedCallbackResponse);
Assertions.assertThat(returnedCallbackResponse.getState()).isEqualTo(State.FTPA_SUBMITTED);
assertEquals(asylumCase, returnedCallbackResponse.getData());
}
@Test
void should_return_updated_state_for_appellant_from_ftpa_decided_state() {
when(callback.getCaseDetails()).thenReturn(caseDetails);
when(callback.getEvent()).thenReturn(Event.APPLY_FOR_FTPA_APPELLANT);
when(caseDetails.getCaseData()).thenReturn(asylumCase);
when(caseDetails.getState()).thenReturn(State.FTPA_DECIDED);
PreSubmitCallbackResponse<AsylumCase> returnedCallbackResponse =
ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, callback, callbackResponse);
assertNotNull(returnedCallbackResponse);
Assertions.assertThat(returnedCallbackResponse.getState()).isEqualTo(State.FTPA_DECIDED);
assertEquals(asylumCase, returnedCallbackResponse.getData());
}
@Test
void should_return_updated_state_for_respondent_from_ftpa_decided_state() {
when(callback.getCaseDetails()).thenReturn(caseDetails);
when(callback.getEvent()).thenReturn(Event.APPLY_FOR_FTPA_RESPONDENT);
when(caseDetails.getCaseData()).thenReturn(asylumCase);
when(caseDetails.getState()).thenReturn(State.FTPA_DECIDED);
PreSubmitCallbackResponse<AsylumCase> returnedCallbackResponse =
ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, callback, callbackResponse);
assertNotNull(returnedCallbackResponse);
Assertions.assertThat(returnedCallbackResponse.getState()).isEqualTo(State.FTPA_DECIDED);
assertEquals(asylumCase, returnedCallbackResponse.getData());
}
@Test
void should_return_original_state_when_conditions_not_met() {
when(callback.getCaseDetails()).thenReturn(caseDetails);
when(callback.getEvent()).thenReturn(Event.APPLY_FOR_FTPA_APPELLANT);
when(caseDetails.getCaseData()).thenReturn(asylumCase);
final State priorState = State.DECISION;
when(caseDetails.getState()).thenReturn(priorState);
PreSubmitCallbackResponse<AsylumCase> returnedCallbackResponse =
ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, callback, callbackResponse);
assertNotNull(returnedCallbackResponse);
Assertions.assertThat(returnedCallbackResponse.getState()).isEqualTo(priorState);
assertEquals(asylumCase, returnedCallbackResponse.getData());
}
@Test
void handling_should_throw_if_cannot_actually_handle() {
assertThatThrownBy(
() -> ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_START, callback, callbackResponse))
.hasMessage("Cannot handle callback")
.isExactlyInstanceOf(IllegalStateException.class);
when(callback.getEvent()).thenReturn(Event.SEND_DIRECTION);
assertThatThrownBy(
() -> ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, callback, callbackResponse))
.hasMessage("Cannot handle callback")
.isExactlyInstanceOf(IllegalStateException.class);
verify(asylumCase, never()).write(UPLOAD_HOME_OFFICE_BUNDLE_ACTION_AVAILABLE, YesOrNo.NO);
}
@Test
void it_can_handle_callback() {
for (Event event : Event.values()) {
when(callback.getEvent()).thenReturn(event);
for (PreSubmitCallbackStage callbackStage : PreSubmitCallbackStage.values()) {
boolean canHandle = ftpaAppealStateHandler.canHandle(callbackStage, callback);
if (Arrays.asList(
Event.APPLY_FOR_FTPA_APPELLANT,
Event.APPLY_FOR_FTPA_RESPONDENT
).contains(event)
&& callbackStage == PreSubmitCallbackStage.ABOUT_TO_SUBMIT) {
assertTrue(canHandle);
} else {
assertFalse(canHandle);
}
}
reset(callback);
}
}
@Test
void should_not_allow_null_arguments() {
assertThatThrownBy(() -> ftpaAppealStateHandler.canHandle(null, callback))
.hasMessage("callbackStage must not be null")
.isExactlyInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> ftpaAppealStateHandler.canHandle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, null))
.hasMessage("callback must not be null")
.isExactlyInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> ftpaAppealStateHandler.handle(null, callback, callbackResponse))
.hasMessage("callbackStage must not be null")
.isExactlyInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> ftpaAppealStateHandler.handle(PreSubmitCallbackStage.ABOUT_TO_SUBMIT, null, null))
.hasMessage("callback must not be null")
.isExactlyInstanceOf(NullPointerException.class);
}
}
| 42.780591 | 129 | 0.746326 |
1da408049a309ea4f8a9a69dc9418c852b9fc1c6 | 524 | package com.atyume.modules.system.service;
import com.atyume.modules.base.service.IService;
import com.atyume.modules.system.dto.TreeDto;
import com.atyume.modules.system.po.Organization;
import java.util.List;
public interface OrganizationService extends IService<Organization> {
void createOrganization(Organization organization);
List<TreeDto> queryOrgTree(Long pId);
List<Organization> queryAllWithExclude(Organization excludeOraganization);
void move(Organization source, Organization target);
}
| 27.578947 | 78 | 0.807252 |
50bdb3b1ac6e087fc491bd7674f2e9408e1b5038 | 1,395 | package jp.chang.myclinic.practice.javafx.parts;
import javafx.collections.FXCollections;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
public class SearchResult<M> extends ListView<M> {
private Function<M,String> converter = Object::toString;
private Consumer<M> onSelectCallback = m -> {};
public SearchResult(){
getStyleClass().add("search-result");
setCellFactory(listView -> new ListCell<M>(){
@Override
protected void updateItem(M item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? "" : converter.apply(item));
}
});
setOnMouseClicked(this::onMouseClick);
}
public void setList(List<M> list){
itemsProperty().setValue(FXCollections.observableArrayList(list));
}
public void setOnSelectCallback(Consumer<M> cb){
this.onSelectCallback = cb;
}
public void setConverter(Function<M,String> converter){
this.converter = converter;
}
private void onMouseClick(MouseEvent event){
M selected = getSelectionModel().getSelectedItem();
if( selected != null ){
onSelectCallback.accept(selected);
}
}
}
| 28.469388 | 74 | 0.659498 |
46e1d4e50989efb7c5c44aa67bdf99ea370fccc7 | 1,352 | package com.yushkevich.metrics.consumer.repository;
import com.yushkevich.metrics.commons.message.Metric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
public class MetricRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(MetricRepository.class);
private C3poDataSource dataSource;
public MetricRepository(C3poDataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(Metric metric) throws SQLException {
var query = "INSERT INTO os_metric(description, name, value, created_at, env) VALUES( ?, ?, ?, ?, ?)";
try (
Connection conn = dataSource.getConnection();
PreparedStatement preparedStatement = conn.prepareStatement(query)
) {
preparedStatement.setString(1, metric.getDescription());
preparedStatement.setString(2, metric.getName());
preparedStatement.setDouble(3, metric.getValue());
preparedStatement.setTimestamp(4, new Timestamp(metric.getCreatedAt()));
preparedStatement.setString(5, metric.getEnv());
preparedStatement.execute();
LOGGER.info("Inserted in DB: {}", metric);
}
}
}
| 32.190476 | 110 | 0.68713 |
d803ee61d5a8f8c97dcf4ec0b31b34421855c4e3 | 1,818 | package cellsociety.Utilities.CSVParser;
import cellsociety.cell.IllegalCellStateException;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.ResourceBundle;
public abstract class CSVParser {
private static final String DEFAULT_RESOURCE_PACKAGE =
CSVParser.class.getPackageName() + ".resources.";
private static final String VALID_STATES_FILENAME = "ValidStates";
private File file;
private int rows;
private int cols;
public File getFile() {
return file;
}
public void setFile(File file) throws InputMismatchException {
if (!file.getName().endsWith(".csv")) {
throw new InputMismatchException();
}
this.file = file;
}
public abstract List<Integer> getCellStates(String simType)
throws FileNotFoundException, IllegalCellStateException, IllegalRowSizeException, InvalidDimensionException;
public List<Integer> getValidStatesList(String simType) {
ResourceBundle validStatesBundle = ResourceBundle.getBundle(
DEFAULT_RESOURCE_PACKAGE + VALID_STATES_FILENAME);
if (validStatesBundle.containsKey(simType)) {
return extractIntList(validStatesBundle.getString(simType));
}
return extractIntList(validStatesBundle.getString("Default"));
}
private List<Integer> extractIntList(String commaArr) {
String[] arr = commaArr.split(",");
List<Integer> intList = new ArrayList<>();
for (String element : arr) {
intList.add(Integer.parseInt(element));
}
return intList;
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public void setRows(int rows) {
this.rows = rows;
}
public void setCols(int cols) {
this.cols = cols;
}
}
| 26.735294 | 114 | 0.726623 |
79be53452e851f4508a9f95ce4003bb2772c2baf | 152 | public class Replace {
public static void main(String[] args) {
String s = "Hello".replace('l','w');
System.out.println(s);
}
}
| 21.714286 | 44 | 0.565789 |
f61aea4db8150ab0033edf69dc89f53ddd094436 | 130 | package com.zbx.service;
import com.zbx.pojo.User;
public interface UserService {
public User getUserById(int userId);
}
| 13 | 39 | 0.738462 |
09fd713c212e3d8cb59ff0fe1f0ab6bc440f2464 | 6,696 | package com.dnastack.ddap.explore.resource.service;
import com.dnastack.ddap.explore.common.session.PersistantSession;
import com.dnastack.ddap.explore.common.session.SessionEncryptionUtils;
import com.dnastack.ddap.explore.resource.data.UserCredentialDao;
import com.dnastack.ddap.explore.resource.model.Id.InterfaceId;
import com.dnastack.ddap.explore.resource.model.UserCredential;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.jdbi.v3.core.Jdbi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.server.WebSession;
@Component
@Slf4j
public class UserCredentialService {
private final Jdbi jdbi;
private final ObjectMapper mapper;
@Autowired
public UserCredentialService(Jdbi jdbi, ObjectMapper mapper) {
this.mapper = mapper;
this.jdbi = jdbi;
}
public String getUserIdentifier(WebSession session) {
String userIdentifier = session.getAttribute(PersistantSession.USER_IDENTIFIER_KEY);
if (userIdentifier == null) {
throw new IllegalArgumentException("User does not exist within a session");
}
return userIdentifier;
}
public Optional<UserCredential> getAndDecryptCredentialsForResourceInterface(String privateKey, WebSession session, InterfaceId resourceId) {
return getCredentialsForResourceInterface(session, resourceId)
.map(userCredential -> decryptCredentials(privateKey, userCredential));
}
public Optional<UserCredential> getCredentialsForResourceInterface(WebSession session, InterfaceId resourceId) {
return jdbi.withExtension(UserCredentialDao.class, dao -> dao
.getCredentialForResource(getUserIdentifier(session), resourceId.encodeId()));
}
public List<UserCredential> getSessionBoundCredentials(WebSession session, List<String> interfaceIds) {
return jdbi.withExtension(UserCredentialDao.class, dao -> dao
.getCredentialsForResources(getUserIdentifier(session), interfaceIds));
}
public List<UserCredential> getAndDecryptCredentials(String privateKey, WebSession session, List<String> interfaceIds) {
return jdbi.withExtension(UserCredentialDao.class, dao -> dao
.getCredentialsForResources(getUserIdentifier(session), interfaceIds))
.stream().map(userCredential -> decryptCredentials(privateKey, userCredential))
.collect(Collectors.toList());
}
private UserCredential decryptCredentials(String privateKey, UserCredential userCredential) {
String decryptedCredentials = SessionEncryptionUtils
.decryptData(privateKey, userCredential.getEncryptedCredentials());
userCredential.setCredentials(parseCredentialString(decryptedCredentials));
return userCredential;
}
public String requirePrivateKeyInCookie(ServerHttpRequest request) {
HttpCookie privateKey = request.getCookies().getFirst(SessionEncryptionUtils.COOKIE_NAME);
if (privateKey == null || privateKey.getValue() == null) {
throw new IllegalArgumentException(
"Could not extract the Session Decryption from the Cookie: " + SessionEncryptionUtils.COOKIE_NAME
+ ". Cookie does not exist");
}
return privateKey.getValue();
}
public void storeCredentialsForResource(WebSession session, List<UserCredential> userCredentials) {
String principal = getUserIdentifier(session);
List<String> ids = userCredentials.stream().map(UserCredential::getInterfaceId)
.collect(Collectors.toList());
userCredentials.forEach(userCredential -> {
userCredential.setPrincipalId(getUserIdentifier(session));
String encryptedCredentials = SessionEncryptionUtils
.encryptData(session, serializeCredentialMap(userCredential.getCredentials()));
userCredential.setEncryptedCredentials(encryptedCredentials);
userCredential.setCreationTime(ZonedDateTime.now());
if (userCredential.getExpirationTime() == null) {
userCredential.setExpirationTime(ZonedDateTime.now().plusHours(1));
}
});
jdbi.useExtension(UserCredentialDao.class, dao -> {
List<UserCredential> credentials = dao.getCredentialsForResources(principal, ids);
if (credentials != null && !credentials.isEmpty()) {
List<String> idsToDelete = credentials.stream().map(UserCredential::getInterfaceId)
.collect(Collectors.toList());
dao.deleteCredentials(principal, idsToDelete);
}
dao.createUserCredentials(userCredentials);
});
}
public int deleteCredential(WebSession session, String id) {
return jdbi.withExtension(UserCredentialDao.class, dao -> dao.deleteCredential(getUserIdentifier(session), id));
}
private Map<String, String> parseCredentialString(String credentialString) {
try {
TypeReference<Map<String, String>> typeReference = new TypeReference<>() {
};
return mapper.readValue(credentialString, typeReference);
} catch (IOException e) {
log.error(
"Encountered an error while parsing credential string: " + e.getMessage() + ", returning empty Map", e);
return Map.of();
}
}
private String serializeCredentialMap(Map<String, String> credentialMap) {
try {
return mapper.writeValueAsString(credentialMap);
} catch (IOException e) {
log.error(
"Encountered an error while parsing credential string: " + e.getMessage()
+ ", returning empty representation", e);
return "{}";
}
}
@Scheduled(fixedDelay = 300000)
public void deleteExpiredCredentials() {
jdbi.useExtension(UserCredentialDao.class, dao -> {
log.info("Cleaning up expired or orphaned session resource tokens");
int tokensDeleted = dao.deleteExpiredCredentials();
log.info("Removed " + tokensDeleted + " expired or orphaned tokens");
});
}
}
| 43.2 | 145 | 0.704749 |
23c7310122c0ae532b8105f6726c613fe0800da1 | 283 | package crafttweaker.runtime;
import java.io.*;
/**
* @author Stan
*/
public interface IScriptIterator {
String getGroupName();
boolean next();
String getName();
InputStream open() throws IOException;
IScriptIterator copyCurrent();
}
| 14.15 | 42 | 0.628975 |
7600f13589e3499634cfe301c2500f990fbc9572 | 496 | package com.desertkun.brainout.mode.payload;
import com.desertkun.brainout.client.Client;
public class FoxHuntPayload extends ModePayload
{
private boolean fox;
public FoxHuntPayload(Client playerClient)
{
super(playerClient);
}
@Override
public void init()
{
}
@Override
public void release()
{
}
public boolean isFox()
{
return fox;
}
public void setFox(boolean fox)
{
this.fox = fox;
}
}
| 13.777778 | 47 | 0.606855 |
a55deb577c9720d9aebe4ab8d366b01fc2190a69 | 1,907 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Academics;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
/**
*
* @author Softavate3
*/
public class Fetch extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
System.out.println("aaaaaaaaaaaaaaabbbbbbbbbaaaaaaaaaa");
String pid = request.getParameter("sess");
System.out.println("pid"+pid);
String result=null;
String id=null;
String name=null;
try {
Connection con11 = connection.getDBConnection.makeConn();
Statement st11 = con11.createStatement();
String sql = "select sub_id,sub_name from subject where sub_id ='" + pid + "'";
System.out.println(sql);
ResultSet rs11 = st11.executeQuery(sql);
result = "";
if (rs11.next()) {
id=rs11.getString(1);
name = rs11.getString(2);
}
result = id + ":~" + name + ":~";
con11.close();
st11.close();
} catch (Exception e) {
}
out.write("<status><valid>" + result + "</valid></status>");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
//..... heap memory control.....
Runtime r = Runtime.getRuntime();
r.freeMemory();
r.gc();
}
}
| 28.044118 | 91 | 0.606188 |
5b7946411e22db9a9af39c77a5bb47fdc2926357 | 2,361 | package cz.zcu.viteja.uur.views;
import java.time.LocalDate;
import cz.zcu.viteja.uur.data.AgendaEvent;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableCell;
import javafx.scene.text.Font;
public class AgendaDateCell extends TableCell<AgendaEvent, String> {
private DatePicker dateDP;
// switching to the editation mode
public void startEdit() {
// propagation of mode switching to the parent class
super.startEdit();
// creating editor - DatePicker if it is not already prepared
if (dateDP == null) {
createDatePicker();
}
// disabling label with text
setText(null);
// setting up editor
setGraphic(dateDP);
// opening editor (fields with calendar)
dateDP.show();
}
// switching from editation to presentation mode
public void cancelEdit() {
super.cancelEdit();
// setting label
setText(getItem().toString());
// removing date picker
setGraphic(null);
}
// creating date picker
private void createDatePicker() {
dateDP = new DatePicker(LocalDate.now());
// forbidding writing to the date picker field - only mouse selection of
// the date is allowed
dateDP.setEditable(false);
// reaction on commit - when date is selected, date picker have to
// create commit event
dateDP.setOnAction(event -> {
// commit when date was selected
if (dateDP.getValue() != null) {
commitEdit("");
// cancel when no date was provided
} else {
cancelEdit();
}
});
}
// setting value to the cell when model is changed or manipulated
// this method have to be always overloaded, when new cell type is created
public void updateItem(String item, boolean empty) {
// propagating change to the parent class
super.updateItem(item, empty);
// setting font for the label
setFont(new Font("Arial", 15));
// when no item is provided, cell is showing no information
if (empty) {
setText(null);
setGraphic(null);
} else {
// in editation mode
if (isEditing()) {
// setting the value to editor - date picker
if (dateDP != null) {
dateDP.setValue(LocalDate.now());
}
// disabling label
setText(null);
// setting up editor
setGraphic(dateDP);
// in presentation mode
} else {
// setting the date to label
setText(getItem().toString());
// disabling editor
setGraphic(null);
}
}
}
}
| 25.117021 | 75 | 0.685303 |
f0d735ea8d860a67430a922d160540f79252e461 | 2,139 | package com.prox.api;
import java.util.Date;
import retrofit.RestAdapter;
import android.util.Log;
import com.prox.api.util.DateFormatter;
import com.prox.api.util.ProxEndpoints;
import com.prox.api.util.ProxEndpoints.IProxAPI;
public class ProxApi {
public static void getContributors() {
// Create a very simple REST adapter which points the GitHub API
// endpoint.
RestAdapter restAdapter = new RestAdapter.Builder().setServer(ProxEndpoints.BASE_URL).build();
// Create an instance of our GitHub API interface.
IProxAPI api = restAdapter.create(IProxAPI.class);
// Fetch and print a list of the contributors to this library.
String appId = ProxEndpoints.getApplicationId();
if (appId != null)
api.totalUniqueVisitors(appId, DateFormatter.format(new Date()), DateFormatter.format(new Date()));
else {
Log.e("PROX", "FUCK");
}
}
public static void getTotalVisitors() {
// Create a very simple REST adapter which points the GitHub API
// endpoint.
RestAdapter restAdapter = new RestAdapter.Builder().setServer(ProxEndpoints.BASE_URL).build();
// Create an instance of our GitHub API interface.
IProxAPI api = restAdapter.create(IProxAPI.class);
// Fetch and print a list of the contributors to this library.
String appId = ProxEndpoints.getApplicationId();
if (appId != null)
api.totalVisitors(appId, DateFormatter.format(new Date()), DateFormatter.format(new Date()));
else {
Log.e("PROX", "FUCK");
}
}
public static void getVenueVisitLength() {
// Create a very simple REST adapter which points the GitHub API
// endpoint.
RestAdapter restAdapter = new RestAdapter.Builder().setServer(ProxEndpoints.BASE_URL).build();
// Create an instance of our GitHub API interface.
IProxAPI api = restAdapter.create(IProxAPI.class);
// Fetch and print a list of the contributors to this library.
String appId = ProxEndpoints.getApplicationId();
if (appId != null) {
Log.e("PROX", DateFormatter.format(new Date()));
api.venueVisitLength(appId, DateFormatter.format(new Date()), DateFormatter.format(new Date()));
} else {
Log.e("PROX", "FUCK");
}
}
}
| 32.409091 | 102 | 0.72978 |
fad58cdd1286d9775cd6c55613a89400cf63e54a | 1,890 | package com.gitlab.pedrioko.core.view.util;
import com.gitlab.pedrioko.core.reflection.ReflectionJavaUtil;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
/**
* The Class ArraysUtil.
*/
public class ArraysUtil {
public static void removeDuplicates(Class<?> typeClass, List<? extends Object> fulllist, List<?> toremove) {
if (toremove != null)
if (!toremove.isEmpty()) {
List<? extends Object> aux = new LinkedList<>(fulllist);
for (int i = 0; i < fulllist.size(); i++) {
for (int x = 0; x < toremove.size(); x++) {
if (String.valueOf(ReflectionJavaUtil.getIdValue(toremove.get(x))).trim().equalsIgnoreCase(
String.valueOf(ReflectionJavaUtil.getIdValue(fulllist.get(i))).trim()))
aux.remove(fulllist.get(i));
}
}
fulllist.clear();
fulllist.addAll((List) aux);
}
}
/**
* Suma.
*
* @param list the list
* @return the int
*/
public static int suma(List<Long> list) {
return list.parallelStream().mapToLong(Long::longValue).mapToObj(BigDecimal::new)
.reduce(BigDecimal.ZERO, BigDecimal::add).intValue();
}
/**
* Removes the duplicates.
*
* @param <T> the generic type
* @param list the list
* @return the list
*/
public static <T> List<T> removeDuplicates(List<T> list) {
return list.stream().distinct().collect(Collectors.toList());
}
/**
* Promedio.
*
* @param list the list
* @return the int
*/
public static double promedio(List<Long> list) {
return list.stream().mapToDouble(a -> a).average().orElse(0);
}
}
| 28.636364 | 115 | 0.560317 |
b85b1c229ecf45429b32f57814595ce9ab907cd1 | 1,438 | package io.github.joeljeremy7.externalizedproperties.resolvers.database;
import io.github.joeljeremy7.externalizedproperties.resolvers.database.testentities.JdbcUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import java.sql.SQLException;
@Testcontainers
public class MySqlIntegrationTests extends DatabaseIntegrationTests {
static final int NUMBER_OF_TEST_ENTRIES = 2;
static final DockerImageName MYSQL_IMAGE =
DockerImageName.parse("mysql:8.0.28");
@Container
static final MySQLContainer<?> MYSQL_CONTAINER =
new MySQLContainer<>(MYSQL_IMAGE);
@BeforeAll
static void setup() throws SQLException {
JdbcUtils.createPropertiesTable(
MYSQL_CONTAINER.createConnection(""),
2
);
}
@Override
String getJdbcConnectionString() {
return MYSQL_CONTAINER.getJdbcUrl();
}
@Override
String getJdbcUsername() {
return MYSQL_CONTAINER.getUsername();
}
@Override
String getJdbcPassword() {
return MYSQL_CONTAINER.getPassword();
}
/**
* Dummy test for junit to be able to detect this test class.
*/
@Test
void detect() {}
}
| 26.62963 | 94 | 0.717663 |
77eb238b0450386c9dd095b73c40484e6459c6d2 | 537 | package assimp.importer.ms3d;
import org.lwjgl.util.vector.Vector4f;
final class TempMaterial extends TempComment{
// again, add an extra 0 character to all strings -
final byte[] name = new byte[32];
final byte[] texture = new byte[128];
final byte[] alphamap = new byte[128];
// aiColor4D diffuse,specular,ambient,emissive;
final Vector4f diffuse = new Vector4f();
final Vector4f specular = new Vector4f();
final Vector4f ambient = new Vector4f();
final Vector4f emissive = new Vector4f();
float shininess,transparency;
}
| 28.263158 | 52 | 0.744879 |
fce15fcc9a16453c6dd182b3c4226dda744feb68 | 307 | package com.fred.inventory.utils.binding;
/**
* Observer interface to use with {@link Observable}
* <p/>
* Created by fred on 28.05.16.
*/
public interface Observer<T> {
/**
* Triggered by the observable when it's value changes
*
* @param value The new value
*/
void update(T value);
}
| 19.1875 | 56 | 0.654723 |
8901b5a5caf78f11a5113f73d89ff801d4e25085 | 4,402 | package include.Module;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDownloadFile {
/**
*
* @param sURL:下载地址,如http://www.xnx3.com/down/android/android2_2.apk
* @param sName:文件保存的名字,如android2_2_down.apk
* @param sPath:文件保存路径,如c:\\
*/
public void downAction(String sURL,String sName,String sPath){
int nStartPos = 0;
int nRead = 0;
try {
URL url = new URL(sURL);
// 打开连接
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
// 获得文件长度
long nEndPos = getFileSize(sURL);
RandomAccessFile oSavedFile = new RandomAccessFile(sPath + "\\"
+ sName, "rw");
httpConnection
.setRequestProperty("User-Agent", "Internet Explorer");
String sProperty = "bytes=" + nStartPos + "-";
// 告诉服务器book.rar这个文件从nStartPos字节开始传
httpConnection.setRequestProperty("RANGE", sProperty);
System.out.println(sProperty);
InputStream input = httpConnection.getInputStream();
byte[] b = new byte[1024];
// 读取网络文件,写入指定的文件中
while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos) {
oSavedFile.write(b, 0, nRead);
nStartPos += nRead;
}
httpConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String sURL = "http://www.xnx3.com/down/android/android2_2.apk";
int nStartPos = 0;
int nRead = 0;
String sName = "android2_2_down.apk";
String sPath = "c:\\";
try {
URL url = new URL(sURL);
// 打开连接
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
// 获得文件长度
long nEndPos = getFileSize(sURL);
RandomAccessFile oSavedFile = new RandomAccessFile(sPath + "\\"
+ sName, "rw");
httpConnection
.setRequestProperty("User-Agent", "Internet Explorer");
String sProperty = "bytes=" + nStartPos + "-";
// 告诉服务器book.rar这个文件从nStartPos字节开始传
httpConnection.setRequestProperty("RANGE", sProperty);
System.out.println(sProperty);
InputStream input = httpConnection.getInputStream();
byte[] b = new byte[1024];
// 读取网络文件,写入指定的文件中
while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos) {
oSavedFile.write(b, 0, nRead);
nStartPos += nRead;
}
httpConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
// 获得文件长度
public static long getFileSize(String sURL) {
int nFileLength = -1;
try {
URL url = new URL(sURL);
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
httpConnection
.setRequestProperty("User-Agent", "Internet Explorer");
int responseCode = httpConnection.getResponseCode();
if (responseCode >= 400) {
System.err.println("Error Code : " + responseCode);
return -2; // -2 represent access is error
}
String sHeader;
for (int i = 1;; i++) {
sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null) {
if (sHeader.equals("Content-Length")) {
nFileLength = Integer.parseInt(httpConnection
.getHeaderField(sHeader));
break;
}
} else
break;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(nFileLength);
return nFileLength;
}
} | 36.683333 | 85 | 0.509768 |
653a58ae5a02302ffb6fd984b46e361a1649b50f | 489 | package ui.ascii.machine;
/**
* As the machine could be entering wrong values trying to start a game,
* we need such state to indicate
*/
public enum MachineState {
VIEW_SELECTION("view-selection"), MAIN_MENU("main-menu"), SIZE_SELECTION("size-selection"), IDLE("idle"), GAMEOVER("gameover"), SHIFTING("shifting"), BAD_INPUT("bad-input");
private String text;
private MachineState(String text) {
this.text = text;
}
public String text() {
return this.text;
}
}
| 23.285714 | 175 | 0.695297 |
106ff9b90a10dd6b474b7f042451d3d0acd13d5f | 384 | import java.util.Scanner;
public class AreaPerimetroDoQuadrado {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Digite o valor do lado ");
double lado =in.nextDouble();
System.out.println("A área do quadrado é: "+(lado*lado));
System.out.println("O perimetro do quadrado é: "+(lado*4));
}
}
| 27.428571 | 67 | 0.645833 |
68230404e6b0e6b682e5a3c58aef1ef92e1da4bd | 731 | package simple;
/**
* Generated by jlemon.
* But file must be renamed from `parser.h`to `TokenType.java`.
* And package must be specified manually
*/
public interface TokenType {
short PLUS = 1;
short MINUS = 2;
short DIVIDE = 3;
short TIMES = 4;
short INTEGER = 5;
static String toString(short tokenType) {
switch(tokenType) {
case 1 : return "PLUS";
case 2 : return "MINUS";
case 3 : return "DIVIDE";
case 4 : return "TIMES";
case 5 : return "INTEGER";
}
throw new AssertionError(String.format("Unexpected token type: %d", tokenType));
}
}
| 29.24 | 84 | 0.525308 |
6f8ece20c55237a8a201533509152db8606691bf | 533 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model.interfaces;
/**
*
* @author Aluno
*/
public interface Operations {
public boolean verifyFrameElements();
public void getFrameElements();
public void setFrameElements();
public void removeFrameElements();
public void save();
public void delete();
}
| 20.5 | 80 | 0.634146 |
46deae6be4daebeeab9361b3c7c17603846358ec | 80 | package jllvmgen.instructions.conversion;
public class LLVMIntToPtrToInst {
}
| 13.333333 | 41 | 0.825 |
01239e61051b52eabb9df40cec5bb5e52789610d | 651 | /*
* file operations
*
* Created on: 06.04.18
* Author: Mikhail Belyshov
* Last Modify: $Id$
*
* Copyright © 1994-2018 Paragon Technologie GmbH.
*/
package com.paragon_software.dictionary_manager.file_operations;
import androidx.annotation.NonNull;
import com.paragon_software.dictionary_manager.file_operations.exceptions.CantDeleteFileException;
import com.paragon_software.dictionary_manager.file_operations.exceptions.FileWriteException;
public interface IFileStreamWriter
{
void write( @NonNull final byte[] data, final int len ) throws FileWriteException;
void remove() throws CantDeleteFileException;
void finish();
}
| 25.038462 | 98 | 0.788018 |
2b807551baf49dd00c829b96980b05538454ebf1 | 1,243 | package com.bodyash.spring.boot.wicket.minecraft.web.html.border;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.border.Border;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.FormComponentLabel;
import org.apache.wicket.model.Model;
public class LabeledFormBorder<T> extends Border {
private static final long serialVersionUID = 1L;
private FormComponent<T> formComponent;
public LabeledFormBorder(String labelText, FormComponent<T> container) {
super(container.getId() + "Border");
this.formComponent = container;
FormComponentLabel label = new FormComponentLabel("label", container);
label.add(new AttributeModifier("class", "control-label"));
Label somethingLabelSpan = new Label("labelText", labelText);
somethingLabelSpan.setRenderBodyOnly(true);
label.add(somethingLabelSpan);
addToBorder(label);
add(container);
}
@Override
protected void onBeforeRender() {
if (!formComponent.isValid()) {
add(new AttributeModifier("class", Model.of("form-group has-error")));
} else {
add(new AttributeModifier("class", "form-group"));
}
super.onBeforeRender();
}
}
| 29.595238 | 73 | 0.765084 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.