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 |
|---|---|---|---|---|---|
23319a341682c426508179e25332b191be488964 | 460 | package cn.toesbieya.jxc.record;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "cn.toesbieya.jxc")
@MapperScan("cn.toesbieya.jxc.record.mapper")
public class RecordApplication {
public static void main(String[] args) {
SpringApplication.run(RecordApplication.class, args);
}
}
| 32.857143 | 68 | 0.797826 |
54b14454a83a534e36d321205b40a8b1c4ee9e19 | 15,973 | /*
* Copyright (c) 2012-2014. Alain Barret
*
* 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.github.abarhub.filerw.text;
import com.github.abarhub.filerw.Tools;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class StructTextReaderTest {
@Test
public void testReadLine() throws URISyntaxException, IOException,
ParseException {
File f;
StructTextReader<FieldsListChamps1> in = null;
URL url = getClass().getResource("/data/exemple1.txt");
List<LineContentText<FieldsListChamps1>> list;
LineContentText<FieldsListChamps1> line;
int no;
assertNotNull(url);
f = new File(url.toURI());
System.out.println("Lecture du fichier " + f.getPath() + " :");
try {
in = new StructTextReader<>(new FileReader(f),
FieldsListChamps1.class);
list = new ArrayList<>();
no = 1;
while ((line = in.readLn()) != null) {
list.add(line);
avanceNewLine(in);
no++;
}
assertEquals(3, list.size(), "Error in line " + no);
} finally {
if (in != null)
in.close();
}
}
@Test
public void testReadLine2() throws URISyntaxException,
IOException, ParseException {
File f;
StructTextReader<FieldsListChamps1> in = null;
URL url = getClass().getResource("/data/exemple1.txt");
List<LineContentText<FieldsListChamps1>> list;
LineContentText<FieldsListChamps1> line;
int no;
String[] tab = {"Newton2 Isaac 04011643",
"Einstein Albert 14103879",
"Copernic Nicolas 19021473"};
assertNotNull(url);
f = new File(url.toURI());
System.out.println("Lecture du fichier " + f.getPath() + " :");
try {
in = new StructTextReader<>(Files.newBufferedReader(Paths.get(url.toURI())),
FieldsListChamps1.class);
list = new ArrayList<>();
no = 1;
while ((line = in.readLn()) != null) {
assertTrue(no <= tab.length);
assertEquals(tab[no - 1], line.getLine());
list.add(line);
avanceNewLine(in);
no++;
}
assertEquals(3, list.size(), "Error in line " + no);
} finally {
if (in != null)
in.close();
}
}
@Test
@EnabledOnOs({OS.WINDOWS})
@DisabledOnOs(OS.LINUX)
public void testReadLine3Windows() throws URISyntaxException,
IOException, ParseException {
testReadLinue3("Invalid Size (12!=48)");
}
@Test
@EnabledOnOs({OS.LINUX})
@DisabledOnOs(OS.WINDOWS)
public void testReadLine3Linux() throws URISyntaxException,
IOException, ParseException {
testReadLinue3("Invalid Size (10!=48)");
}
private void testReadLinue3(String message) throws URISyntaxException, IOException, ParseException {
File f;
URL url = getClass().getResource("/data/exemple3.txt");
LineContentText<FieldsListChamps1> line;
String[] tab = {"Newton2 Isaac 04011643"};
assertNotNull(url);
f = new File(url.toURI());
System.out.println("Lecture du fichier " + f.getPath() + " :");
try (StructTextReader<FieldsListChamps1> in = new StructTextReader<>(Files.newBufferedReader(Paths.get(url.toURI())),
FieldsListChamps1.class)) {
line = in.readLn();
assertEquals(tab[0], line.getLine());
ParseException exception = assertThrows(ParseException.class, in::readLn);
// Pour gérer le code sous linux et windows
assertEquals(message, exception.getMessage());
}
}
private void avanceNewLine(Reader reader) throws IOException {
int c = reader.read();
if (c == '\r') {
c = reader.read();
if (c == '\n') {
// cas normal
} else {
fail("Caractere invalide : '" + c + "'");
}
} else if (c == '\n') {
// cas normal
} else {
fail("Caractere invalide : '" + c + "'");
}
}
@Nested
class TestConstucteur {
@Test
void test1() {
// arrange
StringReader in = new StringReader("abc");
// act
StructTextReader<FieldsListChamps1> str = new StructTextReader<>(in, FieldsListChamps1.class);
// assert
assertNotNull(str.getFieldsList());
assertEquals(3, str.getFieldsList().size());
assertTrue(str.getFieldsList().contains(FieldsListChamps1.Nom));
assertTrue(str.getFieldsList().contains(FieldsListChamps1.Prenom));
assertTrue(str.getFieldsList().contains(FieldsListChamps1.DateNaissance));
}
@Test
void test2() {
// arrange
StringReader in = new StringReader("abc");
// act
StructTextReader<FieldsListChamps1> str = new StructTextReader<>(in, Tools.convClassEnum(FieldsListChamps1.class));
// assert
assertNotNull(str.getFieldsList());
assertEquals(3, str.getFieldsList().size());
assertTrue(str.getFieldsList().contains(FieldsListChamps1.Nom));
assertTrue(str.getFieldsList().contains(FieldsListChamps1.Prenom));
assertTrue(str.getFieldsList().contains(FieldsListChamps1.DateNaissance));
}
@Test
void test3() {
// arrange
StringReader in = new StringReader("abc");
// act
StructTextReader<FieldsListChamps1> str = new StructTextReader<>(in, FieldsListChamps1.class, 20);
// assert
assertNotNull(str.getFieldsList());
assertEquals(3, str.getFieldsList().size());
assertTrue(str.getFieldsList().contains(FieldsListChamps1.Nom));
assertTrue(str.getFieldsList().contains(FieldsListChamps1.Prenom));
assertTrue(str.getFieldsList().contains(FieldsListChamps1.DateNaissance));
}
@Test
void test4() {
// arrange
StringReader in = new StringReader("abc");
// act
StructTextReader<FieldsListChamps1> str = new StructTextReader<>(in, Tools.convClassEnum(FieldsListChamps1.class), 30);
// assert
assertNotNull(str.getFieldsList());
assertEquals(3, str.getFieldsList().size());
assertTrue(str.getFieldsList().contains(FieldsListChamps1.Nom));
assertTrue(str.getFieldsList().contains(FieldsListChamps1.Prenom));
assertTrue(str.getFieldsList().contains(FieldsListChamps1.DateNaissance));
}
@Test
void test5() {
// arrange
StringReader in = new StringReader("abc");
// act
assertThrows(IllegalArgumentException.class, () ->
new StructTextReader<>(in, (Class<FieldsListChamps1>) null, 20));
}
@Test
void test6() {
// act
assertThrows(NullPointerException.class, () ->
new StructTextReader<>(null, FieldsListChamps1.class, 20));
}
@Test
void test7() {
// arrange
StringReader in = new StringReader("abc");
// act
assertThrows(IllegalArgumentException.class, () ->
new StructTextReader<>(in, FieldsListChamps1.class, -10));
}
@Test
void test8() {
// arrange
StringReader in = new StringReader("abc");
// act
assertThrows(IllegalArgumentException.class, () ->
new StructTextReader<>(in, FieldsListChamps1.class, 0));
}
@Test
void test9() {
// arrange
StringReader in = new StringReader("abc");
// act
assertThrows(IllegalArgumentException.class, () ->
new StructTextReader<>(in, (List<FieldsListChamps1>) null, 20));
}
@Test
void test10() {
// act
assertThrows(NullPointerException.class, () ->
new StructTextReader<>(null, Tools.convClassEnum(FieldsListChamps1.class), 20));
}
@Test
void test11() {
// arrange
StringReader in = new StringReader("abc");
// act
assertThrows(IllegalArgumentException.class, () ->
new StructTextReader<>(in, Tools.convClassEnum(FieldsListChamps1.class), -10));
}
@Test
void test12() {
// arrange
StringReader in = new StringReader("abc");
// act
assertThrows(IllegalArgumentException.class, () ->
new StructTextReader<>(in, Tools.convClassEnum(FieldsListChamps1.class), 0));
}
}
@Nested
class TestReadLn {
@Test
void test1() throws Exception {
String s = "Newton2 Isaac 04011643";
StringReader str = new StringReader(s);
try (StructTextReader<FieldsListChamps1> in = new StructTextReader<>(str,
FieldsListChamps1.class)) {
// act
LineContentText<FieldsListChamps1> line = in.readLn();
// assert
assertNotNull(line);
assertEquals(s, line.getLine());
assertEquals(-1, str.read());
}
}
@Test
void test2() throws Exception {
String s1 = "Newton2 Isaac 04011643";
String s2 = "Einstein Albert 14103879";
String s3 = "Copernic Nicolas 19021473";
String s = s1 + "\n" + s2 + "\n" + s3 + "\n";
StringReader str = new StringReader(s);
try (StructTextReader<FieldsListChamps1> in = new StructTextReader<>(str,
FieldsListChamps1.class)) {
// act
LineContentText<FieldsListChamps1> line = in.readLn();
// assert
assertNotNull(line);
assertEquals(s1, line.getLine());
int c = in.read();
assertEquals('\n', c);
LineContentText<FieldsListChamps1> line2 = in.readLn();
assertNotNull(line2);
assertEquals(s2, line2.getLine());
c = in.read();
assertEquals('\n', c);
LineContentText<FieldsListChamps1> line3 = in.readLn();
assertNotNull(line3);
assertEquals(s3, line3.getLine());
c = in.read();
assertEquals('\n', c);
assertEquals(-1, str.read());
}
}
@Test
void test3() throws Exception {
String s1 = "Newton2 Isaac 04011643";
String s2 = "Einstein Albert 14103879";
String s3 = "Copernic Nicolas 19021473";
String s = s1 + s2 + s3;
StringReader str = new StringReader(s);
try (StructTextReader<FieldsListChamps1> in = new StructTextReader<>(str,
FieldsListChamps1.class)) {
// act
LineContentText<FieldsListChamps1> line = in.readLn();
// assert
assertNotNull(line);
assertEquals(s1, line.getLine());
LineContentText<FieldsListChamps1> line2 = in.readLn();
assertNotNull(line2);
assertEquals(s2, line2.getLine());
LineContentText<FieldsListChamps1> line3 = in.readLn();
assertNotNull(line3);
assertEquals(s3, line3.getLine());
assertEquals(-1, str.read());
}
}
@Test
void test4() throws Exception {
String s1 = "Newton2 Isaac 04011643";
String s2 = "Einstein Albert 14103879";
String s3 = "Copernic Nicolas 19021473";
String s = s1 + "\r\n" + s2 + "\r\n" + s3 + "\r\n";
StringReader str = new StringReader(s);
try (StructTextReader<FieldsListChamps1> in = new StructTextReader<>(str,
FieldsListChamps1.class)) {
// act
LineContentText<FieldsListChamps1> line = in.readLn();
// assert
assertNotNull(line);
assertEquals(s1, line.getLine());
assertEquals('\r', in.read());
assertEquals('\n', in.read());
LineContentText<FieldsListChamps1> line2 = in.readLn();
assertNotNull(line2);
assertEquals(s2, line2.getLine());
assertEquals('\r', in.read());
assertEquals('\n', in.read());
LineContentText<FieldsListChamps1> line3 = in.readLn();
assertNotNull(line3);
assertEquals(s3, line3.getLine());
assertEquals('\r', in.read());
assertEquals('\n', in.read());
assertEquals(-1, str.read());
}
}
@Test
void test5() throws Exception {
String s1 = "Newton2 Isaac 04011643";
String s2 = "Einstein Albert 14103879";
String s3 = "Copernic Nicolas 19021473";
String s = s1 + "\r" + s2 + "\r" + s3 + "\r";
StringReader str = new StringReader(s);
try (StructTextReader<FieldsListChamps1> in = new StructTextReader<>(str,
FieldsListChamps1.class)) {
// act
LineContentText<FieldsListChamps1> line = in.readLn();
// assert
assertNotNull(line);
assertEquals(s1, line.getLine());
assertEquals('\r', in.read());
LineContentText<FieldsListChamps1> line2 = in.readLn();
assertNotNull(line2);
assertEquals(s2, line2.getLine());
assertEquals('\r', in.read());
LineContentText<FieldsListChamps1> line3 = in.readLn();
assertNotNull(line3);
assertEquals(s3, line3.getLine());
assertEquals('\r', in.read());
assertEquals(-1, str.read());
}
}
}
}
| 35.416851 | 131 | 0.530708 |
e5c184d3e82e3bafc13d603a1fc75daa7a7f7788 | 815 | package pages.ebay;
import components.control.ButtonControl;
import components.control.SelectControl;
import org.openqa.selenium.WebDriver;
import pages.EbayPage;
public class ProductInformationView extends EbayPage {
private SelectControl selectControl;
private ButtonControl buttonControl;
public ProductInformationView(WebDriver webDriver) {
super(webDriver);
webDriver.switchTo().defaultContent();
}
public boolean productInformationPageCorrectlyDisplayed() {
selectControl = new SelectControl(webDriver, "//div[@id='LeftSummaryPanel']");
return selectControl.isControlExist();
}
public void clickOnDescriptionTab() {
buttonControl = new ButtonControl(webDriver, "//a[@aria-controls='desc_panel']");
buttonControl.click();
}
} | 31.346154 | 89 | 0.734969 |
0d0b4b6d521e0b0360427be3d69c47e815aaee5f | 21,301 | package com.compomics.peptizer.gui.component;
import com.compomics.peptizer.MatConfig;
import com.compomics.peptizer.gui.Mediator;
import com.compomics.peptizer.gui.dialog.SaveValidationDialog;
import com.compomics.peptizer.gui.interfaces.SaveValidationPanel;
import com.compomics.peptizer.gui.model.AbstractTableRow;
import com.compomics.peptizer.gui.progressbars.DefaultProgressBar;
import com.compomics.peptizer.interfaces.ValidationSaver;
import com.compomics.peptizer.util.enumerator.TempFileEnum;
import com.compomics.peptizer.util.fileio.FileManager;
import com.compomics.peptizer.util.fileio.TempManager;
import com.compomics.peptizer.util.fileio.ValidationSaveToCSV;
import org.apache.log4j.Logger;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by IntelliJ IDEA.
* User: kenny
* Date: 12-jul-2007
* Time: 22:35:59
*/
/**
* Class description:
* ------------------
* This class was developed to
*/
public class SaveValidationPanel_CSV extends JPanel implements SaveValidationPanel {
// Class specific log4j logger for SaveValidationPanel_CSV instances.
private static Logger logger = Logger.getLogger(SaveValidationPanel_CSV.class);
/**
* The Singleton instance of this Panel.
*/
private static SaveValidationPanel_CSV iSingleton = null;
/**
* The static instance of the parent SaveValidationDialog.
*/
private static SaveValidationDialog iDialog;
/**
* The HashMap couples the TableRow ID's with a boolean corresponding if they will be used in the csv output.
* Keys: AbstractTableRows
* Values: Boolean (csv output inclusive - True or False)
*/
private static HashMap iTableRows = null;
/**
* The Mediator used by the Model.
*/
private static Mediator iMediator = null;
private JTextField txtCSV = null;
private JButton btnCSV = null;
private JCheckBox chkComment = null;
private static JCheckBox chkConfident = null;
private static JCheckBox chkNonConfident = null;
private JCheckBox chkNonPrimary = null;
private static JTable iTable = null;
private File iCSV = null;
private ValidationSaveToCSV iValidationSaver;
/**
* Returns the Singleton instance of SaveValidationPanel_CSV.
*
* @param aDialog
*/
private SaveValidationPanel_CSV(SaveValidationDialog aDialog) {
// Super constructor.
super();
// Set the super dialog.
iDialog = aDialog;
// Make sure the Table is using the correct Mediator.
// If the combobox changes it's selection, make sure necesairy actions are performed!
ActionListener listener = new MyActionListener();
iDialog.addComboBoxListener(listener);
// Get Selected Mediator.
iMediator = iDialog.getSelectedMediator();
// Construct JPanel
construct();
// Try to load parameters.
String s = null;
if ((s = MatConfig.getInstance().getGeneralProperty("SAVEVALIDATION_CSV")) != null) {
setCSV(new File(s));
}
}
/**
* {@inheritDoc}
*/
public static SaveValidationPanel_CSV getInstance(SaveValidationDialog aDialog) {
if (iSingleton == null) {
iSingleton = new SaveValidationPanel_CSV(aDialog);
} else {
// Bizar singleton construction, i know. :)
// This singleton panel must maintain a coupling to the JDialog to follow the Mediator Combobox.
// If a Save dialog is launched a second time, this Panel has a pointer to the old JDialog.
// Therefor, fetch the ActionListener on the ComboBox from the Old Dialog, and place them on the new Dialog & reset the Mediator.
ActionListener[] lActionListeners = iDialog.getComboBoxListeners();
for (ActionListener lActionListener : lActionListeners) {
if (lActionListener instanceof MyActionListener) {
aDialog.addComboBoxListener(lActionListener);
}
}
iDialog = aDialog;
iMediator = iDialog.getSelectedMediator();
rebuildOutput();
}
return iSingleton;
}
/**
* Construct this SaveValidationPanel_CSV instance.
*/
private void construct() {
// Layout
BoxLayout lBoxLayout = new BoxLayout(this, BoxLayout.LINE_AXIS);
this.setLayout(lBoxLayout);
this.setToolTipText("Select a target to save the validation.");
// Components initiation
// JTextField
txtCSV = new JTextField();
txtCSV.setFont(txtCSV.getFont().deriveFont(11.0F));
txtCSV.setBorder(BorderFactory.createEmptyBorder());
txtCSV.setEditable(false);
txtCSV.setText("/");
// JButton
btnCSV = new JButton();
btnCSV.setText("Browse");
btnCSV.setMnemonic(KeyEvent.VK_B);
btnCSV.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
csvSelection();
}
});
// Checkbox to include non-confident peptideidentifciations.
chkComment = new JCheckBox("Include validation comments");
chkComment.setSelected(true);
// Checkbox to include confident not-matched peptideidentifciations.
chkConfident = new JCheckBox("Include confident identifications that did not match the profile");
chkConfident.setSelected(false);
chkConfident.setEnabled(false);
// Checkbox to include non-confident peptideidentifciations.
chkNonConfident = new JCheckBox("Include non confident identifications");
chkNonConfident.setSelected(false);
chkNonConfident.setEnabled(false);
// Checkbox to include non primary rank confident hits
chkNonPrimary = new JCheckBox("Include non primary ranked hits");
chkNonPrimary.setSelected(false);
updateSelectionBox();
// Table.
iTable = new JTable();
iTable.setModel(new CSVOutputTableModel());
iTable.setRowHeight(20);
iTable.setCellSelectionEnabled(false);
iTable.setRowSelectionAllowed(true);
iTable.setColumnSelectionAllowed(false);
// This enable's the JScrollpane again for some reason!
iTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
iTable.setDefaultRenderer(String.class, new CSVOutputTableCellRenderer());
// Put target on the Top panel.
JPanel jpanMiddle = new JPanel();
jpanMiddle.setLayout(new BoxLayout(jpanMiddle, BoxLayout.PAGE_AXIS));
jpanMiddle.add(chkComment);
jpanMiddle.add(Box.createHorizontalStrut(10));
jpanMiddle.add(chkConfident);
jpanMiddle.add(Box.createHorizontalStrut(10));
jpanMiddle.add(chkNonConfident);
jpanMiddle.add(Box.createHorizontalStrut(10));
jpanMiddle.add(chkNonPrimary);
jpanMiddle.add(Box.createHorizontalGlue());
jpanMiddle.setBorder(BorderFactory.createTitledBorder("Options"));
// Put target on the Top panel.
JPanel jpanBottom = new JPanel();
jpanBottom.setLayout(new BoxLayout(jpanBottom, BoxLayout.LINE_AXIS));
jpanBottom.add(txtCSV);
jpanBottom.add(Box.createHorizontalStrut(10));
jpanBottom.add(btnCSV);
jpanBottom.add(Box.createHorizontalGlue());
jpanBottom.setBorder(BorderFactory.createTitledBorder("Target"));
JScrollPane scroll1 = new JScrollPane(iTable);
scroll1.setBorder(BorderFactory.createTitledBorder("Content"));
JPanel jpanMain = new JPanel();
jpanMain.setLayout(new BoxLayout(jpanMain, BoxLayout.PAGE_AXIS));
jpanMain.add(scroll1);
jpanMain.add(Box.createRigidArea(new Dimension(iTable.getSize().width, 20)));
jpanMain.add(jpanMiddle);
jpanMain.add(Box.createRigidArea(new Dimension(iTable.getSize().width, 20)));
jpanMain.add(jpanBottom);
this.add(jpanMain);
this.validate();
}
/**
* Select CSV file.
*/
private void csvSelection() {
if (FileManager.getInstance().selectTXTOutput(this)) {
iCSV = (FileManager.getInstance().getTXTOutput());
try {
txtCSV.setText(iCSV.getCanonicalPath());
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
/**
* Returns an instance to save selected identifications and validation.
*
* @return ValidationSaver to save validation of selected identifications.
*/
public ValidationSaver getNewValidationSaver() {
if (iCSV != null) {
ArrayList lOutputRows = new ArrayList();
for (Object o : iTableRows.keySet()) {
AbstractTableRow row = (AbstractTableRow) o;
if ((Boolean) iTableRows.get(row)) {
lOutputRows.add(row);
}
}
DefaultProgressBar lProgress = new DefaultProgressBar((JFrame) SwingUtilities.getRoot(iMediator), "Writing csv results file into " + iCSV + " .", 0, 1);
iValidationSaver = new ValidationSaveToCSV(iCSV, lOutputRows, lProgress);
if (iValidationSaver instanceof ValidationSaveToCSV) {
((ValidationSaveToCSV) iValidationSaver).setComments(chkComment.isSelected());
}
iValidationSaver.setIncludeConfidentNotSelected(chkConfident.isSelected());
iValidationSaver.setIncludeNonConfident(chkNonConfident.isSelected());
iValidationSaver.setIncludeNonPrimary(chkNonPrimary.isSelected());
return getActiveValidationSaver();
} else {
JOptionPane.showMessageDialog(this.getParent(), "A csv file must be selected first!!", "Validation saver to CSV failed..", JOptionPane.ERROR_MESSAGE);
return null;
}
}
/**
* Get the CSV validationSaver of the Current panel. Use the getNewValidationSaver() for a new Build.
*
* @return
*/
public ValidationSaver getActiveValidationSaver() {
if (iValidationSaver == null) {
iValidationSaver = (ValidationSaveToCSV) getNewValidationSaver();
}
return iValidationSaver;
}
/**
* Set the file we want to save our validation.
*
* @param aCSV File to save our results..
*/
public void setCSV(File aCSV) {
iCSV = aCSV;
try {
txtCSV.setText(iCSV.getCanonicalPath());
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
/**
* String representation of the File Iterator.
*
* @return String representation of the file iterator.
*/
public String toString() {
return "Save to CSV";
}
/**
* If the Mediator changes in selection, the table can change as well. In that case, rebuild the iOutput HashMap.
* Save the properties that were allready set!
*/
private static void rebuildOutput() {
// This will be the new output map.
HashMap lProperties = new HashMap();
int lNumberOfRows = iTable.getRowCount();
for (int i = 0; i < lNumberOfRows; i++) {
// Localise the tablerow.
AbstractTableRow lRow = iMediator.getTableRow(i);
// If the current Map allready contains a boolean for the tablerow, re-use it!
if (iTableRows.get(lRow) != null) {
Boolean aValue = (Boolean) iTableRows.get(lRow);
lProperties.put(lRow, aValue);
} else {
// Else place it's activity status.
lProperties.put(lRow, lRow.isActive());
}
}
// Update the selection boxes.
updateSelectionBox();
// Set the field iTablerows to the reconstructed lProperties.
iTableRows = lProperties;
}
private static void updateSelectionBox() {
TempManager lTempFileManager = TempManager.getInstance();
boolean hasObjectStream_good = lTempFileManager.getNumberOfFiles(iMediator.getSelectedPeptideIdentifications(), TempFileEnum.CONFIDENT_NOT_SELECTED) > 0;
boolean hasObjectStream_bad = lTempFileManager.getNumberOfFiles(iMediator.getSelectedPeptideIdentifications(), TempFileEnum.NON_CONFIDENT) > 0;
if (hasObjectStream_good) {
chkConfident.setEnabled(true);
chkConfident.setSelected(true);
} else {
chkConfident.setEnabled(false);
chkConfident.setSelected(false);
}
if (hasObjectStream_bad) {
chkNonConfident.setEnabled(true);
chkNonConfident.setSelected(false);
} else {
chkNonConfident.setEnabled(false);
chkNonConfident.setSelected(false);
}
}
/**
* The ActionListener is place on the combobox of the parent SaveValidationDialog.
* Whenever it's selection is changed, make sure the Mediator used by the TableModel follows the selection by this Listener!
*/
private class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
iMediator = iDialog.getSelectedMediator();
rebuildOutput();
iTable.validate();
iTable.updateUI();
iTable.repaint();
}
}
/**
* This TableModel serves a dynamic selection of the CSV output.
* The model accesses a Mediator and finds all visible AbstractTableRows that the user originally could see in the GUI.
* These rows are now listed with a boolean whether to use this row for output or not.
*/
private class CSVOutputTableModel implements TableModel {
/**
* The TableModel for a dynamic CSV output of the Mediator results.
* This Model reflects the Mediator's Table.
*/
public CSVOutputTableModel() {
// Create the output map.
int lNumberOfRows = getRowCount();
iTableRows = new HashMap();
for (int i = 0; i < lNumberOfRows; i++) {
Object aKey = iMediator.getTableRow(i);
Boolean aValue = iMediator.getTableRow(i).isActive();
iTableRows.put(aKey, aValue);
}
}
/**
* Returns the number of rows in the model. A
* <code>JTable</code> uses this method to determine how many rows it
* should display. This method should be quick, as it
* is called frequently during rendering.
*
* @return the number of rows in the model
* @see #getColumnCount
*/
public int getRowCount() {
return iMediator.getNumberOfVisibleTableRows();
}
/**
* Returns the number of columns in the model. A
* <code>JTable</code> uses this method to determine how many columns it
* should create and display by default.
*
* @return the number of columns in the model
* @see #getRowCount
*/
public int getColumnCount() {
return 2;
}
/**
* Returns the name of the column at <code>columnIndex</code>. This is used
* to initialize the table's column header name. Note: this name does
* not need to be unique; two columns in a table can have the same name.
*
* @param columnIndex the index of the column
* @return the name of the column
*/
public String getColumnName(int columnIndex) {
if (columnIndex == 0) {
return "Property";
} else if (columnIndex == 1) {
return "Output";
} else {
return "NA!";
}
}
/**
* Returns the most specific superclass for all the cell values
* in the column. This is used by the <code>JTable</code> to set up a
* default renderer and editor for the column.
*
* @param columnIndex the index of the column
* @return the common ancestor class of the object values in the model.
*/
public Class<?> getColumnClass(int columnIndex) {
Class c = null;
try {
c = getValueAt(0, columnIndex).getClass();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return c;
}
/**
* Returns true if the cell at <code>rowIndex</code> and
* <code>columnIndex</code>
* is editable. Otherwise, <code>setValueAt</code> on the cell will not
* change the value of that cell.
*
* @param rowIndex the row whose value to be queried
* @param columnIndex the column whose value to be queried
* @return true if the cell is editable
* @see #setValueAt
*/
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return false;
} else {
return true;
}
}
/**
* Returns the value for the cell at <code>columnIndex</code> and
* <code>rowIndex</code>.
*
* @param rowIndex the row whose value is to be queried
* @param columnIndex the column whose value is to be queried
* @return the value Object at the specified cell
*/
public Object getValueAt(int rowIndex, int columnIndex) {
Object o = null;
AbstractTableRow row = iMediator.getTableRow(rowIndex);
if (columnIndex == 0) {
o = row.getName();
} else if (columnIndex == 1) {
o = iTableRows.get(row);
}
return o;
}
/**
* Sets the value in the cell at <code>columnIndex</code> and
* <code>rowIndex</code> to <code>aValue</code>.
*
* @param aValue the new value
* @param rowIndex the row whose value is to be changed
* @param columnIndex the column whose value is to be changed
* @see #getValueAt
* @see #isCellEditable
*/
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// Activity column,
if (columnIndex == 1) {
// Set the value (Boolean for column 1) to iTableRows.
iTableRows.put(iMediator.getTableRow(rowIndex), aValue);
}
}
/**
* Adds a listener to the list that is notified each time a change
* to the data model occurs.
*
* @param l the TableModelListener
*/
public void addTableModelListener(TableModelListener l) {
// No implementation.
}
/**
* Removes a listener from the list that is notified each time a
* change to the data model occurs.
*
* @param l the TableModelListener
*/
public void removeTableModelListener(TableModelListener l) {
// No implementation.
}
}
/**
* This CellRenderer serves padding for the Table.
*/
private class CSVOutputTableCellRenderer extends DefaultTableCellRenderer {
/**
* JLabel used for rendering.
*/
JLabel lbl = null;
/**
* Empty constructor.
* The renderer makes overall use of the DefaultTableCellRenderer plus setting an empty padding border.
*/
public CSVOutputTableCellRenderer() {
super();
}
// implements javax.swing.table.TableCellRenderer
/**
* Returns the default table cell renderer.
*
* @param table the <code>JTable</code>
* @param value the value to assign to the cell at
* <code>[row, column]</code>
* @param isSelected true if cell is selected
* @param hasFocus true if cell has focus
* @param row the row of the cell to render
* @param column the column of the cell to render
* @return the default table cell renderer
*/
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
// set padding - you should provide caching of compound
// borders and Insets instance for performace reasons...
lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
lbl.setBorder(new CompoundBorder(new EmptyBorder(new Insets(1, 4, 1, 4)), lbl.getBorder()));
return lbl;
}
}
}
| 36.22619 | 164 | 0.619126 |
30109e4289e15ad4242fad24520f68f84590f284 | 3,471 | /*************************************************************************
* *
* EJBCA Community: The OpenSource Certificate Authority *
* *
* This software 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 any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.ejbca.ui.web.admin.services.servicetypes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import org.ejbca.core.model.services.IInterval;
import org.ejbca.ui.web.admin.CustomLoader;
/**
* Class used to populate the fields in the custominterval.jsp subview page.
*
*
* @version $Id: CustomIntervalType.java 28844 2018-05-04 08:31:02Z samuellb $
*/
public class CustomIntervalType extends IntervalType {
private static final long serialVersionUID = -8378607303311336382L;
public static final String NAME = "CUSTOMINTERVAL";
public CustomIntervalType() {
super("custominterval.jsp", NAME, true);
}
private String autoClassPath;
private String manualClassPath;
private String propertyText;
/**
* @return the propertyText
*/
public String getPropertyText() {
return propertyText;
}
/**
* @param propertyText the propertyText to set
*/
public void setPropertyText(String propertyText) {
this.propertyText = propertyText;
}
/**
* Sets the class path, and detects if it is an auto-detected class
* or a manually specified class.
*/
public void setClassPath(String classPath) {
if (CustomLoader.isDisplayedInList(classPath, IInterval.class)) {
autoClassPath = classPath;
manualClassPath = "";
} else {
autoClassPath = "";
manualClassPath = classPath;
}
}
@Override
public String getClassPath() {
return autoClassPath != null && !autoClassPath.isEmpty() ? autoClassPath : manualClassPath;
}
public void setAutoClassPath(String classPath) {
autoClassPath = classPath;
}
public String getAutoClassPath() {
return autoClassPath;
}
public void setManualClassPath(String classPath) {
manualClassPath = classPath;
}
public String getManualClassPath() {
return manualClassPath;
}
@Override
public Properties getProperties(ArrayList<String> errorMessages) throws IOException{
Properties retval = new Properties();
retval.load(new ByteArrayInputStream(getPropertyText().getBytes()));
return retval;
}
@Override
public void setProperties(Properties properties) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
properties.store(baos, null);
setPropertyText(new String(baos.toByteArray()));
}
@Override
public boolean isCustom() {
return true;
}
}
| 30.716814 | 99 | 0.594353 |
75617c650aeaa65564eba3a8fd872f97f0784c10 | 1,019 | package com.example.android.sunshine.app.wear;
import android.util.Log;
import com.example.android.sunshine.app.sync.SunshineSyncAdapter;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.WearableListenerService;
public class SunshineWearableListenerService extends WearableListenerService {
private static final String TAG = SunshineWearableListenerService.class.getSimpleName();
// Wear.
private static final String WEATHER_INFO_REQUEST = "/weather-info-request";
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.d(TAG, "Data is changed");
for (DataEvent dataEvent : dataEvents) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
String path = dataEvent.getDataItem().getUri().getPath();
Log.i(TAG, "Path: " + path);
if (path.equals(WEATHER_INFO_REQUEST)) {
SunshineSyncAdapter.syncImmediately(this);
}
}
}
}
}
| 30.878788 | 90 | 0.736016 |
5e3fad1b9b61411a5cf2202ce286444900831326 | 1,681 | package easy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Renat Kaitmazov
*/
public final class ArraysIntersection {
public int[] intersect(int[] nums1, int[] nums2) {
final int size1 = nums1.length;
final int size2 = nums2.length;
final int[] smaller = size1 < size2 ? nums1 : nums2;
final int[] bigger = nums1 == smaller ? nums2 : nums1;
final int smallerSize = size1 < size2 ? size1 : size2;
final Map<Integer, Integer> counter = new HashMap<>(smallerSize);
for (int i = 0; i < smallerSize; ++i) {
final int key = smaller[i];
final Integer count = counter.get(key);
if (count == null) {
counter.put(key, 1);
} else {
counter.put(key, count + 1);
}
}
final int biggerSize = smallerSize == size1 ? size2 : size1;
final List<Integer> intersection = new ArrayList<>();
for (int i = 0; i < biggerSize; ++i) {
final int key = bigger[i];
final Integer count = counter.get(key);
if (count == null) {
continue;
}
intersection.add(key);
if (count == 1) {
counter.remove(key);
} else {
counter.put(key, count - 1);
}
}
final int intersectionSize = intersection.size();
final int[] newArray = new int[intersectionSize];
for (int i = 0; i < intersectionSize; ++i) {
newArray[i] = intersection.get(i);
}
return newArray;
}
}
| 31.716981 | 73 | 0.525283 |
75e0a6d07e29fc767605cd91e8c140beb38064e2 | 5,171 | /*
* Copyright 2013-2020 The OpenZipkin 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 brave.rpc;
import brave.Span;
import brave.SpanCustomizer;
import brave.Tracer;
import brave.internal.Nullable;
import brave.propagation.TraceContext;
import brave.propagation.TraceContext.Injector;
import brave.sampler.SamplerFunction;
/**
* This standardizes a way to instrument RPC clients, particularly in a way that encourages use of
* portable customizations via {@link RpcRequestParser} and {@link RpcResponseParser}.
*
* <p>Synchronous interception is the most straight forward instrumentation.
*
* <p>You generally need to:
* <ol>
* <li>Start the span and add trace headers to the request</li>
* <li>Put the span in scope so things like log integration works</li>
* <li>Invoke the request</li>
* <li>If there was a Throwable, add it to the span</li>
* <li>Complete the span</li>
* </ol>
*
* <pre>{@code
* RpcClientRequestWrapper requestWrapper = new RpcClientRequestWrapper(request);
* Span span = handler.handleSend(requestWrapper); // 1.
* ClientResponse response = null;
* Throwable error = null;
* try (Scope ws = currentTraceContext.newScope(span.context())) { // 2.
* return response = invoke(request); // 3.
* } catch (Throwable e) {
* error = e; // 4.
* throw e;
* } finally {
* RpcClientResponseWrapper responseWrapper =
* new RpcClientResponseWrapper(requestWrapper, response, error);
* handler.handleReceive(responseWrapper, span); // 5.
* }
* }</pre>
*
* @since 5.12
*/
public final class RpcClientHandler extends RpcHandler<RpcClientRequest, RpcClientResponse> {
/** @since 5.12 */
public static RpcClientHandler create(RpcTracing rpcTracing) {
if (rpcTracing == null) throw new NullPointerException("rpcTracing == null");
return new RpcClientHandler(rpcTracing);
}
final Tracer tracer;
final SamplerFunction<RpcRequest> sampler;
final Injector<RpcClientRequest> injector;
RpcClientHandler(RpcTracing rpcTracing) {
super(rpcTracing.clientRequestParser(), rpcTracing.clientResponseParser());
this.tracer = rpcTracing.tracing().tracer();
this.injector = rpcTracing.propagation().injector(RpcClientRequest.SETTER);
this.sampler = rpcTracing.clientSampler();
}
/**
* Starts the client span after assigning it a name and tags. This {@link
* Injector#inject(TraceContext, Object) injects} the trace context onto the request before
* returning.
*
* <p>Call this before sending the request on the wire.
*
* @see #handleSendWithParent(RpcClientRequest, TraceContext)
* @see RpcTracing#clientSampler()
* @see RpcTracing#clientRequestParser()
* @since 5.12
*/
public Span handleSend(RpcClientRequest request) {
if (request == null) throw new NullPointerException("request == null");
return handleSend(request, tracer.nextSpan(sampler, request));
}
/**
* Like {@link #handleSend(RpcClientRequest)}, except explicitly controls the parent of the client
* span.
*
* @param parent the parent of the client span representing this request, or null for a new
* trace.
* @see Tracer#nextSpanWithParent(SamplerFunction, Object, TraceContext)
* @since 5.12
*/
public Span handleSendWithParent(RpcClientRequest request, @Nullable TraceContext parent) {
if (request == null) throw new NullPointerException("request == null");
return handleSend(request, tracer.nextSpanWithParent(sampler, request, parent));
}
/**
* Like {@link #handleSend(RpcClientRequest)}, except explicitly controls the span representing
* the request.
*
* @since 5.12
*/
public Span handleSend(RpcClientRequest request, Span span) {
if (request == null) throw new NullPointerException("request == null");
if (span == null) throw new NullPointerException("span == null");
injector.inject(span.context(), request);
return handleStart(request, span);
}
/**
* Finishes the client span after assigning it tags according to the response or error.
*
* <p>This is typically called once the response headers are received, and after the span is
* {@link Tracer.SpanInScope#close() no longer in scope}.
*
* <p><em>Note</em>: It is valid to have a {@link RpcClientResponse} that only includes an
* {@linkplain RpcClientResponse#error() error}. However, it is better to also include the
* {@linkplain RpcClientResponse#request() request}.
*
* @see RpcResponseParser#parse(RpcResponse, TraceContext, SpanCustomizer)
* @since 5.12
*/
public void handleReceive(RpcClientResponse response, Span span) {
handleFinish(response, span);
}
}
| 37.744526 | 100 | 0.71959 |
7204ec09f77a3fa812a19475a1cf0e1c37cec74d | 197 | package com.javacp;
public class ClassSuffix {
class Inner<A> {
class Bar {
class Fuz<B> {}
}
}
public ClassSuffix.Inner<String>.Bar.Fuz<Integer> suffix;
}
| 17.909091 | 61 | 0.573604 |
15492de1062496807c83e49fd1f8f1332d655fee | 1,343 | package com.craigrueda.gateway.core.handler.error;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
/**
* Created by Craig Rueda
*
* Gives a concrete class to reference in configuration rather than depending on the various instances
* created in other framework configs...
*
*/
public class GatewayWebExceptionHandler extends DefaultErrorWebExceptionHandler {
/**
* Create a new {@code GatewayWebExceptionHandler} instance.
*
* @param errorAttributes the error attributes
* @param resourceProperties the resources configuration properties
* @param errorProperties the error configuration properties
* @param applicationContext the current application context
*/
public GatewayWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
ErrorProperties errorProperties, ApplicationContext applicationContext) {
super(errorAttributes, resourceProperties, errorProperties, applicationContext);
}
}
| 44.766667 | 111 | 0.781832 |
b970b59e61d300a268cbbafeea4bbfa93c6a8fb7 | 416 | package fi.joniaromaa.parinacorelibrary.api.storage.module;
import javax.annotation.Nonnull;
import fi.joniaromaa.parinacorelibrary.api.storage.Storage;
public abstract class StorageModuleAdapter<T extends StorageModule, U extends Storage>
{
private U storage;
public StorageModuleAdapter(@Nonnull U storage)
{
this.storage = storage;
}
protected @Nonnull U getStorage()
{
return this.storage;
}
}
| 19.809524 | 86 | 0.78125 |
2ffec4ea003806e08381e3fddec10e0badbe7227 | 2,332 | package news.androidtv.subchannel.activities;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.android.media.tv.companionlibrary.model.InternalProviderData;
import com.google.android.media.tv.companionlibrary.model.Program;
import news.androidtv.subchannel.R;
import news.androidtv.subchannel.services.TifPlaybackService;
/**
* Created by Nick on 4/29/2017.
*/
public class ProgramInfoActivity extends Activity {
public static final String EXTRA_TIMEOUT = "timeout";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program_info);
Program p = TifPlaybackService.mCurrentProgram;
try {
((TextView) findViewById(R.id.info_title)).setText(
p.getInternalProviderData().get(TifPlaybackService.IPD_KEY_POST_TITLE).toString());
((TextView) findViewById(R.id.info_submitted)).setText(
p.getInternalProviderData().get(TifPlaybackService.IPD_KEY_POST_BY).toString());
} catch (InternalProviderData.ParseException e) {
e.printStackTrace();
}
// Display info about this program into layout.
// Setup automated timeout
if (getIntent() != null && getIntent().hasExtra(EXTRA_TIMEOUT)) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, getIntent().getIntExtra(EXTRA_TIMEOUT, Integer.MAX_VALUE));
}
// Turn into side-panel
// Sets the size and position of dialog activity.
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.height = getResources().getDimensionPixelSize(R.dimen.side_panel_height);
getWindow().setAttributes(layoutParams);
}
}
| 37.015873 | 103 | 0.69554 |
a06f61a03f9f5cf7ef1644cc3eaeed5c17ee155e | 3,547 | /*
* Copyright (C) 2016 Adam Huang <poisondog@gmail.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 poisondog.vfs.http;
import java.io.FileNotFoundException;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import poisondog.net.http.HttpGet;
import poisondog.net.http.HttpHead;
import poisondog.net.http.HttpParameter;
import poisondog.net.http.HttpResponse;
import poisondog.vfs.IFile;
/**
* @author Adam Huang
* @since 2016-12-13
*/
public class HttpFileFactoryTest {
private HttpFileFactory mFactory;
private HttpGet mGet;
private HttpHead mHead;
private HttpResponse mGood;
private HttpResponse mNotFound;
@Before
public void setUp() throws Exception {
mFactory = new HttpFileFactory();
mGet = Mockito.spy(new HttpGet());
mHead = Mockito.spy(new HttpHead());
HttpResponse response = new HttpResponse(200);
response.setContent("Hello".getBytes());
mGood = Mockito.spy(response);
mNotFound = Mockito.spy(new HttpResponse(404));
mFactory.setGet(mGet);
mFactory.setHead(mHead);
}
@Test
public void testExists() throws Exception {
Mockito.when(mHead.execute(Mockito.any(HttpParameter.class))).thenReturn(mGood);
Assert.assertTrue(mFactory.exists("http://google.com"));
Mockito.when(mHead.execute(Mockito.any(HttpParameter.class))).thenThrow(new FileNotFoundException());
Assert.assertTrue(!mFactory.exists("http://google.com/234.mp4"));
}
@Test
public void testHidden() throws Exception {
Assert.assertTrue(!mFactory.isHidden("http://google.com/folder/"));
Assert.assertTrue(!mFactory.isHidden("http://google.com/234.mp4"));
Assert.assertTrue(mFactory.isHidden("http://google.com/.folder/"));
Assert.assertTrue(mFactory.isHidden("http://google.com/.234.mp4"));
}
@Test
public void testGet() throws Exception {
Mockito.when(mGet.execute(Mockito.any(HttpParameter.class))).thenReturn(mGood);
List<String> result = IOUtils.readLines(mFactory.get("http://google.com"), "utf8");
Assert.assertNotNull(result);
Assert.assertEquals(1, result.size());
Assert.assertEquals("Hello", result.get(0));
// System.out.println("size: " + mFactory.getContentSize("https://dl.dropboxusercontent.com/u/9172363/tmp/demo1.mp4"));
// System.out.println("last: " + mFactory.getLastModifiedTime("https://dl.dropboxusercontent.com/u/9172363/tmp/demo1.mp4"));
}
@Test
public void testInstance() throws Exception {
Mockito.when(mGet.execute(Mockito.any(HttpParameter.class))).thenReturn(mGood);
HttpData result = (HttpData)mFactory.getFile("http://google.com");
Assert.assertEquals("Hello", IOUtils.toString(result.getInputStream(), "utf8"));
}
// @Test
// public void testList() throws Exception {
//// System.out.println(mFactory.list("http://hypem.com/download/"));
// for (IFile file : mFactory.list("http://walton.poisondog.com:8081/nexus/content/repositories/releases/com/walton/cob/")) {
// System.out.println(file.getUrl());
// }
// }
}
| 36.193878 | 126 | 0.740908 |
906a02977d3da9b7955033c8ba2477287bb4eff6 | 5,085 | /*
* 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.pig.impl.util;
import java.util.*;
import org.apache.pig.data.Tuple;
public class LineageTracer {
// Use textbook Union-Find data structure, with counts associated with items
// note: we test for equality by comparing tuple references, not by calling the "equals()" method
// the "IdentityHashMap" data structure is based on reference equality
IdentityHashMap<Tuple, Tuple> parents = new IdentityHashMap<Tuple, Tuple>();
IdentityHashMap<Tuple, Integer> counts = new IdentityHashMap<Tuple, Integer>(); // has one entry per unique tuple being tracked
IdentityHashMap<Tuple, Integer> ranks = new IdentityHashMap<Tuple, Integer>();
// insert a new tuple (if a tuple is inserted multiple times, it gets a count > 1)
public void insert(Tuple t) {
if (parents.containsKey(t)) {
counts.put(t, counts.get(t)+1);
} else {
parents.put(t, t);
counts.put(t, 1);
ranks.put(t, 0);
}
}
// union two tuple sets
public void union(Tuple t1, Tuple t2) {
link(getRepresentative(t1), getRepresentative(t2));
}
// find the set representative of a given tuple
public Tuple getRepresentative(Tuple t) {
Tuple tParent = parents.get(t);
if (tParent != t) {
tParent = getRepresentative(tParent);
parents.put(t, tParent);
}
return tParent;
}
private void link(Tuple t1, Tuple t2) {
int t1Rank = ranks.get(t1);
int t2Rank = ranks.get(t2);
if (t1Rank > t2Rank) {
parents.put(t2, t1);
} else {
parents.put(t1, t2);
if (t1Rank == t2Rank) ranks.put(t2, t2Rank + 1);
}
}
// get the cardinality of each tuple set (identified by a representative tuple)
public IdentityHashMap<Tuple, Integer> getCounts() {
return getWeightedCounts(new IdentityHashSet<Tuple>(), 1);
}
// get the cardinality of each tuple set, weighted in a special way
// weighting works like this: if a tuple set contains one or more tuples from the "specialTuples" set, we multiply its value by "multiplier"
public IdentityHashMap<Tuple, Integer> getWeightedCounts(IdentityHashSet<Tuple> specialTuples, int multiplier) {
IdentityHashMap<Tuple, Integer> repCounts = new IdentityHashMap<Tuple, Integer>();
IdentityHashSet<Tuple> specialSets = new IdentityHashSet<Tuple>();
for (IdentityHashMap.Entry<Tuple, Integer> e : counts.entrySet()) {
Tuple t = e.getKey();
int newCount = counts.get(t);
Tuple rep = getRepresentative(t);
int oldCount = (repCounts.containsKey(rep))? repCounts.get(rep) : 0;
repCounts.put(rep, oldCount + newCount);
if (specialTuples.contains(t)) specialSets.add(rep);
}
for (IdentityHashMap.Entry<Tuple, Integer> e : repCounts.entrySet()) {
if (specialSets.contains(e.getKey())) e.setValue(e.getValue() * multiplier);
}
return repCounts;
}
// get all members of the set containing t
public Collection<Tuple> getMembers(Tuple t) {
Tuple representative = getRepresentative(t);
Collection<Tuple> members = new LinkedList<Tuple>();
for (IdentityHashMap.Entry<Tuple, Integer> e : counts.entrySet()) {
Tuple t1 = e.getKey();
if (getRepresentative(t1) == representative) members.add(t1);
}
return members;
}
// get a mapping from set representatives to members
public IdentityHashMap<Tuple, Collection<Tuple>> getMembershipMap() {
IdentityHashMap<Tuple, Collection<Tuple>> map = new IdentityHashMap<Tuple, Collection<Tuple>>();
for (IdentityHashMap.Entry<Tuple, Integer> e : counts.entrySet()) {
Tuple t = e.getKey();
Tuple representative = getRepresentative(t);
Collection<Tuple> members = map.get(representative);
if (members == null) {
members = new LinkedList<Tuple>();
map.put(representative, members);
}
members.add(t);
}
return map;
}
}
| 39.418605 | 144 | 0.635005 |
8938ba77839dd07a8d1073f7085a9c4b03555dde | 2,116 | package org.ekstep.ep.samza.search.domain;
import java.util.ArrayList;
public class Item implements IObject {
private Integer num_answers;
private String title;
private String name;
private String template;
private String type;
private String owner;
private String status;
private String qlevel;
private ArrayList<String> language;
private ArrayList<String> keywords;
private ArrayList<String> concepts;
private ArrayList<String> gradeLevel;
private boolean cacheHit;
public String title() { return title; }
public Integer num_answers() {
return num_answers;
}
public String name() {
return name;
}
public String template() {
return template;
}
public String type() {
return type;
}
public String status() {
return status;
}
public String owner() {
return owner;
}
public String qlevel() {
return qlevel;
}
public ArrayList<String> language() {
return language;
}
public ArrayList<String> keywords() {
return keywords;
}
public ArrayList<String> concepts() {
return concepts;
}
public ArrayList<String> gradeLevel() {
return gradeLevel;
}
@Override
public boolean getCacheHit() {
return false;
}
@Override
public void setCacheHit(boolean b) {
}
@Override
public String toString() {
return "Item{" +
"num_answers=" + num_answers +
", title='" + title + '\'' +
", name='" + name + '\'' +
", template='" + template + '\'' +
", type='" + type + '\'' +
", owner='" + owner + '\'' +
", status='" + status + '\'' +
", qlevel='" + qlevel + '\'' +
", language=" + language +
", keywords=" + keywords +
", concepts=" + concepts +
", gradeLevel=" + gradeLevel +
", cacheHit=" + cacheHit +
'}';
}
}
| 21.591837 | 50 | 0.523157 |
3f837c284376146896f29069301ee4ce05cb52cb | 11,200 | package ru.mail.polis.kvstorage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import one.nio.http.HttpClient;
import one.nio.http.HttpServer;
import one.nio.http.HttpServerConfig;
import one.nio.http.HttpSession;
import one.nio.http.Path;
import one.nio.http.Request;
import one.nio.http.Response;
import one.nio.net.ConnectionString;
import ru.mail.polis.KVDao;
import ru.mail.polis.KVService;
public class MyService extends HttpServer implements KVService{
public final static String STATUS_ENDPOINT = "/v0/status";
public final static String STORAGE_ENDPOINT = "/v0/entity";
public final static String ID_PARAMETER = "id=";
public final static String REPLICAS_PARAMETER = "replicas=";
public final static String QUERY_FROM_REPLICA = "from-replica";
public final static String UPDATED_VALUE_HEADER = "updated: ";
public final int STATUS_SUCCESS_GET = 200;
public final int STATUS_SUCCESS_PUT = 201;
public final int STATUS_SUCCESS_DELETE = 202;
public final int STATUS_NOT_FOUND = 404;
private final Set<String> topology;
private final List<String> topologyList;
private final Map<String, HttpClient> clients;
private final MyDAO dao;
private final String myHost;
public MyService(HttpServerConfig config, KVDao dao, Set<String> topology) throws IOException{
super(config);
this.topology = topology;
this.topologyList = new ArrayList<>(topology);
this.dao = (MyDAO)dao;
myHost = "http://localhost:" + config.acceptors[0].port;
clients = new HashMap<>();
for (String host : topology){
if (!host.equals(myHost)){
clients.put(host, new HttpClient(new ConnectionString(host)));
}
}
}
@Path(MyService.STATUS_ENDPOINT)
public Response statusEndpoint(Request request){
return Response.ok(Response.EMPTY);
}
@Path(MyService.STORAGE_ENDPOINT)
public Response storageEndpoint(Request request){
try {
switch (request.getMethod()){
case Request.METHOD_GET:
return handleGet(request);
case Request.METHOD_PUT:
return handlePut(request);
case Request.METHOD_DELETE:
return handleDelete(request);
}
} catch (IllegalArgumentException e){
return createBadRequestResponse();
}
return createInternalErrorResponse();
}
@Override
public void handleDefault(Request request, HttpSession session) throws IOException {
session.sendResponse(createBadRequestResponse());
}
private Response handleGet(Request request) throws IllegalArgumentException{
byte[] key = getKey(request);
if (fromReplica(request)){
Response response;
try{
response = new Response(Response.OK, dao.get(key));
} catch (NoSuchElementException e) {
response = createNotFoundResponse();
} catch (IOException e) {
e.printStackTrace();
response = createInternalErrorResponse();
}
long time = dao.getTime(key);
if (time > 0) {
response.addHeader(UPDATED_VALUE_HEADER + time);
}
return response;
} else{
AckFrom ackFrom = new AckFrom(request);
TopologyStrategy.GetTopologyStrategy strategy = new TopologyStrategy.GetTopologyStrategy(ackFrom.ack, ackFrom.from);
for (String host : getHostsForKey(key, ackFrom.from)){
if (host.equals(myHost)) {
try {
strategy.addValue(dao.getTime(key), dao.get(key));
strategy.addSuccess();
} catch (NoSuchElementException e) {
long time = dao.getTime(key);
if (time > 0){
strategy.addDeleted();
} else {
strategy.addNotFound();
}
} catch (IOException e) {
e.printStackTrace();
}
} else{
try {
Response response = clients.get(host).get(request.getURI(), QUERY_FROM_REPLICA);
String timeStr = response.getHeader(UPDATED_VALUE_HEADER);
Long time = null;
if (timeStr != null) {
time = Long.parseLong(timeStr);
}
if (response.getStatus() == STATUS_SUCCESS_GET){
strategy.addSuccess();
strategy.addValue(Long.parseLong(response.getHeader(UPDATED_VALUE_HEADER)), response.getBody());
} else if (response.getStatus() == STATUS_NOT_FOUND){
if (time != null) {
strategy.addDeleted();
} else {
strategy.addNotFound();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return strategy.getResponse();
}
}
private Response handlePut(Request request) throws IllegalArgumentException{
byte[] key = getKey(request);
byte[] value = request.getBody();
if (fromReplica(request)){
Response response;
try {
dao.upsert(key, value);
response = createSuccessPutResponse();
} catch (IOException e){
e.printStackTrace();
response = createInternalErrorResponse();
}
return response;
} else{
AckFrom ackFrom = new AckFrom(request);
TopologyStrategy.PutTopologyStrategy strategy = new TopologyStrategy.PutTopologyStrategy(ackFrom.ack, ackFrom.from);
for (String host : getHostsForKey(key, ackFrom.from)){
if (host.equals(myHost)){
try {
dao.upsert(key, value);
strategy.addSuccess();
} catch (IOException e){
e.printStackTrace();
}
} else{
try {
Response response = clients.get(host).put(request.getURI(), value, QUERY_FROM_REPLICA);
if (response.getStatus() == STATUS_SUCCESS_PUT){
strategy.addSuccess();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return strategy.getResponse();
}
}
private Response handleDelete(Request request) throws IllegalArgumentException{
byte[] key = getKey(request);
if (fromReplica(request)){
Response response;
try {
dao.remove(key);
response = createSuccessDeleteResponse();
} catch (IOException e){
e.printStackTrace();
response = createInternalErrorResponse();
}
return response;
} else{
AckFrom ackFrom = new AckFrom(request);
TopologyStrategy.DeleteTopologyStrategy strategy = new TopologyStrategy.DeleteTopologyStrategy(ackFrom.ack, ackFrom.from);
for (String host : getHostsForKey(key, ackFrom.from)){
if (host.equals(myHost)){
try {
dao.remove(key);
strategy.addSuccess();
} catch (IOException e) {
e.printStackTrace();
}
} else{
try {
Response response = clients.get(host).delete(request.getURI(), QUERY_FROM_REPLICA);
if (response.getStatus() == STATUS_SUCCESS_DELETE){
strategy.addSuccess();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
return strategy.getResponse();
}
}
private byte[] getKey(Request request) throws IllegalArgumentException{
String id = request.getParameter(ID_PARAMETER);
if (id == null || id.isEmpty()){
throw new IllegalArgumentException();
}
return id.getBytes();
}
private List<String> getHostsForKey(byte[] key, int from){
int hash = 0;
for (byte k : key){
hash += k;
}
int index = Math.abs(hash);
int hostsCount = topologyList.size();
List<String> hosts = new ArrayList<>(from);
for (int i = index + from; i > index; i--){
hosts.add(topologyList.get(i % hostsCount));
}
return hosts;
}
private boolean fromReplica(Request request){
return request.getHeader(QUERY_FROM_REPLICA) != null;
}
private class AckFrom{
final int ack;
final int from;
public AckFrom(Request request) throws IllegalArgumentException{
String replicas = request.getParameter(REPLICAS_PARAMETER);
if (replicas == null){
int size = topology.size();
this.ack = size / 2 + 1;
this.from = size;
} else {
try {
String[] split = replicas.split("/");
int ack = Integer.parseInt(split[0]);
int from = Integer.parseInt(split[1]);
if (ack < 1 || ack > from){
throw new Exception();
}
this.ack = ack;
this.from = from;
} catch (Exception e){
throw new IllegalArgumentException();
}
}
}
}
public static Response createNotEnoughReplicaResponse(){
return new Response(Response.GATEWAY_TIMEOUT, Response.EMPTY);
}
public static Response createSuccessPutResponse(){
return new Response(Response.CREATED, Response.EMPTY);
}
public static Response createSuccessDeleteResponse(){
return new Response(Response.ACCEPTED, Response.EMPTY);
}
public static Response createBadRequestResponse(){
return new Response(Response.BAD_REQUEST, Response.EMPTY);
}
public static Response createNotFoundResponse(){
return new Response(Response.NOT_FOUND, Response.EMPTY);
}
public static Response createInternalErrorResponse(){
return new Response(Response.INTERNAL_ERROR, Response.EMPTY);
}
}
| 37.209302 | 134 | 0.535625 |
518d4af4f57a0b4ed91ffe48d1ce7775a7fb9bed | 3,534 | package org.recap.repository;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
/**
* BaseSpecification which defines the criteria query for the Domain Driven
*
* @author Ramanujam (CEI)
*
*/
public abstract class BaseSpecification<T> implements Specification<T> {
private List<SearchCriteria> list;
public BaseSpecification() {
this.list = new ArrayList<>();
}
/**
* Adds the criteria to be used in the query.
* @param criteria
*/
public void add(SearchCriteria criteria) {
list.add(criteria);
}
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
//create a new predicate list
List<Predicate> predicates = new ArrayList<>();
//add add criteria to predicates
list.forEach(criteria -> {
if (criteria.getOperation().equals(SearchOperation.GREATER_THAN)) {
predicates.add(criteriaBuilder.greaterThan(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.LESS_THAN)) {
predicates.add(criteriaBuilder.lessThan(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.GREATER_THAN_EQUAL)) {
predicates.add(criteriaBuilder.greaterThanOrEqualTo(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.LESS_THAN_EQUAL)) {
predicates.add(criteriaBuilder.lessThanOrEqualTo(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.NOT_EQUAL)) {
predicates.add(criteriaBuilder.notEqual(
root.get(criteria.getKey()), criteria.getValue()));
} else if (criteria.getOperation().equals(SearchOperation.EQUAL)) {
predicates.add(criteriaBuilder.equal(
root.get(criteria.getKey()), criteria.getValue()));
} else if (criteria.getOperation().equals(SearchOperation.CONTAINS)) {
predicates.add(criteriaBuilder.like(
criteriaBuilder.lower(root.get(criteria.getKey())),
"%" + criteria.getValue().toString().toLowerCase() + "%"));
} else if (criteria.getOperation().equals(SearchOperation.STARTS_WITH)) {
predicates.add(criteriaBuilder.like(
criteriaBuilder.lower(root.get(criteria.getKey())),
criteria.getValue().toString().toLowerCase() + "%"));
} else if (criteria.getOperation().equals(SearchOperation.ENDS_WITH)) {
predicates.add(criteriaBuilder.like(
criteriaBuilder.lower(root.get(criteria.getKey())),
"%" + criteria.getValue().toString().toLowerCase()));
} else if (criteria.getOperation().equals(SearchOperation.IN)) {
predicates.add(criteriaBuilder.in(root.get(criteria.getKey())).value(criteria.getValue()));
} else if (criteria.getOperation().equals(SearchOperation.NOT_IN)) {
predicates.add(criteriaBuilder.not(root.get(criteria.getKey())).in(criteria.getValue()));
}
});
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
}
}
| 41.576471 | 111 | 0.683928 |
c7caaa0e18455105298d5fa881a85866fc158e22 | 2,124 | /*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.interfaces;
import javax.lang.model.type.TypeMirror;
import org.spongepowered.tools.obfuscation.mirror.TypeHandle;
/**
* Manager object which cann supply {@link TypeHandle} instances
*/
public interface ITypeHandleProvider {
/**
* Generate a type handle for the specified type
*
* @param name Type name (class name)
* @return A new type handle or null if the type could not be found
*/
public abstract TypeHandle getTypeHandle(String name);
/**
* Generate a type handle for the specified type, simulate the target using
* the supplied type
*
* @param name Type name (class name)
* @param simulatedTarget Simulation target
* @return A new type handle
*/
public abstract TypeHandle getSimulatedHandle(String name, TypeMirror simulatedTarget);
}
| 38.618182 | 91 | 0.735405 |
0b74348fe213b616abcaf56b8b8edc43147c007a | 837 | /*
* Copyright (C) 2010-2020 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.gui.api.factory;
import org.apache.wicket.Component;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import com.evolveum.midpoint.gui.api.prism.wrapper.ItemWrapper;
import com.evolveum.midpoint.gui.impl.factory.panel.ItemPanelContext;
public interface GuiComponentFactory<T extends ItemPanelContext<?, ?>> {
<IW extends ItemWrapper<?, ?>> boolean match(IW wrapper);
Component createPanel(T panelCtx);
Integer getOrder();
default void configure(T panelCtx, Component component) {
panelCtx.getFeedback().setFilter(new ComponentFeedbackMessageFilter(component));
}
}
| 31 | 88 | 0.76583 |
790aaf14c97b4b8875ac6e3b012a4d49b07f3d81 | 4,188 | package org.jembi.bsis.repository;
import java.io.File;
import java.util.List;
import java.util.Map;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.jembi.bsis.model.admin.FormField;
import org.jembi.bsis.model.user.User;
import org.jembi.bsis.repository.FormFieldRepository;
import org.jembi.bsis.suites.DBUnitContextDependentTestSuite;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Test using DBUnit to test the FormFieldRepository
*/
public class FormFieldRepositoryTest extends DBUnitContextDependentTestSuite {
@Autowired
FormFieldRepository formFieldRepository;
@Override
protected IDataSet getDataSet() throws Exception {
File file = new File("src/test/resources/dataset/FormFieldRepositoryDataset.xml");
return new FlatXmlDataSetBuilder().setColumnSensing(true).build(file);
}
@Override
protected User getLoggedInUser() throws Exception {
return null;
}
@Test
public void testFindFormFieldById() throws Exception {
FormField one = formFieldRepository.findFormFieldById(1l);
Assert.assertNotNull("There is a FormField with id 1", one);
Assert.assertEquals("The Form field matches what was expected", "Donor", one.getForm());
}
@Test
public void testFindFormFieldByIdUnknown() throws Exception {
FormField one = formFieldRepository.findFormFieldById(1111l);
Assert.assertNull("There is no FormField with id 1111", one);
}
@Test
public void testGetFormField() throws Exception {
FormField donorField = formFieldRepository.getFormField("Donor", "donorNumber");
Assert.assertNotNull("There is a donorNumber field for the Donor form", donorField);
Assert.assertEquals("The Form field matches what was expected", "Donor", donorField.getForm());
}
@Test
public void testGetFormFieldUnknown() throws Exception {
FormField donorField = formFieldRepository.getFormField("Donor", "junit");
Assert.assertNull("There is no junit field for the Donor form", donorField);
}
@Test
public void testGetAllDonorForm() throws Exception {
List<FormField> all = formFieldRepository.getFormFields("Donor");
Assert.assertNotNull("There are FormFields for the Donor Form", all);
Assert.assertEquals("There are 46 FormFields", 46, all.size());
}
@Test
public void testGetRequiredFormFieldsDonorForm() throws Exception {
List<String> all = formFieldRepository.getRequiredFormFields("Donor");
Assert.assertNotNull("There are FormFields for the Donor Form", all);
Assert.assertEquals("There are 5 required FormFields", 5, all.size());
Assert.assertTrue("donorNumber is a required field for the Donor form", all.contains("donorNumber"));
}
@Test
public void testGetRequiredFormFieldsUnknownForm() throws Exception {
List<String> all = formFieldRepository.getRequiredFormFields("Junit");
Assert.assertNotNull("There are no FormFields for the unknown Form", all);
Assert.assertEquals("There are no FormFields for the unknown Form", 0, all.size());
}
@Test
public void testGetFieldMaxLengths() throws Exception {
Map<String, Integer> maxLengths = formFieldRepository.getFieldMaxLengths("Donor");
Assert.assertNotNull("There is a non-null result", maxLengths);
Assert.assertEquals("There are 45 FormFields for Donor Form", 45, maxLengths.size());
// FIXME: there is a bug here - callingName field is repeated for Donor Form
Integer length = maxLengths.get("donorNumber");
Assert.assertEquals("donorNumber has a maxLength of 15", new Integer(15), length);
}
@Test
public void testUpdateFormField() throws Exception {
FormField donorField = formFieldRepository.getFormField("Donor", "donorNumber");
Assert.assertNotNull("There is a donorNumber field for the Donor form", donorField);
donorField.setMaxLength(123);
formFieldRepository.updateFormField(donorField);
FormField savedDonorField = formFieldRepository.getFormField("Donor", "donorNumber");
Assert.assertEquals("The Form field matches what was expected", new Integer(123), savedDonorField.getMaxLength());
}
}
| 40.269231 | 118 | 0.758835 |
5a51e663d67b69fc78d379b2ac29d5115e73ada2 | 225 | package com.zandero.rest.test.data;
public class ItemDto {
private final String value;
public ItemDto(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
| 15 | 35 | 0.617778 |
e37fb42531351ff541f936cb6f24153196cd27c3 | 13,925 | /*
* 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.mina.filter.codec.textline;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.filter.codec.ProtocolCodecSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.RecoverableProtocolDecoderException;
import org.junit.Test;
/**
* Tests {@link TextLineDecoder}.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class TextLineDecoderTest {
@Test
public void testNormalDecode() throws Exception {
TextLineDecoder decoder = new TextLineDecoder(StandardCharsets.UTF_8, LineDelimiter.WINDOWS);
CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
ProtocolCodecSession session = new ProtocolCodecSession();
ProtocolDecoderOutput out = session.getDecoderOutput();
IoBuffer in = IoBuffer.allocate(16);
// Test one decode and one output
in.putString("ABC\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("ABC", session.getDecoderOutputQueue().poll());
// Test two decode and one output
in.clear();
in.putString("DEF", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("GHI\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("DEFGHI", session.getDecoderOutputQueue().poll());
// Test one decode and two output
in.clear();
in.putString("JKL\r\nMNO\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(2, session.getDecoderOutputQueue().size());
assertEquals("JKL", session.getDecoderOutputQueue().poll());
assertEquals("MNO", session.getDecoderOutputQueue().poll());
// Test aborted delimiter (DIRMINA-506)
in.clear();
in.putString("ABC\r\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("ABC\r", session.getDecoderOutputQueue().poll());
// Test splitted long delimiter
decoder = new TextLineDecoder(StandardCharsets.UTF_8, new LineDelimiter("\n\n\n"));
in.clear();
in.putString("PQR\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("PQR", session.getDecoderOutputQueue().poll());
// Test splitted long delimiter which produces two output
decoder = new TextLineDecoder(StandardCharsets.UTF_8, new LineDelimiter("\n\n\n"));
in.clear();
in.putString("PQR\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\nSTU\n\n\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(2, session.getDecoderOutputQueue().size());
assertEquals("PQR", session.getDecoderOutputQueue().poll());
assertEquals("STU", session.getDecoderOutputQueue().poll());
// Test splitted long delimiter mixed with partial non-delimiter.
decoder = new TextLineDecoder(StandardCharsets.UTF_8, new LineDelimiter("\n\n\n"));
in.clear();
in.putString("PQR\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("X\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\n\nSTU\n\n\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(2, session.getDecoderOutputQueue().size());
assertEquals("PQR\nX", session.getDecoderOutputQueue().poll());
assertEquals("STU", session.getDecoderOutputQueue().poll());
}
public void testAutoDecode() throws Exception {
TextLineDecoder decoder = new TextLineDecoder(StandardCharsets.UTF_8, LineDelimiter.AUTO);
CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
ProtocolCodecSession session = new ProtocolCodecSession();
ProtocolDecoderOutput out = session.getDecoderOutput();
IoBuffer in = IoBuffer.allocate(16);
// Test one decode and one output
in.putString("ABC\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("ABC", session.getDecoderOutputQueue().poll());
// Test two decode and one output
in.clear();
in.putString("DEF", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("GHI\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("DEFGHI", session.getDecoderOutputQueue().poll());
// Test one decode and two output
in.clear();
in.putString("JKL\r\nMNO\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(2, session.getDecoderOutputQueue().size());
assertEquals("JKL", session.getDecoderOutputQueue().poll());
assertEquals("MNO", session.getDecoderOutputQueue().poll());
// Test multiple '\n's
in.clear();
in.putString("\n\n\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(3, session.getDecoderOutputQueue().size());
assertEquals("", session.getDecoderOutputQueue().poll());
assertEquals("", session.getDecoderOutputQueue().poll());
assertEquals("", session.getDecoderOutputQueue().poll());
// Test splitted long delimiter (\r\r\n)
in.clear();
in.putString("PQR\r", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\r", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("PQR", session.getDecoderOutputQueue().poll());
// Test splitted long delimiter (\r\r\n) which produces two output
in.clear();
in.putString("PQR\r", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\r", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\nSTU\r\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(2, session.getDecoderOutputQueue().size());
assertEquals("PQR", session.getDecoderOutputQueue().poll());
assertEquals("STU", session.getDecoderOutputQueue().poll());
// Test splitted long delimiter mixed with partial non-delimiter.
in.clear();
in.putString("PQR\r", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("X\r", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear();
in.putString("\r\nSTU\r\r\n", encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(2, session.getDecoderOutputQueue().size());
assertEquals("PQR\rX", session.getDecoderOutputQueue().poll());
assertEquals("STU", session.getDecoderOutputQueue().poll());
in.clear();
String s = new String(new byte[] { 0, 77, 105, 110, 97 });
in.putString(s, encoder);
in.flip();
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals(s, session.getDecoderOutputQueue().poll());
}
public void testOverflow() throws Exception {
TextLineDecoder decoder = new TextLineDecoder(StandardCharsets.UTF_8, LineDelimiter.AUTO);
decoder.setMaxLineLength(3);
CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
ProtocolCodecSession session = new ProtocolCodecSession();
ProtocolDecoderOutput out = session.getDecoderOutput();
IoBuffer in = IoBuffer.allocate(16);
// Make sure the overflow exception is not thrown until
// the delimiter is encountered.
in.putString("A", encoder).flip().mark();
decoder.decode(session, in.reset().mark(), out);
assertEquals(0, session.getDecoderOutputQueue().size());
decoder.decode(session, in.reset().mark(), out);
assertEquals(0, session.getDecoderOutputQueue().size());
decoder.decode(session, in.reset().mark(), out);
assertEquals(0, session.getDecoderOutputQueue().size());
decoder.decode(session, in.reset().mark(), out);
assertEquals(0, session.getDecoderOutputQueue().size());
in.clear().putString("A\r\nB\r\n", encoder).flip();
try {
decoder.decode(session, in, out);
fail();
} catch (RecoverableProtocolDecoderException e) {
// signifies a successful test execution
assertTrue(true);
}
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("B", session.getDecoderOutputQueue().poll());
// Make sure OOM is not thrown.
System.gc();
long oldFreeMemory = Runtime.getRuntime().freeMemory();
in = IoBuffer.allocate(1048576 * 16).sweep((byte) ' ').mark();
for (int i = 0; i < 10; i++) {
decoder.decode(session, in.reset().mark(), out);
assertEquals(0, session.getDecoderOutputQueue().size());
// Memory consumption should be minimal.
assertTrue(Runtime.getRuntime().freeMemory() - oldFreeMemory < 1048576);
}
in.clear().putString("C\r\nD\r\n", encoder).flip();
try {
decoder.decode(session, in, out);
fail();
} catch (RecoverableProtocolDecoderException e) {
// signifies a successful test execution
assertTrue(true);
}
decoder.decode(session, in, out);
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("D", session.getDecoderOutputQueue().poll());
// Memory consumption should be minimal.
assertTrue(Runtime.getRuntime().freeMemory() - oldFreeMemory < 1048576);
}
public void testSMTPDataBounds() throws Exception {
TextLineDecoder decoder = new TextLineDecoder(Charset.forName("ISO-8859-1"), new LineDelimiter("\r\n.\r\n"));
CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
ProtocolCodecSession session = new ProtocolCodecSession();
IoBuffer in = IoBuffer.allocate(16).setAutoExpand(true);
in.putString("\r\n", encoder).flip().mark();
decoder.decode(session, in.reset().mark(), session.getDecoderOutput());
assertEquals(0, session.getDecoderOutputQueue().size());
in.putString("Body\r\n.\r\n", encoder).flip().mark();
decoder.decode(session, in.reset().mark(), session.getDecoderOutput());
assertEquals(1, session.getDecoderOutputQueue().size());
assertEquals("\r\n\r\nBody", session.getDecoderOutputQueue().poll());
}
}
| 40.835777 | 117 | 0.631382 |
fedfcd97f071d246fa393fa3a030448d8ab8e970 | 270 | package com.other.vendor;
import javax.inject.Inject;
public class TestImplementation2 implements TestInterface {
@Inject
public TestImplementation2() {
}
@Override
public Source getSource() {
return Source.FROM_IMPLEMENTATION_2;
}
}
| 16.875 | 59 | 0.703704 |
0c50813280d563fc362d33b77ae2d4888f78f1ff | 383 | package com.github.vjuranek.netty.nbd.client;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
public class Utils {
public static final ChannelFutureListener writeFailed = (ChannelFuture future) -> {
if (!future.isSuccess()) {
future.cause().printStackTrace();
future.channel().close();
}
};
}
| 23.9375 | 87 | 0.671018 |
decca062fe1e6f623b789b530ce6bdebb5ae4b0a | 4,800 | /*
* 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.felix.gogo.runtime.threadio;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Locale;
public class ThreadPrintStream extends PrintStream
{
final PrintStream dflt;
final ThreadIOImpl io;
final boolean errorStream;
public ThreadPrintStream(ThreadIOImpl threadIO, PrintStream out, boolean error)
{
super(out);
dflt = out;
io = threadIO;
errorStream = error;
}
public PrintStream getCurrent()
{
Marker marker = io.current();
return errorStream ? marker.getErr() : marker.getOut();
}
/**
* Access to the root stream through reflection
*/
public PrintStream getRoot()
{
return dflt;
}
//
// Delegate methods
//
public void flush()
{
getCurrent().flush();
}
public void close()
{
getCurrent().close();
}
public boolean checkError()
{
return getCurrent().checkError();
}
public void setError()
{
// getCurrent().setError();
}
public void clearError()
{
// getCurrent().clearError();
}
public void write(int b)
{
getCurrent().write(b);
}
public void write(byte[] buf, int off, int len)
{
getCurrent().write(buf, off, len);
}
public void print(boolean b)
{
getCurrent().print(b);
}
public void print(char c)
{
getCurrent().print(c);
}
public void print(int i)
{
getCurrent().print(i);
}
public void print(long l)
{
getCurrent().print(l);
}
public void print(float f)
{
getCurrent().print(f);
}
public void print(double d)
{
getCurrent().print(d);
}
public void print(char[] s)
{
getCurrent().print(s);
}
public void print(String s)
{
getCurrent().print(s);
}
public void print(Object obj)
{
getCurrent().print(obj);
}
public void println()
{
getCurrent().println();
}
public void println(boolean x)
{
getCurrent().println(x);
}
public void println(char x)
{
getCurrent().println(x);
}
public void println(int x)
{
getCurrent().println(x);
}
public void println(long x)
{
getCurrent().println(x);
}
public void println(float x)
{
getCurrent().println(x);
}
public void println(double x)
{
getCurrent().println(x);
}
public void println(char[] x)
{
getCurrent().println(x);
}
public void println(String x)
{
getCurrent().println(x);
}
public void println(Object x)
{
getCurrent().println(x);
}
public PrintStream printf(String format, Object... args)
{
return getCurrent().printf(format, args);
}
public PrintStream printf(Locale l, String format, Object... args)
{
return getCurrent().printf(l, format, args);
}
public PrintStream format(String format, Object... args)
{
return getCurrent().format(format, args);
}
public PrintStream format(Locale l, String format, Object... args)
{
return getCurrent().format(l, format, args);
}
public PrintStream append(CharSequence csq)
{
return getCurrent().append(csq);
}
public PrintStream append(CharSequence csq, int start, int end)
{
return getCurrent().append(csq, start, end);
}
public PrintStream append(char c)
{
return getCurrent().append(c);
}
public void write(byte[] b) throws IOException
{
getCurrent().write(b);
}
}
| 21.145374 | 84 | 0.562708 |
900e37a349ed32e5014c0062dba62b1b21a74640 | 381 | package ru.job4j.tracker;
import java.util.List;
/**Интерфейс.
*@author IvanPJF (teaching-light@yandex.ru)
*@since 28.09.2018
*@version 0.1
*/
public interface Input {
/**
* Общий метод для классов реализующих этот интерфейс.
* @param question Вопрос пользователю.
*/
String ask(String question);
int ask(String question, List<Integer> range);
}
| 19.05 | 58 | 0.677165 |
7decd998ee579a50acb78800ae50b7c8ef7e4485 | 2,958 | package com.google.android.gms.auth;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.google.android.gms.common.internal.Objects;
import com.google.android.gms.common.internal.Preconditions;
import com.google.android.gms.common.internal.ReflectedParcelable;
import com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable;
import com.google.android.gms.common.internal.safeparcel.SafeParcelWriter;
import java.util.List;
public class TokenData extends AbstractSafeParcelable implements ReflectedParcelable {
public static final Parcelable.Creator<TokenData> CREATOR = new zzk();
private final List<String> zzaa;
private final String zzab;
private final int zzv;
private final String zzw;
private final Long zzx;
private final boolean zzy;
private final boolean zzz;
public static TokenData zza(Bundle bundle, String str) {
Class<TokenData> cls = TokenData.class;
bundle.setClassLoader(cls.getClassLoader());
Bundle bundle2 = bundle.getBundle(str);
if (bundle2 == null) {
return null;
}
bundle2.setClassLoader(cls.getClassLoader());
return (TokenData) bundle2.getParcelable("TokenData");
}
TokenData(int i, String str, Long l, boolean z, boolean z2, List<String> list, String str2) {
this.zzv = i;
this.zzw = Preconditions.checkNotEmpty(str);
this.zzx = l;
this.zzy = z;
this.zzz = z2;
this.zzaa = list;
this.zzab = str2;
}
public final String zzb() {
return this.zzw;
}
public boolean equals(Object obj) {
if (!(obj instanceof TokenData)) {
return false;
}
TokenData tokenData = (TokenData) obj;
if (!TextUtils.equals(this.zzw, tokenData.zzw) || !Objects.equal(this.zzx, tokenData.zzx) || this.zzy != tokenData.zzy || this.zzz != tokenData.zzz || !Objects.equal(this.zzaa, tokenData.zzaa) || !Objects.equal(this.zzab, tokenData.zzab)) {
return false;
}
return true;
}
public int hashCode() {
return Objects.hashCode(this.zzw, this.zzx, Boolean.valueOf(this.zzy), Boolean.valueOf(this.zzz), this.zzaa, this.zzab);
}
public void writeToParcel(Parcel parcel, int i) {
int beginObjectHeader = SafeParcelWriter.beginObjectHeader(parcel);
SafeParcelWriter.writeInt(parcel, 1, this.zzv);
SafeParcelWriter.writeString(parcel, 2, this.zzw, false);
SafeParcelWriter.writeLongObject(parcel, 3, this.zzx, false);
SafeParcelWriter.writeBoolean(parcel, 4, this.zzy);
SafeParcelWriter.writeBoolean(parcel, 5, this.zzz);
SafeParcelWriter.writeStringList(parcel, 6, this.zzaa, false);
SafeParcelWriter.writeString(parcel, 7, this.zzab, false);
SafeParcelWriter.finishObjectHeader(parcel, beginObjectHeader);
}
}
| 38.921053 | 248 | 0.684922 |
94596bba2471d42e9710753ea4ed07f44e3960d5 | 792 | package geeksForGeeks.arrays;
import java.util.Arrays;
/**
* @author Sarveswara Tippireddy
* <p>This GeeksforGeeks problem can be found @
* http://www.geeksforgeeks.org/find-pythagorean-triplet-in-an-unsorted-array/
*/
public class Arrays132 {
public boolean findPythogoreanTriplets(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * a[i];
}
Arrays.sort(a);
for (int i = a.length - 1; i > 1; i--) {
if (helper(a, i - 1, a[i])) {
return true;
}
}
return false;
}
private boolean helper(int[] a, int k, int x) {
int i = 0, j = k;
while (i < j) {
if (a[i] + a[j] > x) {
j--;
} else if (a[i] + a[j] < x) {
i++;
} else {
return true;
}
}
return false;
}
}
| 20.307692 | 78 | 0.512626 |
84317072b0f76dad22ffbcaacd6f8c297644db9a | 9,455 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.alibaba.polardbx.executor.ddl.job.factory;
import com.alibaba.polardbx.common.utils.Pair;
import com.alibaba.polardbx.executor.ddl.job.converter.DdlJobDataConverter;
import com.alibaba.polardbx.executor.ddl.job.converter.PhysicalPlanData;
import com.alibaba.polardbx.executor.ddl.job.task.basic.CreateTablePhyDdlTask;
import com.alibaba.polardbx.executor.ddl.job.task.cdc.CdcTableGroupDdlMarkTask;
import com.alibaba.polardbx.executor.ddl.job.task.tablegroup.AlterTableGroupAddSubTaskMetaTask;
import com.alibaba.polardbx.executor.ddl.newengine.job.DdlJobFactory;
import com.alibaba.polardbx.executor.ddl.newengine.job.DdlTask;
import com.alibaba.polardbx.executor.ddl.newengine.job.ExecutableDdlJob;
import com.alibaba.polardbx.gms.partition.TablePartitionRecord;
import com.alibaba.polardbx.gms.tablegroup.PartitionGroupRecord;
import com.alibaba.polardbx.gms.tablegroup.TableGroupConfig;
import com.alibaba.polardbx.optimizer.OptimizerContext;
import com.alibaba.polardbx.optimizer.config.table.ComplexTaskMetaManager;
import com.alibaba.polardbx.optimizer.context.ExecutionContext;
import com.alibaba.polardbx.optimizer.core.rel.PhyDdlTableOperation;
import com.alibaba.polardbx.optimizer.core.rel.ddl.data.AlterTableGroupItemPreparedData;
import com.alibaba.polardbx.optimizer.partition.PartitionInfo;
import com.alibaba.polardbx.optimizer.partition.PartitionInfoUtil;
import com.alibaba.polardbx.optimizer.partition.pruning.PhysicalPartitionInfo;
import com.alibaba.polardbx.optimizer.tablegroup.AlterTableGroupSnapShotUtils;
import org.apache.calcite.rel.core.DDL;
import org.apache.calcite.sql.SqlAlterTableGroup;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class AlterTableGroupSubTaskJobFactory extends DdlJobFactory {
@Deprecated
protected final DDL ddl;
protected final AlterTableGroupItemPreparedData preparedData;
private final List<PhyDdlTableOperation> phyDdlTableOperations;
private final Map<String, List<List<String>>> tableTopology;
private final Map<String, Set<String>> targetTableTopology;
private final Map<String, Set<String>> sourceTableTopology;
protected final List<Pair<String, String>> orderedTargetTableLocations;
private final boolean skipBackfill;
protected final ExecutionContext executionContext;
private final String targetPartition;
public AlterTableGroupSubTaskJobFactory(DDL ddl, AlterTableGroupItemPreparedData preparedData,
List<PhyDdlTableOperation> phyDdlTableOperations,
Map<String, List<List<String>>> tableTopology,
Map<String, Set<String>> targetTableTopology,
Map<String, Set<String>> sourceTableTopology,
List<Pair<String, String>> orderedTargetTableLocations,
String targetPartition,
boolean skipBackfill,
ExecutionContext executionContext) {
this.preparedData = preparedData;
this.phyDdlTableOperations = phyDdlTableOperations;
this.ddl = ddl;
this.tableTopology = tableTopology;
this.targetTableTopology = targetTableTopology;
this.sourceTableTopology = sourceTableTopology;
this.orderedTargetTableLocations = orderedTargetTableLocations;
this.skipBackfill = skipBackfill;
this.executionContext = executionContext;
this.targetPartition = targetPartition;
}
@Override
protected void validate() {
}
@Override
protected ExecutableDdlJob doCreate() {
String schemaName = preparedData.getSchemaName();
String tableName = preparedData.getTableName();
String tableGroupName = preparedData.getTableGroupName();
TableGroupConfig tableGroupConfig = OptimizerContext.getContext(schemaName).getTableGroupInfoManager()
.getTableGroupConfigByName(tableGroupName);
PartitionInfo newPartitionInfo = generateNewPartitionInfo();
TablePartitionRecord logTableRec = PartitionInfoUtil.prepareRecordForLogicalTable(newPartitionInfo);
logTableRec.partStatus = TablePartitionRecord.PARTITION_STATUS_LOGICAL_TABLE_PUBLIC;
List<TablePartitionRecord> partRecList =
PartitionInfoUtil.prepareRecordForAllPartitions(newPartitionInfo);
Map<String, List<TablePartitionRecord>> subPartRecInfos = PartitionInfoUtil
.prepareRecordForAllSubpartitions(partRecList, newPartitionInfo,
newPartitionInfo.getPartitionBy().getPartitions());
//DdlTask validateTask = new AlterTableGroupValidateTask(schemaName, preparedData.getTableGroupName());
DdlTask addMetaTask =
new AlterTableGroupAddSubTaskMetaTask(schemaName, tableName,
tableGroupConfig.getTableGroupRecord().getTg_name(),
tableGroupConfig.getTableGroupRecord().getId(), "",
ComplexTaskMetaManager.ComplexTaskStatus.CREATING.getValue(), 0, logTableRec, partRecList,
subPartRecInfos);
List<DdlTask> taskList = new ArrayList<>();
//1. validate
//taskList.add(validateTask);
//2. create physical table
//2.1 insert meta to complex_task_outline
taskList.add(addMetaTask);
//2.2 create partitioned physical table
phyDdlTableOperations.forEach(o -> o.setPartitionInfo(newPartitionInfo));
if (!tableTopology.isEmpty()) {
PhysicalPlanData physicalPlanData =
DdlJobDataConverter.convertToPhysicalPlanData(tableTopology, phyDdlTableOperations);
DdlTask phyDdlTask =
new CreateTablePhyDdlTask(schemaName, physicalPlanData.getLogicalTableName(), physicalPlanData);
taskList.add(phyDdlTask);
}
List<DdlTask> bringUpNewPartitions = ComplexTaskFactory
.addPartitionTasks(schemaName, tableName, sourceTableTopology, targetTableTopology,
skipBackfill || tableTopology.isEmpty(), executionContext);
//3.2 status: CREATING -> DELETE_ONLY -> WRITE_ONLY -> WRITE_REORG -> READY_TO_PUBLIC
taskList.addAll(bringUpNewPartitions);
//cdc ddl mark task
SqlKind sqlKind = ddl.kind();
Map<String, Set<String>> newTopology =
newPartitionInfo.getPhysicalPartitionTopology(null).entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey,
v -> v.getValue().stream().map(PhysicalPartitionInfo::getPhyTable).collect(Collectors.toSet())));
DdlTask cdcDdlMarkTask = new CdcTableGroupDdlMarkTask(schemaName, tableName, sqlKind, newTopology);
taskList.add(cdcDdlMarkTask);
final ExecutableDdlJob executableDdlJob = new ExecutableDdlJob();
executableDdlJob.addSequentialTasks(taskList);
executableDdlJob.labelAsHead(addMetaTask);
executableDdlJob.labelAsTail(bringUpNewPartitions.get(bringUpNewPartitions.size() - 1));
return executableDdlJob;
}
@Override
protected void excludeResources(Set<String> resources) {
for (String partName : preparedData.getOldPartitionNames()) {
resources.add(concatWithDot(
concatWithDot(concatWithDot(preparedData.getSchemaName(), preparedData.getTableGroupName()), partName),
preparedData.getTableName()));
}
}
@Override
protected void sharedResources(Set<String> resources) {
}
protected PartitionInfo generateNewPartitionInfo() {
String schemaName = preparedData.getSchemaName();
String tableName = preparedData.getTableName();
String tableGroupName = preparedData.getTableGroupName();
PartitionInfo curPartitionInfo =
OptimizerContext.getContext(schemaName).getPartitionInfoManager().getPartitionInfo(tableName);
List<PartitionGroupRecord> inVisiblePartitionGroupRecords = preparedData.getInvisiblePartitionGroups();
SqlNode sqlAlterTableGroupSpecNode = ((SqlAlterTableGroup) ddl.getSqlNode()).getAlters().get(0);
PartitionInfo newPartInfo =
AlterTableGroupSnapShotUtils
.getNewPartitionInfo(curPartitionInfo, inVisiblePartitionGroupRecords, sqlAlterTableGroupSpecNode,
tableGroupName,
targetPartition,
orderedTargetTableLocations,
preparedData.getNewPartitionNames(),
executionContext);
return newPartInfo;
}
}
| 49.502618 | 119 | 0.71835 |
08295528d0f111e5d7e30fca4ab82ca277004269 | 4,301 | package com.github.cstettler.dddttc.support.infrastructure.persistence;
import com.github.cstettler.dddttc.stereotype.ApplicationService;
import com.github.cstettler.dddttc.stereotype.InfrastructureService;
import com.github.cstettler.dddttc.stereotype.Repository;
import org.springframework.aop.support.annotation.AnnotationClassFilter;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import static java.lang.reflect.Modifier.isPublic;
import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
import static org.springframework.transaction.TransactionDefinition.PROPAGATION_MANDATORY;
import static org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRED;
import static org.springframework.util.ReflectionUtils.isEqualsMethod;
import static org.springframework.util.ReflectionUtils.isHashCodeMethod;
public class TransactionConfiguration {
@Bean
BeanFactoryTransactionAttributeSourceAdvisor applicationServiceTransactionAttributeSourceAdvisor(BeanFactory beanFactory) {
return stereotypeBasedTransactionAttributeSourceAdvisor(beanFactory, ApplicationService.class, PROPAGATION_REQUIRED);
}
@Bean
BeanFactoryTransactionAttributeSourceAdvisor repositoryTransactionAttributeSourceAdvisor(BeanFactory beanFactory) {
return stereotypeBasedTransactionAttributeSourceAdvisor(beanFactory, Repository.class, PROPAGATION_MANDATORY);
}
@Bean
BeanFactoryTransactionAttributeSourceAdvisor infrastructureServiceTransactionAttributeSourceAdvisor(BeanFactory beanFactory) {
return stereotypeBasedTransactionAttributeSourceAdvisor(beanFactory, InfrastructureService.class, PROPAGATION_MANDATORY);
}
private static BeanFactoryTransactionAttributeSourceAdvisor stereotypeBasedTransactionAttributeSourceAdvisor(BeanFactory beanFactory, Class<? extends Annotation> stereotype, int propagationBehavior) {
BeanFactoryTransactionAttributeSourceAdvisor transactionAttributeSourceAdvisor = new BeanFactoryTransactionAttributeSourceAdvisor();
transactionAttributeSourceAdvisor.setClassFilter(new AnnotationClassFilter(stereotype, true));
transactionAttributeSourceAdvisor.setAdvice(stereotypeBasedTransactionInterceptor(beanFactory, stereotype, propagationBehavior));
return transactionAttributeSourceAdvisor;
}
private static TransactionInterceptor stereotypeBasedTransactionInterceptor(BeanFactory beanFactory, Class<? extends Annotation> stereotype, int propagationBehavior) {
TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
transactionInterceptor.setTransactionAttributeSource(stereotypeBasedTransactionAttributeSource(stereotype, propagationBehavior));
transactionInterceptor.setBeanFactory(beanFactory);
return transactionInterceptor;
}
private static TransactionAttributeSource stereotypeBasedTransactionAttributeSource(Class<? extends Annotation> stereotype, int propagationBehavior) {
return (method, targetClassCandidate) -> {
if (isEqualsMethod(method) || isHashCodeMethod(method)) {
return null;
}
if (findAnnotation(targetClass(method, targetClassCandidate), stereotype) != null && isPublic(method.getModifiers())) {
DefaultTransactionAttribute defaultTransactionAttribute = new DefaultTransactionAttribute();
defaultTransactionAttribute.setPropagationBehavior(propagationBehavior);
return defaultTransactionAttribute;
}
return null;
};
}
private static Class<?> targetClass(Method method, Class<?> targetClassCandidate) {
if (targetClassCandidate != null) {
return targetClassCandidate;
}
return method.getDeclaringClass();
}
}
| 51.819277 | 204 | 0.811904 |
c12bd659322f6b8501793d277166b49925d68ff8 | 697 | package com.example.imageuploaddemo;
public class Upload {
private String title;
private String image;
public Upload() {
}
public Upload(String title, String image) {
if(title.trim().equals("")){
title = "No Name";
}
this.title = title;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
| 19.914286 | 51 | 0.480631 |
3d983b9c1c0de4b974d67eca531419a0fb29220f | 2,723 | package es.uniovi.asw.voterAcess.webService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import es.uniovi.asw.dbManagement.model.Voter;
import es.uniovi.asw.dbManagement.persistence.Repository;
import es.uniovi.asw.voterAcess.ChangePassword;
import es.uniovi.asw.voterAcess.infrastructure.ErrorFactory;
import es.uniovi.asw.voterAcess.webService.responses.ChangePasswordResponse;
import es.uniovi.asw.voterAcess.webService.responses.errors.ErrorResponse;
@RestController
@Controller
public class ChangePasswordController implements ChangePassword{
private static final Logger log = LoggerFactory.getLogger(GetVoterInfoController.class);
@RequestMapping(value="/changePassword",
method=RequestMethod.POST,
headers = "Accept=application/json",
produces="application/json")
public String changePassword(@RequestBody ChangePasswordResponse data)
{
log.info("Password: " + data.getPassword() + " New Password: " + data.getNewPassword());
if(data.getEmail().compareTo("")==0)
throw ErrorFactory.getErrorResponse(ErrorFactory.Errors.REQUIRED_EMAIL);
if(data.getPassword().compareTo("")==0)
throw ErrorFactory.getErrorResponse(ErrorFactory.Errors.REQUIRED_PASSWORD);
if(data.getNewPassword().compareTo("")==0)
throw ErrorFactory.getErrorResponse(ErrorFactory.Errors.REQUIRED_NEW_PASSWORD);
Voter voter = Repository.voterR.findByEmail(data.getEmail());
if (voter != null)
{
if(changePassword(data.getPassword(),data.getNewPassword(), voter))
{
return "{\"Resultado\":\"Contraseña cambiada correctamente\"}";
}
else { throw ErrorFactory.getErrorResponse(ErrorFactory.Errors.INCORRECT_PASSWORD); }
}
else // Voter no encontrado
{
throw ErrorFactory.getErrorResponse(ErrorFactory.Errors.USER_NOT_FOUND);
}
}
@ExceptionHandler(ErrorResponse.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public String handleErrorResponses(ErrorResponse excep)
{
return excep.getMessageJSONFormat();
}
private boolean changePassword(String password, String newPassword,Voter voter)
{
if (password.compareTo(voter.getPassword()) == 0)
{
voter.setPassword(newPassword);
Repository.voterR.save(voter);
return true;
}
return false;
}
} | 32.416667 | 90 | 0.784062 |
9e165859a4f84e59afa39da595d46a883b34aeac | 974 | package com.thinkaurelius.titan.diskstorage.cassandra.thrift;
import com.thinkaurelius.titan.diskstorage.BackendException;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import com.thinkaurelius.titan.CassandraStorageSetup;
import com.thinkaurelius.titan.diskstorage.DistributedStoreManagerTest;
public class ThriftDistributedStoreManagerTest extends DistributedStoreManagerTest<CassandraThriftStoreManager> {
@BeforeClass
public static void startCassandra() {
CassandraStorageSetup.startCleanEmbedded();
}
@Before
public void setUp() throws BackendException {
manager = new CassandraThriftStoreManager(
CassandraStorageSetup.getCassandraThriftConfiguration(this.getClass().getSimpleName()));
store = manager.openDatabase("distributedcf");
}
@After
public void tearDown() throws BackendException {
if (null != manager)
manager.close();
}
}
| 31.419355 | 113 | 0.753593 |
7b1eb6c12a82607301649d866527d7471502652a | 1,189 | package com.practice.hackerrank.algorithms.strings;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
* Problem- [Funny String] (https://www.hackerrank.com/challenges/funny-string/problem)
*
* @author lakshay
*/
public class FunnyString {
// Complete the funnyString function below.
static String funnyString(String s) {
char[] ch = s.toCharArray();
int len = ch.length;
for (int i = 0; i < ch.length - 1; i++) {
int forwardDiff = Math.abs(ch[i] - ch[i + 1]);
int backDiff = Math.abs(ch[len - 1 - i] - ch[len - 2 - i]);
System.out.println("f =" + forwardDiff + "b =" + backDiff);
if (forwardDiff != backDiff) {
return "Not Funny";
}
}
return "Funny";
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int q = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int qItr = 0; qItr < q; qItr++) {
String s = scanner.nextLine();
String result = funnyString(s);
System.out.println(result);
}
scanner.close();
}
}
| 27.651163 | 87 | 0.624895 |
216f924721b53258ee6bc9838b79e6a4e48fc5f1 | 4,016 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.accumulo.serde;
import java.util.Properties;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.junit.Assert;
import org.junit.Test;
/**
*
*/
public class TestAccumuloSerDeParameters {
@Test
public void testParseColumnVisibility() throws SerDeException {
Properties properties = new Properties();
Configuration conf = new Configuration();
properties.setProperty(AccumuloSerDeParameters.COLUMN_MAPPINGS, ":rowid,cf:f2,cf:f3");
properties.setProperty(serdeConstants.LIST_COLUMNS, "field1,field2,field3");
properties.setProperty(serdeConstants.LIST_TYPE_NAME, "string,string,string");
properties.setProperty(AccumuloSerDeParameters.VISIBILITY_LABEL_KEY, "foo&bar");
AccumuloSerDeParameters params = new AccumuloSerDeParameters(conf, properties,
AccumuloSerDe.class.getName());
ColumnVisibility cv = params.getTableVisibilityLabel();
Assert.assertEquals(new ColumnVisibility("foo&bar"), cv);
}
@Test
public void testParseAuthorizationsFromConf() throws SerDeException {
Configuration conf = new Configuration(false);
conf.set(AccumuloSerDeParameters.AUTHORIZATIONS_KEY, "foo,bar");
Authorizations auths = AccumuloSerDeParameters.getAuthorizationsFromConf(conf);
Assert.assertEquals(new Authorizations("foo,bar"), auths);
}
@Test
public void testParseAuthorizationsFromnProperties() throws SerDeException {
Configuration conf = new Configuration();
Properties properties = new Properties();
properties.setProperty(AccumuloSerDeParameters.COLUMN_MAPPINGS, ":rowid,cf:f2,cf:f3");
properties.setProperty(serdeConstants.LIST_COLUMNS, "field1,field2,field3");
properties.setProperty(serdeConstants.LIST_COLUMN_TYPES, "string,string,string");
properties.setProperty(AccumuloSerDeParameters.AUTHORIZATIONS_KEY, "foo,bar");
AccumuloSerDeParameters params = new AccumuloSerDeParameters(conf, properties,
AccumuloSerDe.class.getName());
Authorizations auths = params.getAuthorizations();
Assert.assertEquals(new Authorizations("foo,bar"), auths);
}
@Test
public void testNullAuthsFromProperties() throws SerDeException {
Configuration conf = new Configuration();
Properties properties = new Properties();
properties.setProperty(AccumuloSerDeParameters.COLUMN_MAPPINGS, ":rowid,cf:f2,cf:f3");
properties.setProperty(serdeConstants.LIST_COLUMNS, "field1,field2,field3");
properties.setProperty(serdeConstants.LIST_COLUMN_TYPES, "string,string,string");
AccumuloSerDeParameters params = new AccumuloSerDeParameters(conf, properties,
AccumuloSerDe.class.getName());
Authorizations auths = params.getAuthorizations();
Assert.assertNull(auths);
}
@Test
public void testNullAuthsFromConf() throws SerDeException {
Configuration conf = new Configuration(false);
Authorizations auths = AccumuloSerDeParameters.getAuthorizationsFromConf(conf);
Assert.assertNull(auths);
}
}
| 39.372549 | 90 | 0.772659 |
aa71b53ece53bc52820d416ecf5bd6755ad890de | 6,492 | package com.sell.liqihao.sellsystem.module.Setting.ui;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import com.sell.liqihao.sellsystem.App.app;
import com.sell.liqihao.sellsystem.R;
import com.sell.liqihao.sellsystem.base.BaseActivity;
import com.sell.liqihao.sellsystem.module.Login.bean.ResultBean;
import com.sell.liqihao.sellsystem.module.Login.ui.LoginActivity;
import com.sell.liqihao.sellsystem.module.Setting.contract.SettingContract;
import com.sell.liqihao.sellsystem.module.Setting.presenter.SettingPresenter;
import com.sell.liqihao.sellsystem.module.Util.PopUtil;
import com.sell.liqihao.sellsystem.utils.ToastUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class SettingActivity extends BaseActivity<SettingPresenter> implements SettingContract.view {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.AppBarLayout01)
AppBarLayout AppBarLayout01;
@BindView(R.id.updateAddress)
LinearLayout updateAddress;
@BindView(R.id.updatePass)
LinearLayout updatePass;
@BindView(R.id.setting_signOut)
Button settingSignOut;
@Override
public void initView() {
ButterKnife.bind(this);
initToolBar(toolbar,true,"设置");
if (getSupportActionBar() != null)
getSupportActionBar().setHomeAsUpIndicator(R.mipmap.navbar_back);
}
@Override
public void getData() {
}
@Override
public int getLayout() {
return R.layout.activity_setting;
}
@Override
public void onShowLoading() {
}
@Override
public void onHideLoading() {
}
@Override
public void onShowNetError() {
}
@Override
public void setPresenter(SettingPresenter presenter) {
if (this.presenter == null)
this.presenter = new SettingPresenter();
}
@Override
public void onShowNoMore() {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@OnClick({R.id.updateAddress, R.id.updatePass, R.id.setting_signOut})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.updateAddress:
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("您之前的地址为" + app.userBean.getAddress() + "是否确定更改?")
.setCancelable(false)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
showPop();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog.show();
break;
case R.id.updatePass:
showPassPop();
break;
case R.id.setting_signOut:
app.userBean = null;
startActivity(new Intent(this, LoginActivity.class));
finish();
break;
}
}
EditText popEdt;
Button popBtn;
PopupWindow popup;
@Override
public void showPop() {
if (popUp!= null)
popUp.dismiss();
View pop = getLayoutInflater().inflate(R.layout.pop_show,null);
popEdt = pop.findViewById(R.id.pop_msg);
popBtn = pop.findViewById(R.id.pop_confirm);
popEdt.setHint("请输入新地址");
popup = PopUtil.pop(pop);
popup.update();
popup.showAtLocation(updateAddress,Gravity.CENTER,0,0);
popBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TextUtils.isEmpty(popEdt.getText().toString()))
ToastUtils.showShort(getApplicationContext(),"地址为空,请重新输入");
else presenter.doUpdateAddress(popEdt.getText().toString());
}
});
}
PopupWindow popUp;
EditText oldText;
EditText newText;
Button confirm;
@Override
public void showPassPop() {
if (popup!= null)
popup.dismiss();
View pop = getLayoutInflater().inflate(R.layout.pop_updatepass,null);
oldText = pop.findViewById(R.id.pop_update_pass);
newText = pop.findViewById(R.id.pop_update_newpass);
confirm = pop.findViewById(R.id.pop_update_confirm);
oldText.setHint("请输入现在的密码");
newText.setHint("请输入新密码");
popUp = PopUtil.pop(pop);
popUp.update();
popUp.showAtLocation(settingSignOut,Gravity.CENTER,0,0);
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (oldText.getText().toString().equals(app.userBean.getPass())){
if (TextUtils.isEmpty(newText.getText().toString()))
ToastUtils.showShort(getApplicationContext(), "新密码为空,请重新输入");
else presenter.doUpdatePass(newText.getText().toString());
} else {
ToastUtils.showShort(getApplicationContext(),"密码验证错误,请重新输入");
}
}
});
}
@Override
public void onAddressChange(ResultBean resultBean) {
app.userBean.setAddress(resultBean.getResult());
ToastUtils.showShort(this,"修改成功");
popup.dismiss();
}
@Override
public void onPassChanger(ResultBean resultBean) {
app.userBean.setPass(resultBean.getResult());
ToastUtils.showShort(this,"修改成功");
popUp.dismiss();
}
}
| 32.46 | 101 | 0.613986 |
51e6c75513e32faa2708158db8ae2038648e5e82 | 515 | import java.io.*;
class lcm
{
int a,b;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
lcm() throws IOException
{
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
cal(a,b);
}
void cal(int x,int y)
{
int k;
k=1;
while((x*k)%y!=0)
k++;
System.out.println("Lcm:"+(x*k));
}
public static void main()throws IOException
{
lcm a=new lcm();
}
} | 19.807692 | 75 | 0.508738 |
ee94e2e33ea6f1d9cc72a0833a29b20b1527702a | 1,716 | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.stream.processor.core.ha.tcp;
import org.wso2.carbon.stream.processor.core.internal.beans.DeploymentConfig;
/**
* Singleton tcp server.
*/
public class TCPServer {
private static TCPServer instance = new TCPServer();
private EventSyncServer eventSyncServer = new EventSyncServer();
private boolean started = false;
private TCPServer() {
}
public static TCPServer getInstance() {
return instance;
}
public void start(DeploymentConfig deploymentConfig) {
if (!started) {
eventSyncServer.start(deploymentConfig);
started = true;
}
}
public void stop() {
if (started) {
try {
eventSyncServer.shutdownGracefully();
} finally {
started = false;
}
}
}
public void clearResources() {
eventSyncServer.clearResources();
}
public EventSyncServer getEventSyncServer() {
return eventSyncServer;
}
}
| 26.8125 | 77 | 0.65035 |
16d6ae2ebee66dc331cfccc09ad482f74b3a0a2e | 11,016 | package pragmaticdevelopment.com.honeydue;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import pragmaticdevelopment.com.honeydue.DBSource.ListsModel;
import pragmaticdevelopment.com.honeydue.HelperClasses.ListHelper;
import static pragmaticdevelopment.com.honeydue.HelperClasses.ListHelper.*;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ListFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ListFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ListFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private ListTask lTask = null;
private ListView lvLists;
private ListsAdapter la;
private ListsModel[] lists;
private int[] listIDs;
public static ListFragment newInstance() {
// Put bundle or other args here
return new ListFragment();
}
public ListFragment() {
// Required empty public constructor
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.lvLists) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.actions_menu, menu);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
SharedPreferences sp = getContext().getSharedPreferences(getString(R.string.shared_pref_id), Context.MODE_PRIVATE);
final String spToken = sp.getString("token", null);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final long itemId = info.id;
switch (item.getItemId()) {
case R.id.action_share_list:
final EditText shEditText = new EditText(this.getActivity());
AlertDialog dialog = new AlertDialog.Builder(this.getActivity())
.setTitle("Share this list")
.setMessage("Username")
.setView(shEditText)
.setPositiveButton("Share", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String shUser = String.valueOf(shEditText.getText());
ListHelper.addCollabUserShareList(listIDs[(int) itemId], shUser, spToken);
Toast.makeText(getActivity().getApplicationContext(), "Successfully shared with " + shUser,
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
return true;
case R.id.action_edit_list:
final EditText edEditText = new EditText(this.getActivity());
AlertDialog builder = new AlertDialog.Builder(this.getActivity())
.setTitle("Edit List Name")
.setMessage("New List Name")
.setView(edEditText)
.setPositiveButton("Set", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newName = String.valueOf(edEditText.getText());
ListHelper.updateList(listIDs[(int) itemId], newName, spToken);
Toast.makeText(getActivity().getApplicationContext(), "Successfully changed list name to " + newName,
Toast.LENGTH_SHORT).show();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ListFragment lf = ListFragment.newInstance();
ft.replace(R.id.fragFrame, lf, "lists");
ft.commit();
}
})
.setNegativeButton("Cancel", null)
.create();
builder.show();
return true;
case R.id.action_delete_list:
Log.d("delete ", "delete");
ListHelper.deleteList(listIDs[(int) itemId], spToken);
Toast.makeText(getActivity().getApplicationContext(), "List deleted!",
Toast.LENGTH_SHORT).show();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ListFragment lf = ListFragment.newInstance();
ft.replace(R.id.fragFrame, lf, "lists");
ft.commit();
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list, container, false);
// Initialize lists
lvLists = (ListView) view.findViewById(R.id.lvLists);
registerForContextMenu(lvLists);
// Get user token
SharedPreferences sp = getContext().getSharedPreferences(getString(R.string.shared_pref_id), Context.MODE_PRIVATE);
String spToken = sp.getString("token", null);
if(spToken != null) {
// Acquire lists
lTask = new ListTask(spToken);
lTask.execute((Void) null);
try { lTask.get(); // this will cause application to wait until it returns
}catch(Exception ex){}
// Set adapter to ListView
lvLists.setAdapter(la);
// Put IDs of lists in an array
listIDs = new int[lists.length];
for (int i = 0; i < lists.length; i++) {
listIDs[i] = lists[i].getId();
}
}
lvLists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getContext(), TaskListActivity.class);
i.putExtra("LIST_ID_EXTRA", listIDs[position]);
ListsModel selected = (ListsModel)lvLists.getItemAtPosition(position);
i.putExtra("LIST_TITLE_EXTRA", selected.getTitle());
startActivity(i);
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public class ListsAdapter extends ArrayAdapter<ListsModel>{
public ListsAdapter(Context context, ArrayList<ListsModel> lists){
super(context, 0, lists);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListsModel list = getItem(position);
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_list, parent, false);
}
TextView tvList = (TextView) convertView.findViewById(R.id.txtListTitle);
tvList.setText(list.getTitle());
return convertView;
}
}
public class ListTask extends AsyncTask<Void, Void, Boolean>{
String uToken;
ListTask(String token){
uToken = token;
}
@Override
protected Boolean doInBackground(Void... params) {
try{
lists = getAllLists(uToken);
la = new ListsAdapter(getContext(), new ArrayList<ListsModel>(Arrays.asList(lists)));
return la.getCount() > 0;
}catch(Exception e){
return false;
}
}
@Override
protected void onPostExecute(final Boolean success){
lTask = null;
// If there are no lists
if(!success) Toast.makeText(getContext(), "No Lists Available", Toast.LENGTH_SHORT).show();
}
@Override
protected void onCancelled(){
lTask = null;
}
}
}
| 37.216216 | 133 | 0.601761 |
4c185441e05f52d3e3cefb315eca7b8de2c0714a | 134 | package dk.in2isoft.onlineobjects.core;
public interface PrivilegedQuery {
public PrivilegedQuery as(Privileged... privileged);
}
| 16.75 | 53 | 0.798507 |
8c0286367c80d8bc889dd89acd084d847d8f8b6b | 632 | package io.github.whazzabi.whazzup.business.cloudwatch;
import java.util.List;
import static java.util.Collections.emptyList;
public class MappingPredicates {
private List<String> includes;
private List<String> excludes;
public List<String> getIncludes() {
return includes != null ? includes : emptyList();
}
public void setIncludes(List<String> includes) {
this.includes = includes;
}
public List<String> getExcludes() {
return excludes != null ? excludes : emptyList();
}
public void setExcludes(List<String> excludes) {
this.excludes = excludes;
}
} | 23.407407 | 57 | 0.674051 |
3f950ebf37a1d46defdb9eb9777ffbe7f6845202 | 259 | package com.cjpowered.learn.inventory;
import java.time.LocalDate;
import java.util.Optional;
import com.cjpowered.learn.marketing.MarketingInfo;
public interface Item {
Order createOrder(LocalDate when, InventoryDatabase db, MarketingInfo marketInfo);
}
| 23.545455 | 83 | 0.822394 |
010df063eb57ab9f7d252d0bbcb50794fdea2c0e | 1,890 | package ru.apermyakov.testtask.requests;
import ru.apermyakov.testtask.user.User;
import java.util.*;
/**
* Class for modulate computer requests.
*
* @author apermyakov.
* @version 1.0.
* @since 12.01.2018.
*/
public class ComputerRequest implements Request {
/**
* Field for board height.
*/
private int height;
/**
* Field for board width.
*/
private int width;
/**
* Constructor.
*
* @param height board height.
* @param width board width.
*/
public ComputerRequest(int height, int width) {
this.height = height;
this.width = width;
}
/**
* Method for request coordinates.
*
* @return map of coordinates.
*/
@Override
public Map<String, Integer> requestCoordinates() {
Random random = new Random();
Map<String, Integer> result = new HashMap<>();
result.put("Height", random.nextInt(this.height) + 1);
result.put("Width", random.nextInt(this.width) + 1);
return result;
}
/**
* Method for request complexity.
*
* @return complexity.
*/
@Override
public int requestComplexity() {
return 0;
}
/**
* Method for request priority.
*
* @param users users.
*/
@Override
public void requestPriority(List<User> users) {
}
/**
* Method for request size.
*
* @return map of sizes.
*/
@Override
public Map<String, Integer> requestSize() {
return null;
}
/**
* Method for request value.
*
* @param users list of users.
*/
@Override
public void requestValue(List<User> users) {
}
/**
* Method for request continue or exit.
*
* @return true if continue.
*/
@Override
public boolean continueGame() {
return true;
}
}
| 19.090909 | 62 | 0.55873 |
9dce06167108506ff0139ddd4e878388f4ebeb17 | 5,766 | package com.jcommerce.gwt.client.panels.promote;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.jcommerce.gwt.client.ContentWidget;
import com.jcommerce.gwt.client.ModelNames;
import com.jcommerce.gwt.client.PageState;
import com.jcommerce.gwt.client.form.BeanObject;
import com.jcommerce.gwt.client.model.IGoods;
import com.jcommerce.gwt.client.model.ISnatch;
import com.jcommerce.gwt.client.service.CreateService;
import com.jcommerce.gwt.client.service.ListService;
import com.jcommerce.gwt.client.widgets.ColumnPanel;
import com.jcommerce.gwt.client.widgets.DateWidget;
public class NewSnatchPanel extends ContentWidget {
private ColumnPanel contentPanel = new ColumnPanel();
public static class State extends PageState {
public String getPageClassName() {
return NewSnatchPanel.class.getName();
}
public String getMenuDisplayName() {
return "添加夺宝奇兵 ";
}
}
public State getCurState() {
if (curState == null ) {
curState = new State();
}
return (State)curState;
}
public String getDescription() {
return "cwBasicTextDescription";
}
public String getName() {
return "添加夺宝奇兵 ";
}
protected void onRender(Element parent, int index) {
super.onRender(parent, index);
ColumnPanel topPanel = new ColumnPanel();
final TextBox snTextBox = new TextBox();
topPanel.createPanel(ISnatch.SNATCH_NAME, "活动名称", snTextBox);
HorizontalPanel searchPanel = new HorizontalPanel();
final TextBox searchTextBox = new TextBox();
Button searchButton = new Button("搜索");
searchPanel.add(searchTextBox);
searchPanel.add(searchButton);
topPanel.createPanel("", "商品关键字", searchPanel);
HorizontalPanel selectPanel = new HorizontalPanel();
final ListBox listGoods = new ListBox();
listGoods.addItem("请先搜索商品");
selectPanel.add(listGoods);
topPanel.createPanel("", "活动商品", selectPanel);
final DateWidget startTime = new DateWidget();
final DateWidget endTime = new DateWidget();
topPanel.createPanel("", "活动开始时间", startTime);
topPanel.createPanel("", "活动结束时间", endTime);
final TextBox maxBox = new TextBox();
final TextBox minBox = new TextBox();
final TextBox maxPaidBox = new TextBox();
final TextBox scoreConsumBox = new TextBox();
final TextArea descArea = new TextArea();
descArea.setSize(300, 50);
topPanel.createPanel("", "价格上限", maxBox);
topPanel.createPanel("", "价格下限", minBox);
topPanel.createPanel("", "最多需支付的价格", maxPaidBox);
topPanel.createPanel("", "消耗积分", scoreConsumBox);
topPanel.createPanel("", "活动描述", descArea);
searchButton.addSelectionListener(new SelectionListener<ButtonEvent>(){
public void componentSelected(ButtonEvent ce) {
listGoods.clear();
new ListService().listBeans(ModelNames.GOODS, new ListService.Listener() {
public void onSuccess(List<BeanObject> beans) {
List<String> goods = new ArrayList<String>();
for(BeanObject bean : beans) {
goods.add(bean.getString(IGoods.NAME));
if(bean.getString(IGoods.NAME).equals(searchTextBox.getText()) || bean.getString(IGoods.NUMBER).equals(searchTextBox.getText())) {
listGoods.addItem(bean.getString(IGoods.NAME));
}
}
if(searchTextBox.getText().equals("")) {
for(String str : goods) {
listGoods.addItem(str);
}
}
}
});
}});
HorizontalPanel contentpanel = new HorizontalPanel();
Button okButton = new Button("确定");
Button resetButton = new Button("重置");
contentpanel.setSpacing(30);
contentpanel.add(okButton);
contentpanel.add(resetButton);
contentPanel.add(topPanel);
contentPanel.add(contentpanel);
add(contentPanel);
okButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
Map<String,Object> map = new HashMap<String,Object>();
map.put(ISnatch.SNATCH_NAME, snTextBox.getText());
map.put(ISnatch.GOOD_NAME, listGoods.getItemText(listGoods.getSelectedIndex()));
map.put(ISnatch.START_TIME, startTime.getValue().getTime());
map.put(ISnatch.END_TIME, endTime.getValue().getTime());
map.put(ISnatch.MAX_PAID_PRICE, maxPaidBox.getText());
map.put(ISnatch.SCORE_CONSUM, scoreConsumBox.getText());
map.put(ISnatch.MAX_PRICE, maxBox.getText());
map.put(ISnatch.MIN_PRICE, minBox.getText());
// System.out.println(descArea.getValue());
map.put(ISnatch.DESC, descArea.getValue());
BeanObject bean = new BeanObject(ModelNames.SNATCH,map);
new CreateService().createBean(bean, new CreateService.Listener() {
public void onSuccess(String id) {
SnatchListPanel.State state = new SnatchListPanel.State();
state.execute();
}
});
}
});
resetButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
snTextBox.setText("");
startTime.setValue(new Date());
endTime.setValue(new Date());
maxBox.setText("0.0");
minBox.setText("0.0");
maxPaidBox.setText("0.0");
scoreConsumBox.setText("");
descArea.clear();
}
});
}
}
| 35.592593 | 138 | 0.695109 |
698e62a09beed875056a9a4e439b9bec2945b918 | 503 | package jointfaas;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
public class AwsIndex implements RequestStreamHandler {
private Index handler = new Index();
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
handler.handle(inputStream, outputStream);
}
} | 33.533333 | 119 | 0.801193 |
4d0690d509ddc5587e910d6bfb6dd144dc5b3358 | 312 | package foodsearch.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.UUID;
@Data
public class Delivery {
public Delivery() {
//Default Constructor
}
private UUID orderId;
private String foodName;
private String storeName;
private String stationName;
}
| 16.421053 | 31 | 0.708333 |
948bee857581e674c1b96e28f694422ef173112a | 776 | package com.amazonaws.ssm.parameter;
public class Constants {
// ParameterName limit is 1024 chars. To make sure that we never hit that limit with auto name generation,
// lets have a number less than the allowed limit i.e 1000.
// The total of following three variables should be less than 1000.
// This can be increased in the future.
public static final int ALLOWED_LOGICAL_RESOURCE_ID_LENGTH = 500;
public static final String CF_PARAMETER_NAME_PREFIX = "CFN";
public static final int GUID_LENGTH = 12;
public static final int ERROR_STATUS_CODE_400 = 400;
public static final int ERROR_STATUS_CODE_500 = 500;
public static final Integer MAX_RESULTS = 50;
public static final String AWS_EC2_IMAGE_DATATYPE = "aws:ec2:image";
}
| 43.111111 | 110 | 0.75 |
0f3ebab963be062988a0b363714ae251d743665c | 7,386 | package app.cn.extra.mall.merchant.activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import org.greenrobot.eventbus.EventBus;
import java.util.HashMap;
import java.util.Map;
import app.cn.extra.mall.merchant.R;
import app.cn.extra.mall.merchant.event.SingleInfoEvent;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cfkj.app.cn.cfkjcommonlib.common.BaseActivty;
import cfkj.app.cn.cfkjcommonlib.common.Utils;
/**
* Description 修改单条信息页(账户信息等)
* Data 2018/6/11-10:53
* Content
*
* @author lzy
*/
public class ChangeSingleInfoActivity extends BaseActivty {
@BindView(R.id.img_back)
ImageView imgBack;
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.tv_submit)
TextView tvSubmit;
@BindView(R.id.rl_title)
RelativeLayout rlTitle;
@BindView(R.id.et_content)
EditText etContent;
/**
* 用以判断修改的信息
*/
private String tag = "";
/**
* 原内容
*/
private String content = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_single_info);
ButterKnife.bind(this);
initView();
}
/**
* 初始化界面内元素
*/
private void initView() {
Intent intent = getIntent();
tag = intent.getStringExtra("tag");
content = intent.getStringExtra("content");
if (!TextUtils.isEmpty(content)) {
if ("uTel".equals(tag) || "sTel".equals(tag)) {
etContent.setInputType(InputType.TYPE_CLASS_PHONE);
}
etContent.setText(content);
} else {
if ("uNickName".equals(tag)) {
etContent.setHint(getResources().getString(R.string.inputUNickName));
} else if ("uEmail".equals(tag)) {
etContent.setHint(getResources().getString(R.string.inputUEmail));
} else if ("uBirthday".equals(tag)) {
etContent.setHint(getResources().getString(R.string.inputUBirthday));
} else if ("uTel".equals(tag)) {
etContent.setHint(getResources().getString(R.string.inputUTel));
etContent.setInputType(InputType.TYPE_CLASS_PHONE);
} else if ("sDescribe".equals(tag)) {
etContent.setHint(getResources().getString(R.string.inputSDescribe));
}
}
}
@OnClick({R.id.img_back, R.id.tv_submit})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.img_back:
finish();
break;
case R.id.tv_submit:
doSubmit();
break;
default:
}
}
/**
* 提交修改的信息
*/
private void doSubmit() {
if (TextUtils.isEmpty(etContent.getText().toString().trim())) {
showShortToast(ChangeSingleInfoActivity.this, getResources().getString(
R.string.singleInfoEmpty));
return;
}
/**
* 未修改内容
*/
if (content.equals(etContent.getText().toString().trim())) {
showShortToast(ChangeSingleInfoActivity.this, getResources().getString(
R.string.changeNothing));
return;
}
if ("uEmail".equals(tag)) {
if (!Utils.isValidEmail(etContent.getText().toString().trim())) {
showShortToast(ChangeSingleInfoActivity.this, getResources().getString(
R.string.emailError));
return;
}
}
if ("uBirthday".equals(tag)) {
if (!Utils.isValidBirthday(etContent.getText().toString().trim())) {
showShortToast(ChangeSingleInfoActivity.this, getResources().getString(
R.string.birthdayError));
return;
}
}
if ("uTel".equals(tag)) {
if (!Utils.isValidPhoneNumber(etContent.getText().toString().trim())) {
showShortToast(ChangeSingleInfoActivity.this, getResources().getString(
R.string.phoneNumError));
return;
}
}
if ("sTel".equals(tag)) {
if (!Utils.isValidPhoneNumber(etContent.getText().toString().trim())) {
showShortToast(ChangeSingleInfoActivity.this, getResources().getString(
R.string.phoneNumError));
return;
}
}
String uNickName = "";
String uEmail = "";
String uBirthday = "";
String uTel = "";
String sName = "";
String sDescribe = "";
String sTel = "";
if ("uNickName".equals(tag)) {
uNickName = etContent.getText().toString().trim();
imUpdateUserInfo(tag, uNickName);
} else if ("uEmail".equals(tag)) {
uEmail = etContent.getText().toString().trim();
imUpdateUserInfo(tag, uEmail);
} else if ("uBirthday".equals(tag)) {
uBirthday = etContent.getText().toString().trim();
imUpdateUserInfo(tag, uBirthday);
} else if ("uTel".equals(tag)) {
uTel = etContent.getText().toString().trim();
imUpdateUserInfo(tag, uTel);
} else if ("sName".equals(tag)) {
sName = etContent.getText().toString().trim();
} else if ("sDescribe".equals(tag)) {
sDescribe = etContent.getText().toString().trim();
} else if ("sTel".equals(tag)) {
sTel = etContent.getText().toString().trim();
}
EventBus.getDefault().post(new SingleInfoEvent(uNickName,
uEmail, uBirthday, uTel, sName, sDescribe, sTel));
finish();
}
private void imUpdateUserInfo(String tag, String value) {
Map<UserInfoFieldEnum, Object> fields = new HashMap<>(1);
if ("uNickName".equals(tag)) {
fields.put(UserInfoFieldEnum.Name, value);
} else if ("uEmail".equals(tag)) {
fields.put(UserInfoFieldEnum.EMAIL, value);
} else if ("uBirthday".equals(tag)) {
fields.put(UserInfoFieldEnum.BIRTHDAY, value);
} else if ("uTel".equals(tag)) {
fields.put(UserInfoFieldEnum.MOBILE, value);
} else if ("pic".equals(tag)) {
fields.put(UserInfoFieldEnum.AVATAR, value);
}
NIMClient.getService(UserService.class).updateUserInfo(fields)
.setCallback(new RequestCallbackWrapper<Void>() {
@Override
public void onResult(int i, Void aVoid, Throwable throwable) {
}
});
}
}
| 35.854369 | 88 | 0.567154 |
749adf5a4a7fe1bbe5cabbe276929eff08c1c791 | 7,989 | // Generated by view binder compiler. Do not edit!
package com.example.latest.vasu.newappcenter.databinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.viewbinding.ViewBinding;
import androidx.viewbinding.ViewBindings;
import com.example.latest.vasu.newappcenter.R;
import com.example.latest.vasu.newappcenter.widgets.SquareImageView;
import java.lang.NullPointerException;
import java.lang.Override;
import java.lang.String;
public final class ListItmeTopThreeAppsBinding implements ViewBinding {
@NonNull
private final ConstraintLayout rootView;
@NonNull
public final FrameLayout cardApp1;
@NonNull
public final FrameLayout cardApp2;
@NonNull
public final FrameLayout cardApp3;
@NonNull
public final ImageView ivAd1;
@NonNull
public final ImageView ivAd2;
@NonNull
public final ImageView ivAd3;
@NonNull
public final ImageView ivAppBg1;
@NonNull
public final ImageView ivAppBg2;
@NonNull
public final ImageView ivAppBg3;
@NonNull
public final SquareImageView ivAppThumb1;
@NonNull
public final SquareImageView ivAppThumb2;
@NonNull
public final SquareImageView ivAppThumb3;
@NonNull
public final ImageView ivTitleBg;
@NonNull
public final TextView tvAppDownload1;
@NonNull
public final TextView tvAppDownload2;
@NonNull
public final TextView tvAppDownload3;
@NonNull
public final TextView tvAppName1;
@NonNull
public final TextView tvAppName2;
@NonNull
public final TextView tvAppName3;
@NonNull
public final TextView tvTitle;
private ListItmeTopThreeAppsBinding(@NonNull ConstraintLayout rootView,
@NonNull FrameLayout cardApp1, @NonNull FrameLayout cardApp2, @NonNull FrameLayout cardApp3,
@NonNull ImageView ivAd1, @NonNull ImageView ivAd2, @NonNull ImageView ivAd3,
@NonNull ImageView ivAppBg1, @NonNull ImageView ivAppBg2, @NonNull ImageView ivAppBg3,
@NonNull SquareImageView ivAppThumb1, @NonNull SquareImageView ivAppThumb2,
@NonNull SquareImageView ivAppThumb3, @NonNull ImageView ivTitleBg,
@NonNull TextView tvAppDownload1, @NonNull TextView tvAppDownload2,
@NonNull TextView tvAppDownload3, @NonNull TextView tvAppName1, @NonNull TextView tvAppName2,
@NonNull TextView tvAppName3, @NonNull TextView tvTitle) {
this.rootView = rootView;
this.cardApp1 = cardApp1;
this.cardApp2 = cardApp2;
this.cardApp3 = cardApp3;
this.ivAd1 = ivAd1;
this.ivAd2 = ivAd2;
this.ivAd3 = ivAd3;
this.ivAppBg1 = ivAppBg1;
this.ivAppBg2 = ivAppBg2;
this.ivAppBg3 = ivAppBg3;
this.ivAppThumb1 = ivAppThumb1;
this.ivAppThumb2 = ivAppThumb2;
this.ivAppThumb3 = ivAppThumb3;
this.ivTitleBg = ivTitleBg;
this.tvAppDownload1 = tvAppDownload1;
this.tvAppDownload2 = tvAppDownload2;
this.tvAppDownload3 = tvAppDownload3;
this.tvAppName1 = tvAppName1;
this.tvAppName2 = tvAppName2;
this.tvAppName3 = tvAppName3;
this.tvTitle = tvTitle;
}
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
@NonNull
public static ListItmeTopThreeAppsBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static ListItmeTopThreeAppsBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.list_itme_top_three_apps, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static ListItmeTopThreeAppsBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.card_app1;
FrameLayout cardApp1 = ViewBindings.findChildViewById(rootView, id);
if (cardApp1 == null) {
break missingId;
}
id = R.id.card_app2;
FrameLayout cardApp2 = ViewBindings.findChildViewById(rootView, id);
if (cardApp2 == null) {
break missingId;
}
id = R.id.card_app3;
FrameLayout cardApp3 = ViewBindings.findChildViewById(rootView, id);
if (cardApp3 == null) {
break missingId;
}
id = R.id.iv_ad_1;
ImageView ivAd1 = ViewBindings.findChildViewById(rootView, id);
if (ivAd1 == null) {
break missingId;
}
id = R.id.iv_ad_2;
ImageView ivAd2 = ViewBindings.findChildViewById(rootView, id);
if (ivAd2 == null) {
break missingId;
}
id = R.id.iv_ad_3;
ImageView ivAd3 = ViewBindings.findChildViewById(rootView, id);
if (ivAd3 == null) {
break missingId;
}
id = R.id.iv_app_bg_1;
ImageView ivAppBg1 = ViewBindings.findChildViewById(rootView, id);
if (ivAppBg1 == null) {
break missingId;
}
id = R.id.iv_app_bg_2;
ImageView ivAppBg2 = ViewBindings.findChildViewById(rootView, id);
if (ivAppBg2 == null) {
break missingId;
}
id = R.id.iv_app_bg_3;
ImageView ivAppBg3 = ViewBindings.findChildViewById(rootView, id);
if (ivAppBg3 == null) {
break missingId;
}
id = R.id.iv_app_thumb1;
SquareImageView ivAppThumb1 = ViewBindings.findChildViewById(rootView, id);
if (ivAppThumb1 == null) {
break missingId;
}
id = R.id.iv_app_thumb2;
SquareImageView ivAppThumb2 = ViewBindings.findChildViewById(rootView, id);
if (ivAppThumb2 == null) {
break missingId;
}
id = R.id.iv_app_thumb3;
SquareImageView ivAppThumb3 = ViewBindings.findChildViewById(rootView, id);
if (ivAppThumb3 == null) {
break missingId;
}
id = R.id.iv_title_bg;
ImageView ivTitleBg = ViewBindings.findChildViewById(rootView, id);
if (ivTitleBg == null) {
break missingId;
}
id = R.id.tv_app_download1;
TextView tvAppDownload1 = ViewBindings.findChildViewById(rootView, id);
if (tvAppDownload1 == null) {
break missingId;
}
id = R.id.tv_app_download2;
TextView tvAppDownload2 = ViewBindings.findChildViewById(rootView, id);
if (tvAppDownload2 == null) {
break missingId;
}
id = R.id.tv_app_download3;
TextView tvAppDownload3 = ViewBindings.findChildViewById(rootView, id);
if (tvAppDownload3 == null) {
break missingId;
}
id = R.id.tv_app_name1;
TextView tvAppName1 = ViewBindings.findChildViewById(rootView, id);
if (tvAppName1 == null) {
break missingId;
}
id = R.id.tv_app_name2;
TextView tvAppName2 = ViewBindings.findChildViewById(rootView, id);
if (tvAppName2 == null) {
break missingId;
}
id = R.id.tv_app_name3;
TextView tvAppName3 = ViewBindings.findChildViewById(rootView, id);
if (tvAppName3 == null) {
break missingId;
}
id = R.id.tv_title;
TextView tvTitle = ViewBindings.findChildViewById(rootView, id);
if (tvTitle == null) {
break missingId;
}
return new ListItmeTopThreeAppsBinding((ConstraintLayout) rootView, cardApp1, cardApp2,
cardApp3, ivAd1, ivAd2, ivAd3, ivAppBg1, ivAppBg2, ivAppBg3, ivAppThumb1, ivAppThumb2,
ivAppThumb3, ivTitleBg, tvAppDownload1, tvAppDownload2, tvAppDownload3, tvAppName1,
tvAppName2, tvAppName3, tvTitle);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
| 29.263736 | 99 | 0.695957 |
03afe2864d921691f36e60440188005843ad8559 | 139 | package org.gitlab.api.auth;
/**
* Date: 06.04.2015
* Time: 16:53
*
* @author Alexey Pimenov
*/
public interface GitlabAuthToken {
}
| 12.636364 | 34 | 0.661871 |
9c65f64480fbbfefba01d0c229cf6d2bdd700570 | 21,659 | package org.sag.acminer.phases.defusegraph;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import org.sag.acminer.IACMinerDataAccessor;
import org.sag.acminer.database.defusegraph.DefUseGraph;
import org.sag.acminer.database.defusegraph.IDefUseGraphDatabase;
import org.sag.acminer.database.excludedelements.IExcludeHandler;
import org.sag.acminer.phases.entrypoints.EntryPoint;
import org.sag.common.concurrent.CountingThreadExecutor;
import org.sag.common.concurrent.IgnorableRuntimeException;
import org.sag.common.concurrent.LoggingWorkerGroup;
import org.sag.common.concurrent.Worker;
import org.sag.common.concurrent.WorkerCountingThreadExecutor;
import org.sag.common.logging.ILogger;
import org.sag.soot.callgraph.ExcludingJimpleICFG;
import org.sag.soot.callgraph.IJimpleICFG;
import org.sag.soot.callgraph.JimpleICFG;
import org.sag.soot.callgraph.ExcludingJimpleICFG.ExcludingEdgePredicate;
import soot.SootClass;
public class DefUseGraphRunner {
private final ILogger mainLogger;
private final IACMinerDataAccessor dataAccessor;
private final String name;
//TODO Remove commented out sections
/*private final Map<SootClass,Path> stubToFieldOutput;
private final Map<SootClass,Path> stubToMethodOutput;
private final Map<SootClass,Path> stubToStringConstOutput;
private final Map<SootClass,Path> stubToValueOutput;
private final Map<SootClass,Path> stubToFieldOutputUq;
private final Map<SootClass,Path> stubToMethodOutputUq;
private final Map<SootClass,Path> stubToStringConstOutputUq;
private final Map<SootClass,Path> stubToValueOutputUq;
private final Path gFieldOutput;
private final Path gMethodOutput;
private final Path gStringConstOutput;
private final Path gValueOutput;
private final Set<String> allFields;
private final Set<String> allMethods;
private final Map<String,Set<String>> allStringConst;
private final Map<String,Set<String>> allValues;*/
public DefUseGraphRunner(IACMinerDataAccessor dataAccessor, ILogger mainLogger){
this.dataAccessor = dataAccessor;
this.mainLogger = mainLogger;
this.name = getClass().getSimpleName();
/*this.gFieldOutput = FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),"vt_fields.txt");
this.gMethodOutput = FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),"vt_methods.txt");
this.gStringConstOutput = FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),"vt_string_const.txt");
this.gValueOutput = FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),"vt_uses.txt");
this.stubToFieldOutput = new HashMap<>();
this.stubToMethodOutput = new HashMap<>();
this.stubToStringConstOutput = new HashMap<>();
this.stubToValueOutput = new HashMap<>();
this.stubToFieldOutputUq = new HashMap<>();
this.stubToMethodOutputUq = new HashMap<>();
this.stubToStringConstOutputUq = new HashMap<>();
this.stubToValueOutputUq = new HashMap<>();
this.allFields = new HashSet<>();
this.allMethods = new HashSet<>();
this.allStringConst = new HashMap<>();
this.allValues = new HashMap<>();*/
/*for(EntryPoint ep : dataAccessor.getEntryPoints()) {
SootClass stub = ep.getStub();
if(!stubToFieldOutput.containsKey(stub)) {
String stubString = stub.getName().replace(".", "-").replace("$", "~");
stubToFieldOutput.put(stub, FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),
stubString+"_vt_fields.txt"));
stubToMethodOutput.put(stub, FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),
stubString+"_vt_methods.txt"));
stubToStringConstOutput.put(stub, FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),
stubString+"_vt_string_const.txt"));
stubToValueOutput.put(stub, FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),
stubString+"_vt_uses.txt"));
stubToFieldOutputUq.put(stub, FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),
stubString+"_vt_fields_uq.txt"));
stubToMethodOutputUq.put(stub, FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),
stubString+"_vt_methods_uq.txt"));
stubToStringConstOutputUq.put(stub, FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),
stubString+"_vt_string_const_uq.txt"));
stubToValueOutputUq.put(stub, FileHelpers.getPath(PMinerFilePaths.v().getOutput_Miner_DefUseGraphBeforeFilterDir(),
stubString+"_vt_uses_uq.txt"));
}
}*/
}
public boolean run() {
boolean successOuter = true;
mainLogger.info("{}: Begin the value tree runner.",name);
/*try {
FileHelpers.processDirectory(PMinerFilePaths.v().getInput_DefUseGraphBeforeFilterDir(), true, true);
} catch(Throwable t) {
mainLogger.fatal("{}: Failed to create output directory '{}'. Stoping analysis!",name,
PMinerFilePaths.v().getInput_DefUseGraphBeforeFilterDir());
successOuter = false;
}*/
if(successOuter){
WorkerCountingThreadExecutor exe = null;
DefUseGraphMaker vtm = null;
List<LoggingWorkerGroup> workerGroups = new ArrayList<>();
//Set new control predicates database
dataAccessor.setDefUseGraphDB(IDefUseGraphDatabase.Factory.getNew(false));
try{
JimpleICFG baseICFG = new JimpleICFG(dataAccessor.getEntryPoints(),false);
SootClass stub = null;
LoggingWorkerGroup curWorkerGroup = null;
Deque<EntryPoint> eps = new ArrayDeque<>(dataAccessor.getEntryPoints());
exe = new WorkerCountingThreadExecutor();
vtm = new DefUseGraphMaker();
while(!eps.isEmpty()) {
EntryPoint ep = eps.poll();
if(stub == null || !stub.equals(ep.getStub())) {
stub = ep.getStub();
if(curWorkerGroup != null) {
curWorkerGroup.unlockInitialLock();
curWorkerGroup = null;
}
DefUseGraphMakerGroup g = new DefUseGraphMakerGroup(name,stub.toString(),false//,stubToFieldOutputUq.get(stub),
/*stubToMethodOutputUq.get(stub),stubToStringConstOutputUq.get(stub),stubToValueOutputUq.get(stub)*/);
if(g.getLogger() == null) {
mainLogger.fatal("{}: Failed to initilize local logger for '{}'. Skipping analysis of '{}'.",name,stub,stub);
successOuter = false;
} else {
curWorkerGroup = g;
workerGroups.add(g);
}
}
if(curWorkerGroup != null){
Runnable runner = new DefUseGraphMakerRunner(ep,baseICFG,vtm,curWorkerGroup.getLogger());
try {
exe.execute(runner, curWorkerGroup);
} catch(Throwable t) {
mainLogger.fatal("{}: Failed to execute '{}' for group '{}'.",name,runner.toString(),curWorkerGroup.getName());
successOuter = false;
}
}
}
//Unlock the initial lock for the last group produced by the loop
if(curWorkerGroup != null) {
curWorkerGroup.unlockInitialLock();
curWorkerGroup = null;
}
} catch(Throwable t) {
mainLogger.fatal("{}: An unexpected exception occured in the def use graph runner.",t,name);
successOuter = false;
} finally {
//Shutdown the executors
if(exe != null && !exe.shutdownWhenFinished()){
mainLogger.fatal(CountingThreadExecutor.computeJointErrorMsg(exe.getAndClearExceptions(),
"Failed to wait for the executor to terminate.", name));
successOuter = false;
}
if(vtm != null && !vtm.shutdownWhenFinished()) {
mainLogger.fatal(CountingThreadExecutor.computeJointErrorMsg(vtm.getAndClearExceptions(),
"Failed to wait for the def use graph maker to terminate.",name));
successOuter = false;
}
for(LoggingWorkerGroup g : workerGroups) {
if(g.shutdownNormally() && !g.hasExceptions()) {
mainLogger.info("{}: Successfully completed the def use graph runner for Stub '{}'.",name,g.getName());
} else {
mainLogger.fatal("{}: Failed to complete the def use graph runner for Stub '{}'.",name,g.getName());
successOuter = false;
}
}
}
}
/*if(successOuter) {
try {
writeFields(allFields,gFieldOutput,name,mainLogger);
writeMethods(allMethods,gMethodOutput,name,mainLogger);
writeStringConst(allStringConst,gStringConstOutput,name,mainLogger);
writeValues(allValues,gValueOutput,name,mainLogger);
} catch(IgnorableRuntimeException e) {
successOuter = false;
}
}*/
if(!successOuter){
mainLogger.fatal("{}: The def use graph runner failed for one or more entry points. Stopping Analysis!",name);
return false;
}else{
mainLogger.info("{}: The def use graph runner succeeded!",name);
return true;
}
}
/*private static void writeFields(Set<String> fields, Path p, String name, ILogger logger) {
try (PrintStreamUnixEOL ps = new PrintStreamUnixEOL(Files.newOutputStream(p,StandardOpenOption.APPEND,
StandardOpenOption.CREATE,StandardOpenOption.WRITE))) {
for(String s : SortingMethods.sortSet(fields,SootSort.sfStringComp)) {
ps.println("Field: " + s);
}
} catch(Throwable t) {
logger.fatal("{}: An error occured when writing to file '{}'.",name,p);
throw new IgnorableRuntimeException();
}
}
private static void writeMethods(Set<String> methods, Path p, String name, ILogger logger) {
try (PrintStreamUnixEOL ps = new PrintStreamUnixEOL(Files.newOutputStream(p,StandardOpenOption.APPEND,
StandardOpenOption.CREATE,StandardOpenOption.WRITE))) {
for(String s : SortingMethods.sortSet(methods,SootSort.smStringComp)) {
ps.println("Method: " + s);
}
} catch(Throwable t) {
logger.fatal("{}: An error occured when writing to file '{}'.",name,p);
throw new IgnorableRuntimeException();
}
}
private static void writeStringConst(Map<String,Set<String>> stringConsts, Path p, String name, ILogger logger) {
for(String s : stringConsts.keySet())
stringConsts.put(s, SortingMethods.sortSet(stringConsts.get(s),SortingMethods.sComp));
Map<String,Set<String>> temp = SortingMethods.sortMapKey(stringConsts,SortingMethods.sComp);
try (PrintStreamUnixEOL ps = new PrintStreamUnixEOL(Files.newOutputStream(p,StandardOpenOption.APPEND,
StandardOpenOption.CREATE,StandardOpenOption.WRITE))) {
for(String s : temp.keySet()) {
ps.println("StringConst: " + s);
for(String k : temp.get(s)) {
ps.println(" Use: " + k);
}
}
} catch(Throwable t) {
logger.fatal("{}: An error occured when writing to file '{}'.",name,p);
throw new IgnorableRuntimeException();
}
}
private static void writeValues(Map<String,Set<String>> values, Path p, String name, ILogger logger) {
for(String s : values.keySet())
values.put(s, SortingMethods.sortSet(values.get(s),SortingMethods.sComp));
Map<String,Set<String>> temp = SortingMethods.sortMapKey(values,SortingMethods.sComp);
Map<String,BigInteger> countMap = DefUseGraph.computeAllStatementsCount(temp);
BigInteger totalUses = BigInteger.ZERO;
for(BigInteger i : countMap.values()) {
totalUses = totalUses.add(i);
}
try (PrintStreamUnixEOL ps = new PrintStreamUnixEOL(Files.newOutputStream(p,StandardOpenOption.APPEND,
StandardOpenOption.CREATE,StandardOpenOption.WRITE))) {
ps.println("Totals: Unique Control Predicates = " + countMap.keySet().size() + ", Unique Uses = " + totalUses.toString());
for(String s : temp.keySet()) {
ps.println(s + " Count: " + countMap.get(s));
for(String k : temp.get(s)) {
ps.println(" Def: " + k);
}
}
} catch(Throwable t) {
logger.fatal("{}: An error occured when writing to file '{}'.",name,p);
throw new IgnorableRuntimeException();
}
}*/
private static class DefUseGraphMakerGroup extends LoggingWorkerGroup {
/*private final Path fieldsOut;
private final Path methodsOut;
private final Path stringConstOut;
private final Path usesOut;
private volatile Set<String> fields;
private volatile Set<String> methods;
private volatile Map<String,Set<String>> stringConstToUses;
private volatile Map<String,Set<String>> startToUses;*/
public DefUseGraphMakerGroup(String phaseName, String name, boolean shutdownOnError//,
/*Path fieldsOut, Path methodsOut, Path stringConstOut, Path usesOut*/) {
super(phaseName, name, shutdownOnError);
/*this.fieldsOut = fieldsOut;
this.methodsOut = methodsOut;
this.stringConstOut = stringConstOut;
this.usesOut = usesOut;*/
/*this.fields = new HashSet<>();
this.methods = new HashSet<>();
this.stringConstToUses = new HashMap<>();
this.startToUses = new HashMap<>();*/
}
@Override
protected void endWorker(Worker w) {
/*DefUseGraphMakerRunner runner = (DefUseGraphMakerRunner)w.getRunner();
if(!isShutdown) {
synchronized (fields) {
Set<String> f = runner.getFields();
if(f != null)
fields.addAll(f);
}
synchronized (methods) {
Set<String> m = runner.getMethods();
if(m != null)
methods.addAll(m);
}
synchronized (stringConstToUses) {
Map<String,Set<String>> stringConsts = runner.getStringConsts();
if(stringConsts != null) {
for(String s : stringConsts.keySet()) {
Set<String> temp = stringConstToUses.get(s);
if(temp == null) {
temp = new HashSet<>();
stringConstToUses.put(s,temp);
}
temp.addAll(stringConsts.get(s));
}
}
}
synchronized (startToUses) {
Map<String,Set<String>> values = runner.getValues();
if(values != null) {
for(String s : values.keySet()) {
Set<String> temp = startToUses.get(s);
if(temp == null) {
temp = new HashSet<>();
startToUses.put(s,temp);
}
temp.addAll(values.get(s));
}
}
}
}
runner.clearData();*/
super.endWorker(w);
}
@Override
protected void endGroup() {
/*synchronized (fields) {
writeFields(fields,fieldsOut,name,logger);
fields = null;
}
synchronized (methods) {
writeMethods(methods,methodsOut,name,logger);
methods = null;
}
synchronized (stringConstToUses) {
writeStringConst(stringConstToUses, stringConstOut, name, logger);
stringConstToUses = null;
}
synchronized (startToUses) {
writeValues(startToUses, usesOut, name, logger);
startToUses = null;
}*/
super.endGroup();
}
}
private class DefUseGraphMakerRunner implements Runnable {
private final EntryPoint ep;
private final JimpleICFG baseICFG;
private final ILogger logger;
private final DefUseGraphMaker vtm;
/*private volatile Set<String> fields;
private volatile Set<String> methods;
private volatile Map<String,Set<String>> stringConsts;
private volatile Map<String,Set<String>> startToUses;*/
public DefUseGraphMakerRunner(EntryPoint ep, JimpleICFG baseICFG,
DefUseGraphMaker vtm, ILogger logger) {
this.ep = ep;
this.baseICFG = baseICFG;
this.logger = logger;
this.vtm = vtm;
/*this.fields = null;
this.methods = null;
this.stringConsts = null;
this.startToUses = null;*/
}
@Override
public void run() {
IExcludeHandler excludeHandler = null;
IJimpleICFG icfg = null;
logger.fineInfo("{}: Begin making def use graphs for ep '{}'.",name,ep);
try{
excludeHandler = dataAccessor.getExcludedElementsDB().createNewExcludeHandler(ep);
icfg = new ExcludingJimpleICFG(ep, baseICFG, new ExcludingEdgePredicate(baseICFG.getCallGraph(), excludeHandler));
DefUseGraph defUseGraph = vtm.makeDefUseGraphs(dataAccessor.getControlPredicatesDB().getUnits(ep), ep, icfg, logger);
try {
dataAccessor.getDefUseGraphDB().writeAndAddDefUseGraph(ep, defUseGraph, dataAccessor.getConfig().getFilePath("acminer_defusegraph-dir"));
} catch(Throwable t) {
logger.fatal("{}: An error occured in writing the DefUseGraph for '{}'.",t,name,ep);
throw new IgnorableRuntimeException();
}
/*logger.fineInfo("{}: Initilizing the def use graph for '{}'.",name,ep.toString());
defUseGraph.resolveStartNodeToDefStrings();
logger.fineInfo("{}: Successfully initilized the def use graph for '{}'.",name,ep.toString());
Triple<Set<String>, Set<String>, Map<String, Set<String>>> data = vtm.gatherData(defUseGraph, ep, logger);
this.fields = data.getFirst();
this.methods = data.getSecond();
this.stringConsts = data.getThird();
this.startToUses = new HashMap<>();
Map<StartNode, Set<String>> startNodesToDefStrings = defUseGraph.getStartNodesToDefStrings();
for(StartNode sn : startNodesToDefStrings.keySet()) {
String key = "Stmt: " + sn.toString() + " Source: " + sn.getSource();
Set<String> temp = startToUses.get(key);
if(temp == null) {
temp = new HashSet<>();
startToUses.put(key, temp);
}
temp.addAll(startNodesToDefStrings.get(sn));
}
defUseGraph.clearStartNodesToDefStrings();//Free up memory now that we don't need to store these anymore
writeValues();
writeFields();
writeMethods();
writeStringConst();
addFields();
addMethods();
addStringConst();
addValues();*/
logger.fineInfo("{}: The def use graph maker succeeded for ep '{}'.",name,ep);
} catch(IgnorableRuntimeException t) {
throw t;
} catch(Throwable t) {
logger.fatal("{}: An unexpected error occured in the def use graph maker for ep '{}'.",t,ep);
throw new IgnorableRuntimeException();
}
}
/*public void clearData() {
this.fields = null;
this.methods = null;
this.stringConsts = null;
this.startToUses = null;
}
public Set<String> getFields() {return fields;}
public Set<String> getMethods() {return methods;}
public Map<String,Set<String>> getStringConsts() {return stringConsts;}
public Map<String,Set<String>> getValues() {return startToUses;}
private void addFields() {
synchronized (allFields) {
allFields.addAll(fields);
}
}
private void addMethods() {
synchronized (allMethods) {
allMethods.addAll(methods);
}
}
private void addStringConst() {
synchronized (allStringConst) {
for(String stringConst : stringConsts.keySet()) {
Set<String> temp = allStringConst.get(stringConst);
if(temp == null) {
temp = new HashSet<>();
allStringConst.put(stringConst, temp);
}
temp.addAll(stringConsts.get(stringConst));
}
}
}*/
/*private void addValues() {
synchronized (allValues) {
for(String s : startToUses.keySet()) {
Set<String> temp = allValues.get(s);
if(temp == null) {
temp = new HashSet<>();
allValues.put(s, temp);
}
temp.addAll(startToUses.get(s));
}
}
}
private void writeFields() {
Path p = stubToFieldOutput.get(stub);
synchronized (p) {
try (PrintStreamUnixEOL ps = new PrintStreamUnixEOL(Files.newOutputStream(p,StandardOpenOption.APPEND,
StandardOpenOption.CREATE,StandardOpenOption.WRITE))) {
ps.println("Entry Point: " + ep.toString());
for(String s : fields) {
ps.println(" Field: " + s);
}
} catch(Throwable t) {
logger.fatal("{}: An error occured when writing to file '{}' for '{}' of '{}'.",name,p,stub,ep);
throw new IgnorableRuntimeException();
}
}
}
private void writeMethods() {
Path p = stubToMethodOutput.get(stub);
synchronized (p) {
try (PrintStreamUnixEOL ps = new PrintStreamUnixEOL(Files.newOutputStream(p,StandardOpenOption.APPEND,
StandardOpenOption.CREATE,StandardOpenOption.WRITE))) {
ps.println("Entry Point: " + ep.toString());
for(String s : methods) {
ps.println(" Method: " + s);
}
} catch(Throwable t) {
logger.fatal("{}: An error occured when writing to file '{}' for '{}' of '{}'.",name,p,stub,ep);
throw new IgnorableRuntimeException();
}
}
}
private void writeStringConst() {
Path p = stubToStringConstOutput.get(stub);
synchronized (p) {
try (PrintStreamUnixEOL ps = new PrintStreamUnixEOL(Files.newOutputStream(p,StandardOpenOption.APPEND,
StandardOpenOption.CREATE,StandardOpenOption.WRITE))) {
ps.println("Entry Point: " + ep.toString());
for(String s : stringConsts.keySet()) {
ps.println(" StringConst: " + s);
for(String k : stringConsts.get(s)) {
ps.println(" Use: " + k);
}
}
} catch(Throwable t) {
logger.fatal("{}: An error occured when writing to file '{}' for '{}' of '{}'.",name,p,stub,ep);
throw new IgnorableRuntimeException();
}
}
}
private void writeValues() {
Path p = stubToValueOutput.get(stub);
Map<String,BigInteger> countMap = DefUseGraph.computeAllStatementsCount(startToUses);
BigInteger totalUses = BigInteger.ZERO;
for(BigInteger i : countMap.values()) {
totalUses = totalUses.add(i);
}
synchronized (p) {
try (PrintStreamUnixEOL ps = new PrintStreamUnixEOL(Files.newOutputStream(p,StandardOpenOption.APPEND,
StandardOpenOption.CREATE,StandardOpenOption.WRITE))) {
ps.println("Entry Point: " + ep.toString() +
" Totals: Unique Control Predicates = " + countMap.keySet().size() + ", Unique Uses = " + totalUses.toString());
for(String s : startToUses.keySet()) {
ps.println(" " + s + " Count: " + countMap.get(s).toString());
for(String l : startToUses.get(s)) {
ps.println(" Def: " + l);
}
}
} catch(Throwable t) {
logger.fatal("{}: An error occured when writing to file '{}' for '{}' of '{}'.",name,p,stub,ep);
throw new IgnorableRuntimeException();
}
}
}*/
}
}
| 37.733449 | 142 | 0.695323 |
76952eb5f3f5b11f26881a60bd36af90a1553b42 | 6,304 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.synchronizeaftermerge;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.loadsave.LoadSaveTester;
import org.pentaho.di.trans.steps.loadsave.initializer.InitializerInterface;
import org.pentaho.di.trans.steps.loadsave.validator.ArrayLoadSaveValidator;
import org.pentaho.di.trans.steps.loadsave.validator.BooleanLoadSaveValidator;
import org.pentaho.di.trans.steps.loadsave.validator.FieldLoadSaveValidator;
import org.pentaho.di.trans.steps.loadsave.validator.StringLoadSaveValidator;
public class SynchronizeAfterMergeMetaTest implements InitializerInterface<StepMetaInterface> {
LoadSaveTester loadSaveTester;
Class<SynchronizeAfterMergeMeta> testMetaClass = SynchronizeAfterMergeMeta.class;
@ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment();
@Before
public void setUpLoadSave() throws Exception {
KettleEnvironment.init();
PluginRegistry.init( false );
List<String> attributes =
Arrays.asList( "schemaName", "tableName", "databaseMeta", "commitSize", "tableNameInField", "tablenameField",
"operationOrderField", "useBatchUpdate", "performLookup", "OrderInsert", "OrderUpdate", "OrderDelete",
"keyStream", "keyLookup", "keyCondition", "keyStream2", "updateLookup", "updateStream", "update" );
Map<String, String> getterMap = new HashMap<String, String>() {
{
put( "tableNameInField", "istablenameInField" );
put( "tablenameField", "gettablenameField" );
put( "useBatchUpdate", "useBatchUpdate" );
}
};
Map<String, String> setterMap = new HashMap<String, String>() {
{
put( "tableNameInField", "settablenameInField" );
put( "tablenameField", "settablenameField" );
}
};
FieldLoadSaveValidator<String[]> stringArrayLoadSaveValidator =
new ArrayLoadSaveValidator<String>( new StringLoadSaveValidator(), 5 );
Map<String, FieldLoadSaveValidator<?>> attrValidatorMap = new HashMap<String, FieldLoadSaveValidator<?>>();
attrValidatorMap.put( "keyStream", stringArrayLoadSaveValidator );
attrValidatorMap.put( "keyStream2", stringArrayLoadSaveValidator );
attrValidatorMap.put( "keyLookup", stringArrayLoadSaveValidator );
attrValidatorMap.put( "keyCondition", stringArrayLoadSaveValidator );
attrValidatorMap.put( "updateLookup", stringArrayLoadSaveValidator );
attrValidatorMap.put( "updateStream", stringArrayLoadSaveValidator );
attrValidatorMap.put( "update", new ArrayLoadSaveValidator<Boolean>( new BooleanLoadSaveValidator(), 5 ) );
Map<String, FieldLoadSaveValidator<?>> typeValidatorMap = new HashMap<String, FieldLoadSaveValidator<?>>();
loadSaveTester =
new LoadSaveTester( testMetaClass, attributes, new ArrayList<String>(), new ArrayList<String>(),
getterMap, setterMap, attrValidatorMap, typeValidatorMap, this );
}
// Call the allocate method on the LoadSaveTester meta class
@Override
public void modify( StepMetaInterface someMeta ) {
if ( someMeta instanceof SynchronizeAfterMergeMeta ) {
( (SynchronizeAfterMergeMeta) someMeta ).allocate( 5, 5 );
}
}
@Test
public void testSerialization() throws KettleException {
loadSaveTester.testSerialization();
}
@Test
public void testPDI16559() throws Exception {
SynchronizeAfterMergeMeta synchronizeAfterMerge = new SynchronizeAfterMergeMeta();
synchronizeAfterMerge.setKeyStream( new String[] { "field1", "field2", "field3", "field4", "field5" } );
synchronizeAfterMerge.setKeyLookup( new String[] { "lookup1", "lookup2" } );
synchronizeAfterMerge.setKeyCondition( new String[] { "cond1", "cond2", "cond3" } );
synchronizeAfterMerge.setKeyStream2( new String[] { "stream2-a", "stream2-b", "stream2-x", "stream2-d" } );
synchronizeAfterMerge.setUpdateLookup( new String[] { "updlook1", "updlook2", "updlook3", "updlook4", "updlook5" } );
synchronizeAfterMerge.setUpdateStream( new String[] { "updstr1", "updstr2", "updstr3" } );
synchronizeAfterMerge.setUpdate( new Boolean[] { false, true } );
synchronizeAfterMerge.afterInjectionSynchronization();
String ktrXml = synchronizeAfterMerge.getXML();
int targetSz = synchronizeAfterMerge.getKeyStream().length;
Assert.assertEquals( targetSz, synchronizeAfterMerge.getKeyLookup().length );
Assert.assertEquals( targetSz, synchronizeAfterMerge.getKeyCondition().length );
Assert.assertEquals( targetSz, synchronizeAfterMerge.getKeyStream2().length );
targetSz = synchronizeAfterMerge.getUpdateLookup().length;
Assert.assertEquals( targetSz, synchronizeAfterMerge.getUpdateStream().length );
Assert.assertEquals( targetSz, synchronizeAfterMerge.getUpdate().length );
}
}
| 47.044776 | 122 | 0.703204 |
76d2dc1a9efc91618fffbb29a96e7dd22fed137e | 2,289 | /*
* Copyright 2018 Soojeong Shin
*
* 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.example.android.popularmovies;
import android.content.Context;
import androidx.appcompat.widget.AppCompatImageView;
import android.util.AttributeSet;
import static com.example.android.popularmovies.utilities.Constant.THREE;
import static com.example.android.popularmovies.utilities.Constant.TWO;
/**
* The TwoThreeImageView class is responsible for making ImageView 2:3 aspect ratio.
* The TwoThreeImageView is used for movie poster in the movie_list_item.xml.
*/
public class TwoThreeImageView extends AppCompatImageView {
/**
* Creates a TwoThreeImageView
*
* @param context Used to talk to the UI and app resources
*/
public TwoThreeImageView(Context context) {
super(context);
}
public TwoThreeImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TwoThreeImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* This method measures the view and its content to determine the measured width and the measured
* height, which will make 2:3 aspect ratio.
*
* @param widthMeasureSpec horizontal space requirements as imposed by the parent
* @param heightMeasureSpec vertical space requirements as imposed by th parent
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int twoThreeHeight = MeasureSpec.getSize(widthMeasureSpec) * THREE / TWO;
int twoThreeHeightSpec =
MeasureSpec.makeMeasureSpec(twoThreeHeight, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, twoThreeHeightSpec);
}
}
| 35.765625 | 101 | 0.730013 |
7b6ec2239e0df525f3b7aa2ffc5ba59180617aa7 | 4,466 | /**
* 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 com.wipro.ats.bdre.imcrawler.examples.localdata;
import com.wipro.ats.bdre.BaseStructure;
import com.wipro.ats.bdre.imcrawler.crawler.CrawlConfig;
import com.wipro.ats.bdre.imcrawler.crawler.CrawlController;
import com.wipro.ats.bdre.imcrawler.fetcher.PageFetcher;
import com.wipro.ats.bdre.imcrawler.robotstxt.RobotstxtConfig;
import com.wipro.ats.bdre.imcrawler.robotstxt.RobotstxtServer;
import org.apache.commons.cli.CommandLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class LocalDataCollectorController extends BaseStructure {
private static final Logger logger = LoggerFactory.getLogger(LocalDataCollectorController.class);
private static final String[][] PARAMS_STRUCTURE = {
{"r", "root-folder", "rootFolder that contains intermediate crawl data"},
{"t", "num-threads", "No. of concurrent threads to be run"},
{"p", "parent-process-id", "Process Id of the process to begin"},
{"i", "instance-exec-id", "Instance Exec Id for the process"},
};
public static void main(String[] args) throws Exception {
CommandLine commandLine = new LocalDataCollectorController().getCommandLine(args, PARAMS_STRUCTURE);
String rootFolder = commandLine.getOptionValue("root-folder");
logger.debug("root Folder path is " + rootFolder);
String numThread = commandLine.getOptionValue("num-threads");
logger.debug("numberOfCrawlers (number of concurrent threads) " + numThread);
int pid = Integer.parseInt(commandLine.getOptionValue("parent-process-id"));
logger.debug("processId is " + pid);
int instanceExecid = Integer.parseInt(commandLine.getOptionValue("instance-exec-id"));
logger.debug("instanceExec Id is " + instanceExecid);
// if (args.length != 4) {
// logger.info("Needed parameters: ");
// logger.info("\t rootFolder (it will contain intermediate crawl data)");
// logger.info("\t numberOfCrawlers (number of concurrent threads)");
// logger.info("\t Process Id of the process to begin");
// logger.info("\t Instance Exec Id for the process");
// return;
// }
// String rootFolder = args[0];
int numberOfCrawlers = Integer.parseInt(numThread);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(rootFolder);
config.setMaxPagesToFetch(10);
config.setPolitenessDelay(1000);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer, pid, instanceExecid);
controller.addSeed("http://www.ics.uci.edu/");
controller.start(LocalDataCollectorCrawler.class, numberOfCrawlers);
List<Object> crawlersLocalData = controller.getCrawlersLocalData();
long totalLinks = 0;
long totalTextSize = 0;
int totalProcessedPages = 0;
for (Object localData : crawlersLocalData) {
CrawlStat stat = (CrawlStat) localData;
totalLinks += stat.getTotalLinks();
totalTextSize += stat.getTotalTextSize();
totalProcessedPages += stat.getTotalProcessedPages();
}
logger.info("Aggregated Statistics:");
logger.info("\tProcessed Pages: {}", totalProcessedPages);
logger.info("\tTotal Links found: {}", totalLinks);
logger.info("\tTotal Text Size: {}", totalTextSize);
}
} | 48.021505 | 116 | 0.701747 |
7bf2276b8501d6d3692e5c2c4a0ff507af4c1d51 | 790 | package standard.builder;
import standard.accessories.BatteryEnum;
import standard.accessories.ScreenEnum;
import standard.accessories.WebcamEnum;
import standard.instance.HuaweiPhone;
/**
* @author 霖
*/
public class HuaweiPhoneBuilder implements Builder<HuaweiPhone> {
private BatteryEnum battery;
private ScreenEnum screen;
private WebcamEnum webcam;
@Override
public void setScreen(ScreenEnum screen) {
this.screen = screen;
}
@Override
public void setWebcam(WebcamEnum webcam) {
this.webcam = webcam;
}
@Override
public void setBattery(BatteryEnum battery) {
this.battery = battery;
}
@Override
public HuaweiPhone getInstance() {
return new HuaweiPhone(battery, screen, webcam);
}
}
| 20.25641 | 65 | 0.7 |
cddce4c36ced0e0ac52ddbdb7a25affd42e03fb1 | 5,439 | /*
* Copyright 2018 The GraphicsFuzz Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphicsfuzz.glesworker;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.utils.BufferUtils;
import java.nio.IntBuffer;
import com.graphicsfuzz.repackaged.com.google.gson.JsonArray;
import com.graphicsfuzz.repackaged.com.google.gson.JsonObject;
public class PlatformInfoUtil {
private static String getProperty(String prop) {
String res = System.getProperty(prop);
return res == null ? "" : res;
}
public static void getGlVersionInfo(JsonObject platformInfoJson, GL30 gl30) {
BufferUtils.newIntBuffer(16);
platformInfoJson.addProperty("GL_VERSION", Gdx.gl.glGetString(GL20.GL_VERSION));
platformInfoJson.addProperty("GL_SHADING_LANGUAGE_VERSION", Gdx.gl.glGetString(GL20.GL_SHADING_LANGUAGE_VERSION));
platformInfoJson.addProperty("GL_VENDOR", Gdx.gl.glGetString(GL20.GL_VENDOR));
platformInfoJson.addProperty("GL_RENDERER", Gdx.gl.glGetString(GL20.GL_RENDERER));
IntBuffer buff = BufferUtils.newIntBuffer(16);
buff.clear();
Gdx.gl.glGetIntegerv(GL30.GL_MAJOR_VERSION, buff);
platformInfoJson.addProperty("GL_MAJOR_VERSION", buff.get(0));
buff.clear();
Gdx.gl.glGetIntegerv(GL30.GL_MINOR_VERSION, buff);
platformInfoJson.addProperty("GL_MINOR_VERSION", buff.get(0));
JsonArray array = new JsonArray();
try {
final int GL_NUM_SHADING_LANGUAGE_VERSIONS = 0x82E9;
buff.clear();
Gdx.gl.glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, buff);
if(Gdx.gl.glGetError() == GL20.GL_NO_ERROR && gl30 != null) {
int size = buff.get(0);
for(int i=0; i < size; ++i) {
array.add(gl30.glGetStringi(GL20.GL_SHADING_LANGUAGE_VERSION, i));
}
}
}
catch (IllegalStateException e) {
// The above may not work depending what OpenGL version is supported.
}
platformInfoJson.add("Supported_GLSL_versions", array);
}
public static void getPlatformDetails(JsonObject platformInfoJson) {
// Libgdx specific:
platformInfoJson.addProperty("clientplatform", Gdx.app.getType().toString().toLowerCase());
// System.getProperty:
platformInfoJson.addProperty("http.agent", getProperty("http.agent"));
platformInfoJson.addProperty("java.class.version", getProperty("java.class.version"));
platformInfoJson.addProperty("java.runtime.name", getProperty("java.runtime.name"));
platformInfoJson.addProperty("java.runtime.version", getProperty("java.runtime.version"));
platformInfoJson.addProperty("java.vendor", getProperty("java.vendor"));
platformInfoJson.addProperty("java.version", getProperty("java.version"));
// Don't include this, as it can vary, and it isn't particularly useful information.
// platformInfoJson.addProperty("java.vm.info", getProperty("java.vm.info"));
platformInfoJson.addProperty("java.vm.name", getProperty("java.vm.name"));
platformInfoJson.addProperty("java.vm.specification.vendor", getProperty("java.vm.specification.vendor"));
platformInfoJson.addProperty("java.vm.specification.name", getProperty("java.vm.specification.name"));
platformInfoJson.addProperty("java.vm.vendor", getProperty("java.vm.vendor"));
platformInfoJson.addProperty("java.vm.vendor.url", getProperty("java.vm.vendor.url"));
platformInfoJson.addProperty("java.vm.version", getProperty("java.vm.version"));
platformInfoJson.addProperty("java.specification.name", getProperty("java.specification.name"));
platformInfoJson.addProperty("java.specification.vendor", getProperty("java.specification.vendor"));
platformInfoJson.addProperty("java.specification.version", getProperty("java.specification.version"));
platformInfoJson.addProperty("os.arch", getProperty("os.arch"));
platformInfoJson.addProperty("os.name", getProperty("os.name"));
platformInfoJson.addProperty("os.version", getProperty("os.version"));
platformInfoJson.addProperty("sun.cpu.endian", getProperty("sun.cpu.endian"));
platformInfoJson.addProperty("sun.io.unicode.encoding", getProperty("sun.io.unicode.encoding"));
platformInfoJson.addProperty("sun.desktop", getProperty("sun.desktop"));
platformInfoJson.addProperty("sun.java.launcher", getProperty("sun.java.launcher"));
platformInfoJson.addProperty("sun.cpu.isalist", getProperty("sun.cpu.isalist"));
platformInfoJson.addProperty("sun.os.patch.level", getProperty("sun.os.patch.level"));
platformInfoJson.addProperty("sun.management.compiler", getProperty("sun.management.compiler"));
platformInfoJson.addProperty("sun.arch.data.model", getProperty("sun.arch.data.model"));
platformInfoJson.addProperty("user.region", getProperty("user.region"));
platformInfoJson.addProperty("user.language", getProperty("user.language"));
}
}
| 47.295652 | 118 | 0.745174 |
a11c0b8d6f078cdca7f7656679273df6d12a6d30 | 1,102 | package com.eklanku.otuChat.ui.activities.payment.models;
import com.google.gson.annotations.SerializedName;
public class DataDetailSaldoBonus {
@SerializedName("id_member")
private String id_member;
public String getId_member() {
return id_member;
}
public void setId_member(String id_member) {
this.id_member = id_member;
}
public String getSisa_uang() {
return sisa_uang;
}
public void setSisa_uang(String sisa_uang) {
this.sisa_uang = sisa_uang;
}
public String getCarier_member() {
return carier_member;
}
public void setCarier_member(String carier_member) {
this.carier_member = carier_member;
}
public String getBonus_member() {
return bonus_member;
}
public void setBonus_member(String bonus_member) {
this.bonus_member = bonus_member;
}
@SerializedName("sisa_uang")
private String sisa_uang;
@SerializedName("carier_member")
private String carier_member;
@SerializedName("bonus_member")
private String bonus_member;
}
| 21.192308 | 57 | 0.682396 |
82bf5ec101cad280dc6c8a338e7830ab3f5ffa19 | 1,297 | /*
* Copyright (C) 2010-2101 Alibaba Group Holding Limited.
*
* 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.alibaba.otter.node.etl.transform.transformer;
import com.alibaba.otter.shared.etl.model.FileData;
/**
* {@linkplain FileData}数据对象转化
*
* @author jianghang 2011-10-27 下午06:31:15
* @version 4.0.0
*/
public class FileDataTransformer extends AbstractOtterTransformer<FileData, FileData> {
public FileData transform(FileData data, OtterTransformerContext context) {
// 后续可以针对文件进行目标地的fileResolver解析
if (context.getDataMediaPair().getId().equals(data.getPairId())) {
return data;
} else {
return null;
}
// data.setPairId(context.getDataMediaPair().getId());
// return data;
}
}
| 31.634146 | 87 | 0.701619 |
53e42b0950a619acc7a2e5094c6d80b13442c7b7 | 2,119 | /*
* Copyright 2016-present MongoDB, 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.mongodb.benchmark.framework;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BenchmarkResult {
private final String name;
private final List<Long> elapsedTimeNanosList;
private final List<Long> sortedElapsedTimeNanosList;
private final int bytesPerRun;
public BenchmarkResult(final String name, final List<Long> elapsedTimeNanosList, final int bytesPerRun) {
this.name = name;
this.elapsedTimeNanosList = new ArrayList<Long>(elapsedTimeNanosList);
this.bytesPerRun = bytesPerRun;
this.sortedElapsedTimeNanosList = new ArrayList<Long>(elapsedTimeNanosList);
Collections.sort(this.sortedElapsedTimeNanosList);
}
public int getBytesPerIteration() {
return bytesPerRun;
}
public String getName() {
return name;
}
public List<Long> getElapsedTimeNanosList() {
return elapsedTimeNanosList;
}
public long getElapsedTimeNanosAtPercentile(final int percentile) {
return sortedElapsedTimeNanosList.get(Math.max(0, ((int) (getNumIterations() * percentile / 100.0)) - 1));
}
public int getNumIterations() {
return elapsedTimeNanosList.size();
}
@Override
public String toString() {
return "BenchmarkResult{" +
"name='" + name + '\'' +
", elapsedTimeNanosList=" + elapsedTimeNanosList +
", bytesPerRun=" + bytesPerRun +
'}';
}
}
| 31.626866 | 114 | 0.685229 |
d2e68e22ffa5d960a38a0e34aba2fbc5d3c9ac12 | 211 | package edu.berkeley.cs186.database.index;
@SuppressWarnings("serial")
public class BPlusTreeException extends RuntimeException {
public BPlusTreeException(String message) {
super(message);
}
}
| 23.444444 | 58 | 0.753555 |
d9ec8072aa19e0f7124ae72dd80b039dbee7a32b | 480 | package alibaba;
import java.util.ArrayList;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String s = sc.nextLine();
list.add(s);
}
System.out.println(list);
}
public static int xs(String s){
return 0;
}
}
| 21.818182 | 51 | 0.545833 |
37a4cd839ba24e52ffc22e5947486fc534dfc422 | 1,123 | package com.neu.autoparams.util;
import java.util.HashMap;
import java.util.Map;
public class RestResponse {
private static final String RESULT_KEY = "result";
private static final String MESSAGE_KEY = "message";
private static final String DATA_KEY = "data";
private GlobalResponseCode responseCode;
private Map<String, Object> additionalData = new HashMap<>();
private RestResponse(GlobalResponseCode responseCode) {
this.responseCode = responseCode;
}
public static RestResponse create(GlobalResponseCode responseCode) {
return new RestResponse(responseCode);
}
public RestResponse put(String key, Object data) {
this.additionalData.put(key, data);
return this;
}
public RestResponse putData(Object data) {
this.additionalData.put(DATA_KEY, data);
return this;
}
public Map<String, Object> build() {
return new HashMap<String, Object>() {{
put(RESULT_KEY, responseCode);
put(MESSAGE_KEY, responseCode.getMessage());
putAll(additionalData);
}};
}
}
| 25.522727 | 72 | 0.667854 |
76e98075b077f4db94650c68564f3061518edde3 | 1,065 | package com.ceiba.evento.adaptador.dao;
import com.ceiba.evento.modelo.dto.DtoEvento;
import com.ceiba.infraestructura.jdbc.MapperResult;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
public class MapeoEvento implements RowMapper<DtoEvento>, MapperResult {
@Override
public DtoEvento mapRow(ResultSet rs, int rowNum) throws SQLException {
Long id = rs.getLong("id");
String nombre = rs.getString("nombre");
String direccion = rs.getString("direccion");
//Int to double validate
Double valorEntrada = rs.getDouble("valor_entrada");
Long numeroBoletas = rs.getLong("numero_boletas");
Boolean exigeCarnet = rs.getBoolean("exige_carnet");
LocalDate fechaInicio = this.extraerLocalDate(rs, "fecha_inicio");
LocalDate fechaCierre = this.extraerLocalDate(rs, "fecha_cierre");
return new DtoEvento(id,nombre,direccion,valorEntrada,numeroBoletas,exigeCarnet,fechaInicio,fechaCierre);
}
}
| 35.5 | 113 | 0.733333 |
27ee4ddedcfab76ebc716242abad5cd0492487ee | 3,753 | /*
* 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.flink.table.planner.calcite;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.util.TimestampString;
/** A slim extension over a {@link RexBuilder}. See the overridden methods for more explanation. */
public final class FlinkRexBuilder extends RexBuilder {
public FlinkRexBuilder(RelDataTypeFactory typeFactory) {
super(typeFactory);
}
/**
* Compared to the original method we adjust the nullability of the nested column based on the
* nullability of the enclosing type.
*
* <p>If the fields type is NOT NULL, but the enclosing ROW is nullable we still can produce
* nulls.
*/
@Override
public RexNode makeFieldAccess(RexNode expr, String fieldName, boolean caseSensitive) {
RexNode field = super.makeFieldAccess(expr, fieldName, caseSensitive);
if (expr.getType().isNullable() && !field.getType().isNullable()) {
return makeCast(
typeFactory.createTypeWithNullability(field.getType(), true), field, true);
}
return field;
}
/**
* Compared to the original method we adjust the nullability of the nested column based on the
* nullability of the enclosing type.
*
* <p>If the fields type is NOT NULL, but the enclosing ROW is nullable we still can produce
* nulls.
*/
@Override
public RexNode makeFieldAccess(RexNode expr, int i) {
RexNode field = super.makeFieldAccess(expr, i);
if (expr.getType().isNullable() && !field.getType().isNullable()) {
return makeCast(
typeFactory.createTypeWithNullability(field.getType(), true), field, true);
}
return field;
}
/**
* Creates a literal of the default value for the given type.
*
* <p>This value is:
*
* <ul>
* <li>0 for numeric types;
* <li>FALSE for BOOLEAN;
* <li>The epoch for TIMESTAMP and DATE;
* <li>Midnight for TIME;
* <li>The empty string for string types (CHAR, BINARY, VARCHAR, VARBINARY).
* </ul>
*
* <p>Uses '1970-01-01 00:00:00'(epoch 0 second) as zero value for TIMESTAMP_LTZ, the zero value
* '0000-00-00 00:00:00' in Calcite is an invalid time whose month and day is invalid, we
* workaround here. Stop overriding once CALCITE-4555 fixed.
*
* @param type Type
* @return Simple literal, or cast simple literal
*/
@Override
public RexNode makeZeroLiteral(RelDataType type) {
switch (type.getSqlTypeName()) {
case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
return makeLiteral(new TimestampString(1970, 1, 1, 0, 0, 0), type, false);
default:
return super.makeZeroLiteral(type);
}
}
}
| 37.909091 | 100 | 0.669598 |
1fa1187cd3ee25995e7fb7ac4328590cb3918882 | 2,324 | /*******************************************************************************
* Copyright 2014, 2017 gwt-ol3
*
* 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 ol;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import jsinterop.base.JsArrayLike;
/**
* An array of three numbers representing the location of a tile in a tile grid.
* The order is z, x, and y. z is the zoom level.
*/
@JsType(isNative = true, name = "Array", namespace = JsPackage.GLOBAL)
public class TileCoord implements JsArrayLike<Double> {
/**
* @param z zoom
* @param x X-coordinate
* @param y Y-coordinate
*/
public TileCoord(double z, double x, double y) {}
/**
* Clones this object.
*
* @return {ol.TileCoord} clone
*/
@JsOverlay
public final TileCoord cloneObject() {
return this.slice(0);
};
private native TileCoord slice(int begin);
/**
* Gets the zoom.
*
* @return zoom
*/
@JsOverlay
public final double getZ() {
if (this.getLength() > 0) {
return this.getAt(0);
}
return Double.NaN;
};
/**
* Gets the x.
*
* @return x
*/
@JsOverlay
public final double getX() {
if (this.getLength() > 1) {
return this.getAt(1);
}
return Double.NaN;
};
/**
* Gets the y.
*
* @return y
*/
@JsOverlay
public final double getY() {
if (this.getLength() > 2) {
return this.getAt(2);
}
return Double.NaN;
};
}
| 26.11236 | 82 | 0.543029 |
6139a5c6e106777831b38d4312b44312cd079023 | 7,791 | /**
* 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.pulsar.functions.worker.service.api;
import java.io.InputStream;
import java.net.URI;
import java.util.List;
import javax.ws.rs.core.StreamingOutput;
import org.apache.pulsar.broker.authentication.AuthenticationDataHttps;
import org.apache.pulsar.broker.authentication.AuthenticationDataSource;
import org.apache.pulsar.common.functions.FunctionConfig;
import org.apache.pulsar.common.functions.FunctionState;
import org.apache.pulsar.common.io.ConnectorDefinition;
import org.apache.pulsar.common.policies.data.FunctionStats;
import org.apache.pulsar.common.policies.data.FunctionStats.FunctionInstanceStats.FunctionInstanceStatsData;
import org.apache.pulsar.functions.worker.WorkerService;
/**
* Provide service API to access components.
* @param <W> worker service type
*/
public interface Component<W extends WorkerService> {
W worker();
void deregisterFunction(final String tenant,
final String namespace,
final String componentName,
final String clientRole,
AuthenticationDataHttps clientAuthenticationDataHttps);
FunctionConfig getFunctionInfo(final String tenant,
final String namespace,
final String componentName,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
void stopFunctionInstance(final String tenant,
final String namespace,
final String componentName,
final String instanceId,
final URI uri,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
void startFunctionInstance(final String tenant,
final String namespace,
final String componentName,
final String instanceId,
final URI uri,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
void restartFunctionInstance(final String tenant,
final String namespace,
final String componentName,
final String instanceId,
final URI uri,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
void startFunctionInstances(final String tenant,
final String namespace,
final String componentName,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
void stopFunctionInstances(final String tenant,
final String namespace,
final String componentName,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
void restartFunctionInstances(final String tenant,
final String namespace,
final String componentName,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
FunctionStats getFunctionStats(final String tenant,
final String namespace,
final String componentName,
final URI uri,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
FunctionInstanceStatsData getFunctionsInstanceStats(final String tenant,
final String namespace,
final String componentName,
final String instanceId,
final URI uri,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
String triggerFunction(final String tenant,
final String namespace,
final String functionName,
final String input,
final InputStream uploadedInputStream,
final String topic,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
List<String> listFunctions(final String tenant,
final String namespace,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
FunctionState getFunctionState(final String tenant,
final String namespace,
final String functionName,
final String key,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
void putFunctionState(final String tenant,
final String namespace,
final String functionName,
final String key,
final FunctionState state,
final String clientRole,
final AuthenticationDataSource clientAuthenticationDataHttps);
void uploadFunction(final InputStream uploadedInputStream,
final String path,
String clientRole);
StreamingOutput downloadFunction(String path,
String clientRole,
AuthenticationDataHttps clientAuthenticationDataHttps);
StreamingOutput downloadFunction(String tenant,
String namespace,
String componentName,
String clientRole,
AuthenticationDataHttps clientAuthenticationDataHttps);
List<ConnectorDefinition> getListOfConnectors();
void reloadConnectors(String clientRole);
}
| 49 | 118 | 0.552946 |
d01eafd7378a7750b8066c43d81ff297e3d46321 | 376 | package com.github.vole.mps.model.dto;
import com.github.vole.mps.model.entity.Member;
import lombok.Data;
import java.io.Serializable;
@Data
public class MemberInfo implements Serializable {
/**
* 用户基本信息
*/
private Member member;
/**
* 权限标识集合
*/
private String[] permissions;
/**
* 角色集合
*/
private String[] roles;
}
| 15.04 | 49 | 0.62234 |
c9310135697c4b47d5215c1cd8e56326f56b3036 | 1,553 | package com.juja.patterns.objectpool.sampleConnectionPool.case2_withFactory;
import java.util.LinkedList;
import java.util.Queue;
// это наш пул ресурсов
// (тут все так же как в примере classic.case1_simple.ObjectPool
// за исключением строк, помеченных как /*!!*/)
public class ObjectPool {
// он хранит список ресурсов, которые создавались заранее
private Queue<Resource> pool = new LinkedList<Resource>();
// сохранили нашу фабрику, потом из нее извлекать будем ресурсы
private ObjectFactory factory; /*!!*/
// в кострукторе указывается, максимальное количество создаваемых ресурсов
public ObjectPool(ObjectFactory factory) {
// тут если ты заметил мы ничего не делаем
// инициализировать ресурсы из фектори будем позже (lazy initialization)
this.factory = factory; /*!!*/
}
// этим методом мы извлекаем ресурсы для работы с ними
public Resource get() {
Resource resource = pool.poll();
// но если вдруг ресурсов не хватает - тогда дергаем за фектори!
if (resource == null) {
resource = factory.createResource(); /*!!*/
}
System.out.println("get " + resource + " from pool");
return resource;
}
// этим методом мы возвращаем ресурс на место (если его там нет),
// чтобы его можно было повторно использовать
public void put(Resource resource) {
if (!pool.contains(resource)) {
System.out.println("put " + resource + " to pool");
pool.add(resource);
}
}
}
| 33.76087 | 80 | 0.658081 |
202cc297b7b5020e61020434a087dcd722c444f9 | 2,054 | package it.pwned.telegram.bot.api.type.inline;
import com.fasterxml.jackson.annotation.JsonProperty;
import it.pwned.telegram.bot.api.type.Location;
import it.pwned.telegram.bot.api.type.User;
/**
* This object represents an incoming inline query. When the user sends an empty
* query, your bot could return some default or trending results.
*
*/
public class InlineQuery {
private final static String JSON_FIELD_ID = "id";
private final static String JSON_FIELD_FROM = "from";
private final static String JSON_FIELD_LOCATION = "location";
private final static String JSON_FIELD_QUERY = "query";
private final static String JSON_FIELD_OFFSET = "offset";
/**
* Unique identifier for this query
*/
@JsonProperty(JSON_FIELD_ID)
public final String id;
/**
* Sender
*/
@JsonProperty(JSON_FIELD_FROM)
public final User from;
/**
* <em>Optional.</em> Sender location, only for bots that request user
* location
*/
@JsonProperty(JSON_FIELD_LOCATION)
public final Location location;
/**
* Text of the query (up to 512 characters)
*/
@JsonProperty(JSON_FIELD_QUERY)
public final String query;
/**
* Offset of the results to be returned, can be controlled by the bot
*/
@JsonProperty(JSON_FIELD_OFFSET)
public final String offset;
/**
*
* @param id
* Unique identifier for this query
* @param from
* Sender
* @param location
* <em>Optional.</em> Sender location, only for bots that request
* user location
* @param query
* Text of the query (up to 512 characters)
* @param offset
* Offset of the results to be returned, can be controlled by the bot
*/
public InlineQuery(@JsonProperty(JSON_FIELD_ID) String id, @JsonProperty(JSON_FIELD_FROM) User from,
@JsonProperty(JSON_FIELD_LOCATION) Location location, @JsonProperty(JSON_FIELD_QUERY) String query,
@JsonProperty(JSON_FIELD_OFFSET) String offset) {
this.id = id;
this.from = from;
this.location = location;
this.query = query;
this.offset = offset;
}
}
| 26.675325 | 102 | 0.710321 |
bf7b0725357e5bbbd83463f0a248fe1a8c85cac8 | 4,150 | package com.kwok.util.commons;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* 通过 JedisPool 获取 Jedis。
* 注:使用后调用 returnJedis(jedis) 方法手动关闭 jedis,否则超过最大连接数(maxTotal)会抛异常。
* @author Kwok
*/
public class JedisFactory {
private final static Logger logger = LoggerFactory.getLogger(JedisFactory.class);
private static JedisPool jedisPool;
static{
init();
}
private static void init() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(JedisConfig.MAX_TOTAL);
poolConfig.setMaxIdle(JedisConfig.MAX_IDLE);
poolConfig.setMaxWaitMillis(JedisConfig.MAX_WAIT);
poolConfig.setTestOnBorrow(JedisConfig.TEST_ON_BORROW);
jedisPool = new JedisPool(poolConfig, JedisConfig.HOST, JedisConfig.PORT, JedisConfig.TIMEOUT, JedisConfig.AUTH, JedisConfig.DB_INDEX);
logger.info("初始化Redis连接池 {}", jedisPool);
}
public static Jedis getJedis() {
return jedisPool.getResource();
}
public static Jedis getJedis(int dbIndex) {
Jedis jedis = getJedis();
if (jedis != null) {
jedis.select(dbIndex);
}
return jedis;
}
public static void returnJedis(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
/**
* Jedis 配置信息
* @author Kwok
*/
public static class JedisConfig {
private final static Logger logger = LoggerFactory.getLogger(JedisConfig.class);
/**
* Redis服务器地址
*/
public static String HOST = "localhost";
/**
* Redis的端口号
*/
public static int PORT = 6379;
/**
* 访问密码
*/
public static String AUTH = null;
/**
* 连接Redis服务器超时时间
*/
public static int TIMEOUT = 5000;
/**
* 数据库编号
*/
public static int DB_INDEX = 0;
/**
* 控制一个pool最多有多少个jedis实例,默认值是8。
*/
public static int MAX_TOTAL = 8;
/**
* 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
*/
public static int MAX_IDLE = 8;
/**
* 从 pool 中获取可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException。
*/
public static long MAX_WAIT = -1L;
/**
* 在borrow(获取)一个jedis实例时,是否提前进行validate操作。如果为true,则得到的jedis实例均是可用的。
*/
public static boolean TEST_ON_BORROW = true;
static {
init();
}
public static void init(){
try {
Properties props = new Properties();
InputStream is = JedisConfig.class.getClassLoader().getResourceAsStream("redis.properties");
if(is != null) {
props.load(is);
is.close();
HOST = props.getProperty("redis.host", HOST);
PORT = Integer.parseInt(props.getProperty("redis.port", Integer.valueOf(PORT).toString()));
if(!"".equals(props.getProperty("redis.auth"))){
AUTH = props.getProperty("redis.auth", null);
}
TIMEOUT = Integer.parseInt(props.getProperty("redis.timeout", Integer.valueOf(TIMEOUT).toString()));
DB_INDEX = Integer.parseInt(props.getProperty("redis.db", Integer.valueOf(DB_INDEX).toString()));
MAX_TOTAL = Integer.parseInt(props.getProperty("redis.pool.maxTotal", Integer.valueOf(MAX_TOTAL).toString()));
MAX_IDLE = Integer.parseInt(props.getProperty("redis.pool.maxIdle", Integer.valueOf(MAX_IDLE).toString()));
MAX_WAIT = Long.parseLong(props.getProperty("redis.pool.maxWait", Long.valueOf(MAX_WAIT).toString()));
TEST_ON_BORROW = Boolean.parseBoolean(props.getProperty("redis.pool.testOnBorrow", Boolean.valueOf(TEST_ON_BORROW).toString()));
}else{
logger.info("classpath下未发现'redis.properties'配置文件,加载默认配置...");
}
logger.info(
"加载redis配置信息:[HOST={}, PORT={}, AUTH={}, DB_INDEX={}, MAX_TOTAL={}, MAX_IDLE={}, MAX_WAIT={}, TEST_ON_BORROW={}]",
new Object[] { HOST, PORT, AUTH, DB_INDEX, MAX_TOTAL, MAX_IDLE, MAX_WAIT, TEST_ON_BORROW });
} catch (IOException e) {
logger.error("加载redis配置文件失败 {}", e.getMessage(), e);
}
}
}
public static void main(String[] args) {
Jedis jedis = JedisFactory.getJedis();
jedis.set("key", "hello redis!");
System.out.println(jedis.get("key"));
JedisFactory.returnJedis(jedis);
}
}
| 27.483444 | 137 | 0.691566 |
ddff427d89296c9eab7b233ff62d20c84d75486f | 1,950 | package reactor.groovy.config;
import org.reactivestreams.Processor;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.event.Event;
import reactor.event.registry.Registration;
import reactor.event.registry.Registry;
import reactor.event.routing.ConsumerFilteringRouter;
import reactor.event.routing.ConsumerInvoker;
import reactor.filter.Filter;
import reactor.function.Consumer;
import java.util.List;
/**
* @author Stephane Maldini
*/
public class StreamRouter extends ConsumerFilteringRouter {
private final Registry<Processor<Event<?>, Event<?>>> processorRegistry;
public StreamRouter(Filter filter, ConsumerInvoker consumerInvoker,
Registry<Processor<Event<?>, Event<?>>> processorRegistry) {
super(filter, consumerInvoker);
this.processorRegistry = processorRegistry;
}
@Override
@SuppressWarnings("unchecked")
public <E> void route(final Object key, final E event,
final List<Registration<? extends Consumer<?>>> consumers,
final Consumer<E> completionConsumer,
final Consumer<Throwable> errorConsumer) {
Processor<Event<?>, Event<?>> processor;
for (Registration<? extends Processor<Event<?>, Event<?>>> registration : processorRegistry.select(key)){
processor = registration.getObject();
processor.onNext((Event<?>) event);
processor.subscribe(new Subscriber<Event<?>>() {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Integer.MAX_VALUE);
}
@Override
public void onNext(Event<?> hydratedEvent) {
StreamRouter.super.route(hydratedEvent.getKey(), (E) hydratedEvent, consumers, completionConsumer,
errorConsumer);
}
@Override
public void onComplete() {
}
@Override
public void onError(Throwable cause) {
((Event<?>) event).consumeError(cause);
}
});
}
}
}
| 29.104478 | 107 | 0.710256 |
de01acdc80fc54db0daa6061a72b836d19803d81 | 1,227 | package com.grawhy.www.config;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.script.ScriptTemplateConfigurer;
import org.springframework.web.servlet.view.script.ScriptTemplateViewResolver;
import javax.script.ScriptEngine;
/**
* Created by Frank.Park on 2018. 7. 10..
*/
@Configuration
public class WebTemplateConfiguration {
@Bean
public ViewResolver viewResolver(){
return new ScriptTemplateViewResolver("/static/", ".html");
}
@Bean
public ScriptTemplateConfigurer scriptTemplateConfigurer(ScriptEngine scriptEngine){
ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
configurer.setEngine(scriptEngine);
configurer.setScripts("polyfill.js", "static/static/js/server.js");
configurer.setRenderFunction("render");
configurer.setSharedEngine(true);
return configurer;
}
@Bean
public ScriptEngine scriptEngine(){
return new NashornScriptEngineFactory().getScriptEngine();
}
}
| 33.162162 | 88 | 0.760391 |
1ec07e1c6d9455f4121779300308da8c3bff71b6 | 3,162 | package jwk.minecraft.garden.command;
import static net.minecraft.util.EnumChatFormatting.*;
import jwk.minecraft.garden.ProjectGarden;
import jwk.minecraft.garden.currency.CurrencyYD;
import jwk.minecraft.garden.team.ITeam;
import jwk.minecraft.garden.team.TeamRegistry;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
public class CommandTeamCurrency extends CommandInterface {
public static final String SUBCOMMAND_BALANCE = "잔고";
public static final String SUBCOMMAND_INCREASE = "증감";
public static final String SUBCOMMAND_CHANGE = "변경";
public CommandTeamCurrency() {
super("돈 명령어", "/통장 잔고 <팀이름> 또는 /통장 증감 <팀이름> +/-<값> 또는 /통장 변경 <팀이름> <값>");
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args.length == 0) {
sender.addChatMessage(super.ERR_WRONG_COMMAND);
return;
}
String sub = args[0];
int length = args.length - 1;
if (sub.equals(SUBCOMMAND_BALANCE) && length == 1) {
String teamName = args[1];
ITeam team = TeamRegistry.get(teamName);
if (team == null) {
sender.addChatMessage(ProjectGarden.toFormatted("팀 " + AQUA + teamName + WHITE + " 이(가) 존재하지 않습니다."));
return;
}
long balance = CurrencyYD.INSTANCE.getManager().get(team);
sender.addChatMessage(ProjectGarden.toFormatted("팀 " + AQUA + teamName + WHITE + " 의 잔고는 " + GOLD + balance + " YD " + WHITE + "입니다."));
}
else if (sub.equals(SUBCOMMAND_INCREASE) && length == 2) {
String teamName = args[1];
ITeam team = TeamRegistry.get(teamName);
if (team == null) {
sender.addChatMessage(ProjectGarden.toFormatted("팀 " + AQUA + teamName + WHITE + " 이(가) 존재하지 않습니다."));
return;
}
long value = Long.parseLong(args[2]);
long result = 0L;
if (value == 0) {
sender.addChatMessage(ProjectGarden.toFormatted(AQUA + "증감시킬 금액 " + WHITE + "은 " + RED + "0" + WHITE + " 보다 커야 합니다."));
return;
}
else if (value < 0)
result = CurrencyYD.INSTANCE.getManager().decrease(team, Math.abs(value));
else if (value > 0)
result = CurrencyYD.INSTANCE.getManager().increase(team, value);
sender.addChatMessage(ProjectGarden.toFormatted("팀 " + AQUA + teamName + WHITE + " 의 잔고가 " + YELLOW + value + WHITE + " 만큼 증감되어 " + GOLD + result + " YD " + WHITE + "(으)로 변경되었습니다."));
}
else if (sub.equals(SUBCOMMAND_CHANGE) && length == 2) {
String teamName = args[1];
ITeam team = TeamRegistry.get(teamName);
if (team == null) {
sender.addChatMessage(ProjectGarden.toFormatted("팀 " + AQUA + teamName + WHITE + " 이(가) 존재하지 않습니다."));
return;
}
long value = Long.parseLong(args[2]);
if (value < 0) {
sender.addChatMessage(ProjectGarden.toFormatted(AQUA + "증감시킬 금액 " + WHITE + "은 " + RED + "0" + WHITE + " 이상이어야 합니다."));
return;
}
long prev = CurrencyYD.INSTANCE.getManager().set(team, value);
sender.addChatMessage(ProjectGarden.toFormatted("팀 " + AQUA + teamName + WHITE + " 의 잔고가 " + YELLOW + prev + WHITE + " 에서 " + GOLD + value + " YD " + WHITE + "(으)로 변경되었습니다."));
}
else
sender.addChatMessage(super.ERR_WRONG_COMMAND);
}
}
| 33.284211 | 186 | 0.654649 |
03fe480ffc19437bd3233e513d7b28fb14266b2a | 1,765 | package io.ogi.boid.corealgorithm;
import io.ogi.boid.model.Boid;
import java.util.List;
import java.util.stream.Collectors;
class BoidTransformation {
private BoidTransformation() {}
public static List<Boid> getNeighbors(Boid actualBoid, List<Boid> boids, int range) {
return boids.stream()
.filter(other -> !other.equals(actualBoid))
.filter(other -> closeEnough(actualBoid, other, range))
.collect(Collectors.toList());
}
private static boolean closeEnough(Boid actualBoid, Boid other, int range) {
double distance =
Math.sqrt(
(double)(actualBoid.getX() - other.getX()) * (actualBoid.getX() - other.getX())
+ (actualBoid.getY() - other.getY()) * (actualBoid.getY() - other.getY()));
return distance < range;
}
public static double flyTowardsCenter(int position, double center, double cohesionFactor) {
if (center == 0) {
return position;
}
return (center - position) * cohesionFactor;
}
public static double keepDistance(
int position, List<Integer> otherPositions, double separationFactor) {
int move = otherPositions.stream().mapToInt(other -> (position - other)).sum();
return move * separationFactor;
}
public static double matchVelocity(double averageVelocity, double alignmentFactor) {
if (averageVelocity == 0) {
return 0;
}
return averageVelocity * alignmentFactor;
}
public static double keepWithinBounds(
int position, double velocity, int canvasMargin, int canvasLimit, int speedAdjust) {
if (position < canvasMargin) {
return velocity + speedAdjust;
}
if (position > (canvasLimit - canvasMargin)) {
return velocity - speedAdjust;
}
return velocity;
}
}
| 30.431034 | 93 | 0.674221 |
f9831e9264c1b7eede2b1f2531709298fc4dc77b | 286 | package net.fabricmc.examplemod;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.example.ExampleLib;
public class ExampleMod implements ModInitializer {
@Override
public void onInitialize() {
// Lets make sure we can compile against the lib
ExampleLib.hello();
}
}
| 22 | 51 | 0.77972 |
11b5a296f3086888b56e04537537048fd77ab570 | 2,616 | package com.ratel.modules.logging.aspect;
import com.ratel.framework.utils.RequestHolder;
import com.ratel.framework.utils.SecurityUtils;
import com.ratel.framework.utils.StringUtils;
import com.ratel.framework.utils.ThrowableUtil;
import com.ratel.modules.logging.domain.Log;
import com.ratel.modules.logging.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component
@Aspect
@Slf4j
public class LogAspect {
@Autowired
private LogService logService;
ThreadLocal<Long> currentTime = new ThreadLocal<>();
/**
* 配置切入点
*/
@Pointcut("@annotation(com.ratel.modules.logging.aop.log.Log)")
public void logPointcut() {
// 该方法无方法体,主要为了让同类中其他方法使用此切入点
}
/**
* 配置环绕通知,使用在方法logPointcut()上注册的切入点
*
* @param joinPoint join point for advice
*/
@Around("logPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result;
currentTime.set(System.currentTimeMillis());
result = joinPoint.proceed();
Log log = new Log("INFO", System.currentTimeMillis() - currentTime.get());
currentTime.remove();
HttpServletRequest request = RequestHolder.getHttpServletRequest();
logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), joinPoint, log);
return result;
}
/**
* 配置异常通知
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "logPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
Log log = new Log("ERROR", System.currentTimeMillis() - currentTime.get());
currentTime.remove();
log.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes());
HttpServletRequest request = RequestHolder.getHttpServletRequest();
logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint) joinPoint, log);
}
public String getUsername() {
try {
return SecurityUtils.getUsername();
} catch (Exception e) {
return "";
}
}
}
| 33.113924 | 138 | 0.704128 |
52ffb02b2259cccd7a2494debd34b86166b9aa30 | 561 | package com.unclezs.novel.app.framework.components.cell;
import javafx.scene.control.ListCell;
/**
* listCell
*
* @author blog.unclezs.com
* @date 2021/5/5 19:52
*/
public abstract class BaseListCell<T> extends ListCell<T> {
@Override
protected final void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
setText(null);
} else {
updateItem(item);
}
}
/**
* 更新item
*
* @param item T
*/
protected abstract void updateItem(T item);
}
| 18.096774 | 59 | 0.636364 |
5ac72f7b3cb2a551c65e5e7e72c29275311651f9 | 7,408 | /**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
* <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.springblade.support;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.converts.PostgreSqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 代码生成器配置类
*
* @author Chill
*/
@Data
@Slf4j
public class BladeGenerator {
private String packageName = "org.springblade.test";
private String packageDir = "/blade-ops/blade-codegen/src/main/java";
private String[] tablePrefix = {"blade_"};
private String[] includeTables = {"blade_test"};
private String[] excludeTables = {};
private Boolean hasSuperEntity = Boolean.TRUE;
private String[] superEntityColumns = {"id", "create_time", "create_user", "update_time", "update_user", "status", "is_deleted"};
private Boolean isSwagger2 = Boolean.TRUE;
public void run() {
// 获取配置文件
Properties props = getProperties();
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String outputDir = getOutputDir();
String author = props.getProperty("author");
gc.setOutputDir(outputDir);
gc.setAuthor(author);
gc.setFileOverride(true);
gc.setOpen(false);
/**
* 开启 activeRecord 模式
*/
gc.setActiveRecord(false);
/**
* XML 二级缓存
*/
gc.setEnableCache(false);
/**
* XML ResultMap
*/
gc.setBaseResultMap(true);
/**
* XML columList
*/
gc.setBaseColumnList(true);
/**
* 自定义文件命名,注意 %s 会自动填充表实体属性!
*/
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("I%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
gc.setSwagger2(isSwagger2);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
String driverName = props.getProperty("spring.datasource.driver-class-name");
if (StringUtil.containsAny(driverName, DbType.MYSQL.getDb())) {
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert());
} else {
dsc.setDbType(DbType.POSTGRE_SQL);
dsc.setTypeConvert(new PostgreSqlTypeConvert());
}
dsc.setUrl(props.getProperty("spring.datasource.url"));
dsc.setDriverName(driverName);
dsc.setUsername(props.getProperty("spring.datasource.username"));
dsc.setPassword(props.getProperty("spring.datasource.password"));
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大写命名
// strategy.setDbColumnUnderline(true);//全局下划线命名
/**
* 表名生成策略
*/
strategy.setNaming(NamingStrategy.underline_to_camel);
/**
* 字段名生成策略
*/
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
/**
* 此处可以修改为您的表前缀
*/
strategy.setTablePrefix(tablePrefix);
if (includeTables.length > 0) {
/**
* 需要生成的表
*/
strategy.setInclude(includeTables);
}
if (excludeTables.length > 0) {
/**
* 排除生成的表
*/
strategy.setExclude(excludeTables);
}
if (hasSuperEntity) {
strategy.setSuperEntityClass("org.springblade.core.mp.base.BaseEntity");
strategy.setSuperEntityColumns(superEntityColumns);
strategy.setSuperServiceClass("org.springblade.core.mp.base.BaseService");
strategy.setSuperServiceImplClass("org.springblade.core.mp.base.BaseServiceImpl");
} else {
strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
}
// 自定义 controller 父类
strategy.setSuperControllerClass("org.springblade.core.boot.ctrl.BladeController");
strategy.setEntityBuilderModel(false);
strategy.setEntityLombokModel(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
// 控制台扫描
pc.setModuleName(null);
pc.setParent(packageName);
pc.setController("controller");
pc.setEntity("entity");
pc.setXml("mapper");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/entityVO.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return getOutputDir() + "/" + packageName.replace(".", "/") + "/" + "vo" + "/" + tableInfo.getEntityName() + "VO" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/entityDTO.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return getOutputDir() + "/" + packageName.replace(".", "/") + "/" + "dto" + "/" + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/wrapper.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return getOutputDir() + "/" + packageName.replace(".", "/") + "/" + "wrapper" + "/" + tableInfo.getEntityName() + "Wrapper" + StringPool.DOT_JAVA;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.execute();
}
/**
* 获取配置文件
*
* @return 配置Props
*/
private Properties getProperties() {
// 读取配置文件
Resource resource = new ClassPathResource("generator.properties");
Properties props = new Properties();
try {
props = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
/**
* 生成到项目中
*
* @return outputDir
*/
public String getOutputDir() {
return System.getProperty("user.dir") + packageDir;
}
/**
* 页面生成的文件名
*/
private String getGeneratorViewPath(String viewOutputDir, TableInfo tableInfo, String suffixPath) {
String name = StringUtils.firstToLowerCase(tableInfo.getEntityName());
String path = viewOutputDir + "/" + name + "/" + name + suffixPath;
File viewDir = new File(path).getParentFile();
if (!viewDir.exists()) {
viewDir.mkdirs();
}
return path;
}
}
| 29.632 | 150 | 0.718683 |
67292a0f0a66f8cae82b41f894e10eb8073ce942 | 449 | package io.github.rbxapi.javablox.api.friends.verifiedfriends;
public interface QRVerifiedFriends {
/**
* https://friends.roblox.com/docs#!/VerifiedFriends/delete_v1_friends_verified_qr_session
*
* @return Status code
*/
String deleteSession();
/**
* https://friends.roblox.com/docs#!/VerifiedFriends/post_v1_friends_verified_qr_session
*
* @return Status code
*/
String createSession();
}
| 23.631579 | 94 | 0.685969 |
ff5f1a790c503447a8f203be36d17a831aa79700 | 5,603 | package io.crnk.activiti;
import io.crnk.activiti.internal.repository.FormRelationshipRepository;
import io.crnk.activiti.internal.repository.FormResourceRepository;
import io.crnk.activiti.internal.repository.HistoricProcessInstanceResourceRepository;
import io.crnk.activiti.internal.repository.HistoricTaskResourceRepository;
import io.crnk.activiti.internal.repository.ProcessInstanceResourceRepository;
import io.crnk.activiti.internal.repository.TaskRelationshipRepository;
import io.crnk.activiti.internal.repository.TaskResourceRepository;
import io.crnk.activiti.mapper.ActivitiResourceMapper;
import io.crnk.activiti.resource.FormResource;
import io.crnk.activiti.resource.HistoricProcessInstanceResource;
import io.crnk.activiti.resource.HistoricTaskResource;
import io.crnk.activiti.resource.ProcessInstanceResource;
import io.crnk.activiti.resource.TaskResource;
import io.crnk.core.engine.registry.RegistryEntry;
import io.crnk.core.engine.registry.ResourceRegistry;
import io.crnk.core.exception.RepositoryNotFoundException;
import io.crnk.core.module.Module;
import io.crnk.core.repository.ResourceRepositoryV2;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
public class ActivitiModule implements Module {
private ActivitiModuleConfig config;
private ProcessEngine processEngine;
private ActivitiResourceMapper resourceMapper;
private ModuleContext moduleContext;
public static final ActivitiModule create(ProcessEngine processEngine, ActivitiModuleConfig config) {
return new ActivitiModule(processEngine, config);
}
/**
* contructor for CDI
*/
protected ActivitiModule() {
}
private ActivitiModule(ProcessEngine processEngine, ActivitiModuleConfig config) {
this.processEngine = processEngine;
this.config = config;
}
public <T extends TaskResource> ResourceRepositoryV2<T, String> getTaskRepository(Class<T> resourceClass) {
return getRepository(resourceClass);
}
public <T extends HistoricTaskResource> ResourceRepositoryV2<T, String> getHistoricTaskRepository(Class<T> resourceClass) {
return getRepository(resourceClass);
}
public <T extends FormResource> ResourceRepositoryV2<T, String> getFormRepository(Class<T> resourceClass) {
return getRepository(resourceClass);
}
public <T extends ProcessInstanceResource> ResourceRepositoryV2<T, String> getProcessInstanceRepository(
Class<T> resourceClass) {
return getRepository(resourceClass);
}
public <T extends HistoricProcessInstanceResource> ResourceRepositoryV2<T, String> getHistoricProcessInstanceRepository(
Class<T> resourceClass) {
return getRepository(resourceClass);
}
private <T> ResourceRepositoryV2<T, String> getRepository(Class<T> resourceClass) {
ResourceRegistry resourceRegistry = moduleContext.getResourceRegistry();
RegistryEntry entry = resourceRegistry.getEntry(resourceClass);
if (entry == null) {
throw new RepositoryNotFoundException(resourceClass.getName() + " not registered");
}
return entry.getResourceRepositoryFacade();
}
@Override
public String getModuleName() {
return "activiti";
}
@Override
public void setupModule(ModuleContext context) {
this.moduleContext = context;
TaskService taskService = processEngine.getTaskService();
RuntimeService runtimeService = processEngine.getRuntimeService();
FormService formService = processEngine.getFormService();
resourceMapper = new ActivitiResourceMapper(context.getTypeParser(), config.getDateTimeMapper());
for (ProcessInstanceConfig processInstanceConfig : config.getProcessInstances().values()) {
context.addRepository(
new ProcessInstanceResourceRepository(runtimeService, resourceMapper,
processInstanceConfig.getProcessInstanceClass(), processInstanceConfig.getBaseFilters()));
Class<? extends HistoricProcessInstanceResource> historyClass = processInstanceConfig.getHistoryClass();
if (historyClass != null) {
HistoryService historyService = processEngine.getHistoryService();
context.addRepository(
new HistoricProcessInstanceResourceRepository(historyService, resourceMapper, historyClass,
processInstanceConfig.getBaseFilters())
);
}
for (ProcessInstanceConfig.TaskRelationshipConfig taskRel : processInstanceConfig.getTaskRelationships().values()) {
context.addRepository(new TaskRelationshipRepository(processInstanceConfig.getProcessInstanceClass(),
taskRel.getTaskClass(), taskRel.getRelationshipName(), taskRel.getTaskDefinitionKey()));
}
}
for (TaskRepositoryConfig taskConfig : config.getTasks().values()) {
context.addRepository(new TaskResourceRepository(taskService, resourceMapper,
taskConfig.getTaskClass(), taskConfig.getBaseFilters()));
Class<? extends TaskResource> historyClass = taskConfig.getHistoryClass();
if (historyClass != null) {
HistoryService historyService = processEngine.getHistoryService();
context.addRepository(
new HistoricTaskResourceRepository(historyService, resourceMapper, historyClass,
taskConfig.getBaseFilters())
);
}
Class<? extends FormResource> formClass = taskConfig.getFormClass();
if (formClass != null) {
context.addRepository(new FormResourceRepository(formService, taskService, resourceMapper, formClass));
context.addRepository(new FormRelationshipRepository(taskConfig.getTaskClass(), formClass));
}
}
}
public ActivitiResourceMapper getResourceMapper() {
return resourceMapper;
}
}
| 38.115646 | 124 | 0.806354 |
0c646115b484c1eab39eead41b586211143cc85e | 1,924 | /*
* Copyright 2013 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.google.web.bindery.event.shared.binder;
import com.google.web.bindery.event.shared.EventBus;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for a method that handles events sent through an {@link EventBus}.
* The method must have one parameter, which is usually a subclass of
* {@link GenericEvent}. The method will start receiving events after it is
* connected to the EventBus using an {@link EventBinder}. Only the parameter of
* the method is relevant; the name is ignored. For example, the given method
* will be invoked whenever a ProfileLoadedEvent is fired on the event bus to
* which the {@link EventBinder} was bound:
*
* <pre>
* {@literal @}EventHandler
* void onProfileLoaded(ProfileLoadedEvent event) {
* getView().setEmail(event.getProfile().getEmailAddress());
* getView().showSignoutMenu();
* }
* </pre>
*
* Note that an {@link EventBinder} MUST be used to register these annotations,
* otherwise they will have no effect.
*
* @see EventBinder
* @author ekuefler@google.com (Erik Kuefler)
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EventHandler {}
| 36.301887 | 80 | 0.752079 |
5ce4f8fd6dacba0d3bd86072c6683c52ce4f46cc | 685 | package com.headstorm.interview.database;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
public class App
{
public static void main(String[] args)
{
if (args.length < 1)
{
System.out.println("You must provide a file path to read in!");
return;
}
Gson gson = new Gson();
try (JsonReader reader = new JsonReader(new FileReader(args[0])))
{
PortableData[] port = gson.fromJson(reader, PortableData[].class);
for (PortableData data : port)
{
System.out.println(data.getInsertionStatement());
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
} | 19.571429 | 69 | 0.677372 |
c9b09044d45d9549ec3eb170dad4daa0823fdd4d | 711 | package au.gov.ga.geodesy.exception;
public class GeodesyRuntimeException extends RuntimeException {
private static final long serialVersionUID = 3216139083314642872L;
public GeodesyRuntimeException() {
}
public GeodesyRuntimeException(String message) {
super(message);
}
public GeodesyRuntimeException(Throwable cause) {
super(cause);
}
public GeodesyRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public GeodesyRuntimeException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 26.333333 | 94 | 0.718706 |
9d82fa3f3e7b955b87060c779db94cb91d3d0dd1 | 1,312 | package com.github.dcapwell.java.file.operations;
public final class Chmods {
public static final int OK = 0;
private static final String NIO_CLASS = "com.github.dcapwell.java.file.operations.NIOChmod";
public static boolean isNIOSupported() {
return createNIO() != null;
}
public static Chmod createNIO() {
try {
Class<?> clazz = Class.forName(NIO_CLASS);
return (Chmod) clazz.newInstance();
} catch (ClassNotFoundException e) {
return null;
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
}
}
public static String toString(int mode) {
StringBuilder sb = new StringBuilder(4);
sb.append(0);
// owner
sb.append(optCode(mode, 0400, 0200, 0100));
// group
sb.append(optCode(mode, 040, 020, 010));
// other
sb.append(optCode(mode, 04, 02, 01));
return sb.toString();
}
private static int optCode(int mode, int read, int write, int exec) {
int result = 0;
if (isSet(mode, read)) {
result += 4;
}
if (isSet(mode, write)) {
result += 2;
}
if (isSet(mode, exec)) {
result += 1;
}
return result;
}
private static boolean isSet(int mode, int testbit) {
return (mode & testbit) == testbit;
}
}
| 23.428571 | 94 | 0.618902 |
ab4d97e854f10cff4bd01e59b6a387e800b90e34 | 2,996 | package de.gaiasoft.osm.taglib.def;
import de.gaiasoft.osm.taglib.base.ValueBase;
/* This file is auto-generated.
The values of the enum are extracted from OpenStreetMap data. Therefore this enum is considered to be something
database-like and its values are made available under the Open Database License:
http://opendatacommons.org/licenses/odbl/1.0/.
*/
public enum Value_CRAFT implements ValueBase {
HVAC("hvac"),
ELECTRICIAN("electrician"),
PHOTOGRAPHIC_LABORATORY("photographic_laboratory"),
SAILMAKER("sailmaker"),
GRINDING_MILL("grinding_mill"),
ATELIER("atelier"),
CARPENTER("carpenter"),
ENGRAVER("engraver"),
BOOKBINDER("bookbinder"),
CHEESE("cheese"),
LOCKSMITH("locksmith"),
TILER("tiler"),
BLACKSMITH("blacksmith"),
JEWELLER("jeweller"),
STAND_BUILDER("stand_builder"),
ORGAN_BUILDER("organ_builder"),
WINERY("winery"),
WATCHMAKER("watchmaker"),
RESTORATION("restoration"),
METAL_CONSTRUCTION("metal_construction"),
CABINET_MAKER("cabinet_maker"),
WELDER("welder"),
LUTHIER("luthier"),
OIL_MILL("oil_mill"),
WINDOW_CONSTRUCTION("window_construction"),
BAKERY("bakery"),
CHIMNEY_SWEEPER("chimney_sweeper"),
PRINTER("printer"),
SADDLER("saddler"),
CAR_PAINTER("car_painter"),
SHOEMAKER("shoemaker"),
GARDENER("gardener"),
STONEMASON("stonemason"),
LEATHER("leather"),
INSULATION("insulation"),
PAINTER("painter"),
SCULPTOR("sculptor"),
PRINTMAKER("printmaker"),
SAWMILL("sawmill"),
CARPET_LAYER("carpet_layer"),
TINSMITH("tinsmith"),
GLASSBLOWER("glassblower"),
DRESSMAKER("dressmaker"),
SIGNMAKER("signmaker"),
BASKET_MAKER("basket_maker"),
UPHOLSTERER("upholsterer"),
CLOCKMAKER("clockmaker"),
DISTILLERY("distillery"),
RIGGER("rigger"),
AGRICULTURAL_ENGINES("agricultural_engines"),
BOATBUILDER("boatbuilder"),
EMBROIDERER("embroiderer"),
BEEKEEPER("beekeeper"),
TAILOR("tailor"),
PAVER("paver"),
CONFECTIONERY("confectionery"),
HANDICRAFT("handicraft"),
CATERER("caterer"),
PLUMBER("plumber"),
PARQUET_LAYER("parquet_layer"),
BREWERY("brewery"),
KEY_CUTTER("key_cutter"),
BUILDER("builder"),
ROOFER("roofer"),
PHOTOGRAPHER("photographer"),
MUSICAL_INSTRUMENT("musical_instrument"),
PLASTERER("plasterer"),
GOLDSMITH("goldsmith"),
TOOLMAKER("toolmaker"),
CLEANING("cleaning"),
DENTAL_TECHNICIAN("dental_technician"),
SUN_PROTECTION("sun_protection"),
GLAZIERY("glaziery"),
DOOR_CONSTRUCTION("door_construction"),
OPTICIAN("optician"),
ELECTRONICS_REPAIR("electronics_repair"),
FLOORER("floorer"),
POTTERY("pottery"),
TURNER("turner"),
JOINER("joiner"),
SCAFFOLDER("scaffolder"),
;
private String value;
Value_CRAFT(String value) {
this.value = value;
}
@Override
public String getValue() { return value; }
}
| 29.372549 | 115 | 0.675234 |
1b3f404a234c3d0c1a273b93ec645d99dd9d628f | 723 | package net.loomchild.maligna.model.translation;
import java.util.Collections;
import java.util.List;
/**
* Represents empty translation data of source word -
* essentially it means that source word has no translations.
* Always returns empty translation list and probability of translating to
* any word is always zero.
*
* @author Jarek Lipski (loomchild)
*/
class EmptySourceData implements SourceData {
/**
* @param targetWid target word id
* @return always zero
*/
public double getTranslationProbability(int targetWid) {
assert targetWid >= 0;
return 0;
}
/**
* @return empty translation list
*/
public List<TargetData> getTranslationList() {
return Collections.emptyList();
}
}
| 21.264706 | 75 | 0.728907 |
83cb70a0d5427a11640dfbc20d7a2a5bdc7d58ff | 3,074 | package service;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.Calendar;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.collect.ImmutableSortedMap;
public class InMemoryEventTimeline<E> implements EventTimeline<String, E> {
private static final String IDENTIFIER_FORMAT =
"%0"+Long.toHexString(Long.MAX_VALUE).length()+"x"+
"%0"+Integer.toHexString(Integer.MAX_VALUE).length()+"x";
private final AtomicInteger counter = new AtomicInteger();
private final ConcurrentNavigableMap<String, Reference<E>> timeline =
new ConcurrentSkipListMap<String, Reference<E>>();
// Initial lost event ID is lexigraphically less than any valid ID
private String lastLostEventId = getIdentifier(getMillis(), 0);
@Override
public String getLastEventId() {
if (timeline.isEmpty())
return lastLostEventId;
return timeline.lastKey();
}
@Override
public NavigableMap<String, E> getKnown() {
try {
return resolveRefs(timeline);
} catch (ForgottenEventException e) {
// GC may have run, so cleanup and try again
cleanup();
return getKnown();
}
}
@Override
public NavigableMap<String, E> getSince(String id)
throws ForgottenEventException {
if (id.compareTo(lastLostEventId) < 0) {
throw new ForgottenEventException(id + " is before known history.");
}
return resolveRefs(timeline.tailMap(id,false));
}
@Override
public synchronized String record(E event) {
cleanup();
final String id = getNewIdentifier();
timeline.put(id, getReference(event));
return id;
}
protected NavigableMap<String, E> resolveRefs(
final NavigableMap<String, Reference<E>> m)
throws service.EventTimeline.ForgottenEventException {
final ImmutableSortedMap.Builder<String, E> b = ImmutableSortedMap
.<String, E> naturalOrder();
for (final Map.Entry<String, Reference<E>> e : m.entrySet()) {
final E v = e.getValue().get();
if (v == null)
throw new ForgottenEventException(e.getKey() + " has been forgotten.");
b.put(e.getKey(), v);
}
return b.build();
}
protected void cleanup() {
for (String k : timeline.keySet()) {
if (timeline.get(k).get() != null) return;
timeline.remove(k);
lastLostEventId = k;
}
}
/*
* This method can be overridden for testing purposes.
*/
protected Reference<E> getReference(E referent) {
return new SoftReference<E>(referent);
}
private String getNewIdentifier() {
return getIdentifier(getMillis(), counter.addAndGet(1));
}
private static String getIdentifier(final long ms, final int c) {
return String.format(IDENTIFIER_FORMAT, ms, c);
}
private static Long getMillis() {
return Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis();
}
}
| 29 | 79 | 0.696487 |
b9f7e6d1eb12fd94d342807d7844963551d38b14 | 900 | package com.github.extermania.leetcode;
public class $0931_Minimum_Falling_Path_Sum_96_77 {
class Solution {
void f(int[][] A, int i, int j, int[][] dp){
if(i==A.length-1) dp[i][j]=A[i][j];
else{
int min = Integer.MAX_VALUE;
if(j>0) min=Math.min(min, dp[i+1][j-1]);
min = Math.min(min, dp[i+1][j]);
if(j<A[0].length-1) min = Math.min(min, dp[i+1][j+1]);
dp[i][j]=min+A[i][j];
}
}
public int minFallingPathSum(int[][] A) {
if(A.length==0) return 0;
int[][] dp = new int[A.length][A[0].length];
for(int i=A.length-1; i>=0; i--)
for(int j=0; j<A[0].length; j++) f(A, i, j, dp);
int min = Integer.MAX_VALUE;
for(int j=0; j<A[0].length; j++) min = Math.min(min, dp[0][j]);
return min;
}
}
}
| 33.333333 | 73 | 0.468889 |
2de98b0379f2322539e2e837570e7870d62e890d | 183 | package io.specto.hoverfly.junit.dsl;
public class HoverflyDslException extends RuntimeException {
public HoverflyDslException(String message) {
super(message);
}
}
| 20.333333 | 60 | 0.743169 |
ce8e4a6426fcced06b6a1a32d4b1eeb6dce47916 | 2,277 | package dev.tr7zw.transliterationlib.forge.wrapper.item;
import dev.tr7zw.transliterationlib.api.wrapper.item.UseAction;
import net.minecraft.world.item.UseAnim;
public class TRLUseAction implements UseAction {
public static final UseAction NONE = new TRLUseAction(UseAnim.NONE);
public static final UseAction EAT = new TRLUseAction(UseAnim.EAT);
public static final UseAction DRINK = new TRLUseAction(UseAnim.DRINK);
public static final UseAction BLOCK = new TRLUseAction(UseAnim.BLOCK);
public static final UseAction BOW = new TRLUseAction(UseAnim.BOW);
public static final UseAction SPEAR = new TRLUseAction(UseAnim.SPEAR);
public static final UseAction CROSSBOW = new TRLUseAction(UseAnim.CROSSBOW);
private final UseAnim handle;
private TRLUseAction(UseAnim action) {
handle = action;
}
@Override
public Object getHandler() {
return handle;
}
@Override
public UseAction of(Object handler) {
if(handler == UseAnim.BLOCK)return BLOCK;
if(handler == UseAnim.EAT)return EAT;
if(handler == UseAnim.DRINK)return DRINK;
if(handler == UseAnim.BOW)return BOW;
if(handler == UseAnim.SPEAR)return SPEAR;
if(handler == UseAnim.CROSSBOW)return CROSSBOW;
return NONE;
}
@Override
public UseAction getNone() {
return NONE;
}
@Override
public UseAction getEat() {
return EAT;
}
@Override
public UseAction getDrink() {
return DRINK;
}
@Override
public UseAction getBlock() {
return BLOCK;
}
@Override
public UseAction getBow() {
return BOW;
}
@Override
public UseAction getSpear() {
return SPEAR;
}
@Override
public UseAction getCrossbow() {
return CROSSBOW;
}
@SuppressWarnings("unchecked")
@Override
public <H> H getHandler(Class<H> clazz) {
return (H) this.handle;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((handle == null) ? 0 : handle.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TRLUseAction other = (TRLUseAction) obj;
if (handle != other.handle)
return false;
return true;
}
@Override
public boolean isNull() {
return handle == null;
}
}
| 21.083333 | 77 | 0.714097 |
7e8b16bf6c2ebdd4fa8c44eb97fe47b097b681ca | 1,068 | package org.foraci.mxf.mxfReader.entities;
import org.foraci.mxf.mxfReader.Key;
import org.foraci.mxf.mxfReader.UL;
/**
* A key (with length and UL) and its values
*
* @author jforaci
*/
public abstract class Node implements Comparable
{
private Key key;
private int instanceId;
public Node(Key key, int instanceId) {
this.key = key;
this.instanceId = instanceId;
}
public Key key() {
return key;
}
public final int instanceId() {
return instanceId;
}
/**
* A convenience method to get the Universal Label (<code>UL</code>). This is the same as
* invoking <code>key().getUL()</code>.
* @return the Universal Label for this node
*/
public UL ul() {
return key().getUL();
}
public String toString() {
return (key() == null) ? "<DOCUMENT>" : key().toString();
}
public int compareTo(Object o)
{
Node other = (Node) o;
return instanceId() - other.instanceId();
}
}
| 22.25 | 94 | 0.569288 |
6a92d6b647d7b98ec0d5445265a2bcc7a8cb439c | 3,188 | /*
* Copyright (c) 2020 Nikifor Fedorov
* 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.
* SPDX-License-Identifier: Apache-2.0
* Contributors:
* Nikifor Fedorov and others
*/
package ru.krivocraft.tortoise.android;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import ru.krivocraft.tortoise.core.api.AudioFocus;
public class AndroidAudioFocus implements AudioFocus {
private final AudioManager manager;
private final AudioFocusListener androidListener;
public AndroidAudioFocus(ChangeListener listener, AudioManager manager) {
this.manager = manager;
this.androidListener = new AudioFocusListener(listener);
}
@Override
public void request() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(false)
.setOnAudioFocusChangeListener(androidListener)
.build();
manager.requestAudioFocus(focusRequest);
} else {
manager.requestAudioFocus(androidListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
}
@Override
public void release() {
manager.abandonAudioFocus(androidListener);
}
private static final class AudioFocusListener implements AudioManager.OnAudioFocusChangeListener {
private final AudioFocus.ChangeListener listener;
private AudioFocusListener(ChangeListener listener) {
this.listener = listener;
}
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
listener.mute();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
listener.silently();
break;
case AudioManager.AUDIOFOCUS_GAIN:
listener.gain();
break;
default:
//Do nothing
break;
}
}
}
}
| 36.643678 | 112 | 0.644605 |
1cc438ba04b03335a782d4f1ab2efbabbeda504b | 672 | package com.example;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicReference;
public class FutureTaskCache<V> implements Callable<V> {
private final Callable<V> callable;
private final AtomicReference<FutureTask<V>> ref = new AtomicReference<>();
public FutureTaskCache(Callable<V> callable) {
this.callable = callable;
}
@Override
public V call() throws Exception {
FutureTask<V> task = ref.get();
if (task == null) {
task = new FutureTask<>(callable);
if (ref.compareAndSet(null, task)) {
task.run();
} else {
task = ref.get();
}
}
return task.get();
}
}
| 22.4 | 76 | 0.699405 |
acfb5709db648acb4d67266e828d922301665bf8 | 2,757 | package org.t246osslab.easybuggy4sb.vulnerabilities;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.t246osslab.easybuggy4sb.controller.AbstractController;
import org.t246osslab.easybuggy4sb.core.model.User;
@Controller
public class SQLInjectionController extends AbstractController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping(value = "/sqlijc")
public ModelAndView process(@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "password", required = false) String password, ModelAndView mav,
HttpServletRequest req, Locale locale) {
setViewAndCommonObjects(mav, locale, "sqlijc");
String trimedName = StringUtils.trim(name);
String trimedPassword = StringUtils.trim(password);
if (!StringUtils.isBlank(trimedName) && !StringUtils.isBlank(trimedPassword) && trimedPassword.length() >= 8) {
try {
List<User> users = selectUsers(trimedName, trimedPassword);
if (users == null || users.isEmpty()) {
mav.addObject("errmsg", msg.getMessage("msg.error.user.not.exist", null, locale));
} else {
mav.addObject("userList", users);
}
} catch (DataAccessException se) {
log.error("DataAccessException occurs: ", se);
mav.addObject("errmsg", msg.getMessage("msg.db.access.error.occur", null, locale));
}
} else {
if (req.getMethod().equalsIgnoreCase("POST")) {
mav.addObject("errmsg", msg.getMessage("msg.warn.enter.name.and.passwd", null, locale));
}
}
return mav;
}
private List<User> selectUsers(String name, String password) {
return jdbcTemplate.query("SELECT name, secret FROM users WHERE ispublic = 'true' AND name='" + name
+ "' AND password='" + password + "'", new RowMapper<User>() {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setName(rs.getString("name"));
user.setSecret(rs.getString("secret"));
return user;
}
});
}
}
| 40.544118 | 113 | 0.686616 |
84ac52112d9ea2760ae2f8b59aa62e0d7259b234 | 4,133 | import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.ContentType;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
public class PostRequestWork implements Callable<String> {
private final String url;
private final String fileName;
private final String fieldName;
private File file;
private final DefaultProxyRoutePlanner routePlanner;
private long responseTime = -1;
public static final int TIMEOUT = 15 * 1000; // in ms
public PostRequestWork(String url, String fileName, String fieldName, File file, DefaultProxyRoutePlanner routePlanner) {
this.url = url;
this.fileName = fileName;
this.fieldName = fieldName;
this.file = file;
this.routePlanner = routePlanner;
}
public String getUrl() {
return this.url;
}
public String getFileName() {
return this.fileName;
}
public String getFieldName() {
return this.fieldName;
}
public File getFile() {
return this.file;
}
public long getResponseTime() {
return this.responseTime;
}
public String call() throws Exception {
CloseableHttpClient httpclient;
if (this.routePlanner != null) {
httpclient = HttpClients.custom()
.setRoutePlanner(this.routePlanner)
.build();
} else {
httpclient = HttpClients.createDefault();
}
String returnValue = "";
long startTime = System.currentTimeMillis();
try {
// HttpPost httppost = new HttpPost(getUrl());
HttpPost httppost = new HttpPost(getUrl());
RequestConfig.Builder requestConfig = RequestConfig.custom();
requestConfig.setConnectTimeout(PostRequestWork.TIMEOUT);
requestConfig.setConnectionRequestTimeout(PostRequestWork.TIMEOUT);
requestConfig.setSocketTimeout(PostRequestWork.TIMEOUT);
httppost.setConfig(requestConfig.build());
FileBody bin = new FileBody(getFile());
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart(getFieldName(), bin)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
//System.out.println("----------------------------------------");
//System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
//System.out.println("Response content length: " + resEntity.getContentLength());
String responseString = EntityUtils.toString(resEntity, "UTF-8");
//System.out.println(responseString);
returnValue = responseString;
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} catch (IOException ioe) {
System.out.println("IOE: " + ioe);
} finally {
httpclient.close();
}
long endTime = System.currentTimeMillis();
this.responseTime = (endTime - startTime);
System.out.println("URL: " + getUrl() + " : " + this.responseTime + " ms");
return returnValue;
}
}
| 31.310606 | 125 | 0.697314 |
bbd98f7943722042280b1b6acb5dca2b4e8d85c9 | 5,142 | // Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.objc;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.actions.TemplateExpansionAction.Substitution;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.packages.NativeInfo;
import com.google.devtools.build.lib.packages.NativeProvider;
import com.google.devtools.build.lib.rules.apple.DottedVersion;
import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory;
import javax.annotation.Nullable;
/** Provider that describes a simulator device. */
@Immutable
@SkylarkModule(
name = "IosDevice",
category = SkylarkModuleCategory.PROVIDER,
doc = "<b>Deprecated. Use the new Skylark testing rules instead.</b>"
)
public final class IosDeviceProvider extends NativeInfo {
/** A builder of {@link IosDeviceProvider}s. */
public static final class Builder {
private String type;
private DottedVersion iosVersion;
private String locale;
@Nullable
private DottedVersion xcodeVersion;
/**
* Sets the hardware type of the device, corresponding to the {@code simctl} device type.
*/
public Builder setType(String type) {
this.type = type;
return this;
}
/**
* Sets the iOS version of the simulator to use. This may be different than the iOS sdk version
* used to build the application.
*/
public Builder setIosVersion(DottedVersion iosVersion) {
this.iosVersion = iosVersion;
return this;
}
/**
* Sets the xcode version to obtain the iOS simulator from. This may be different than the
* xcode version with which the application was built.
*/
public Builder setXcodeVersion(@Nullable DottedVersion xcodeVersion) {
this.xcodeVersion = xcodeVersion;
return this;
}
public Builder setLocale(String locale) {
this.locale = locale;
return this;
}
public IosDeviceProvider build() {
return new IosDeviceProvider(this);
}
}
/** Skylark name for the IosDeviceProvider. */
public static final String SKYLARK_NAME = "IosDevice";
/** Skylark constructor and identifier for the IosDeviceProvider. */
public static final NativeProvider<IosDeviceProvider> SKYLARK_CONSTRUCTOR =
new NativeProvider<IosDeviceProvider>(IosDeviceProvider.class, SKYLARK_NAME) {};
private final String type;
private final DottedVersion iosVersion;
private final DottedVersion xcodeVersion;
private final String locale;
private IosDeviceProvider(Builder builder) {
super(SKYLARK_CONSTRUCTOR);
this.type = Preconditions.checkNotNull(builder.type);
this.iosVersion = Preconditions.checkNotNull(builder.iosVersion);
this.locale = Preconditions.checkNotNull(builder.locale);
this.xcodeVersion = builder.xcodeVersion;
}
@SkylarkCallable(
name = "ios_version",
doc = "The iOS version of the simulator to use.",
structField = true
)
public String getIosVersionString() {
return iosVersion.toString();
}
@SkylarkCallable(
name = "xcode_version",
doc = "The xcode version to obtain the iOS simulator from, or <code>None</code> if unknown.",
structField = true,
allowReturnNones = true
)
@Nullable
public String getXcodeVersionString() {
return xcodeVersion != null ? xcodeVersion.toString() : null;
}
@SkylarkCallable(
name = "type",
doc = "The hardware type of the device, corresponding to the simctl device type.",
structField = true
)
public String getType() {
return type;
}
public DottedVersion getIosVersion() {
return iosVersion;
}
@Nullable
public DottedVersion getXcodeVersion() {
return xcodeVersion;
}
public String getLocale() {
return locale;
}
/**
* Returns an {@code IosTestSubstitutionProvider} exposing substitutions indicating how to run a
* test in this particular iOS simulator configuration.
*/
public IosTestSubstitutionProvider iosTestSubstitutionProvider() {
return new IosTestSubstitutionProvider(
ImmutableList.of(
Substitution.of("%(device_type)s", getType()),
Substitution.of("%(simulator_sdk)s", getIosVersion().toString()),
Substitution.of("%(locale)s", getLocale())));
}
}
| 33.174194 | 99 | 0.722287 |
fed865d4dd4486c8dd63c5b6b7a6d29641e35982 | 213 | // Copyright 2021 Herald Project Contributors
// SPDX-License-Identifier: Apache-2.0
//
package io.heraldprox.herald.sensor.analysis.sampling;
public interface Filter<T> {
boolean test(Sample<T> item);
}
| 19.363636 | 54 | 0.741784 |
1f9db8ed1d70fe4126f690e8502b34222c69ab98 | 489 | package com.pengsoft.support.config.properties;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Getter;
import lombok.Setter;
/**
* Transaction auto configure properties
*
* @author peng.dang@pengsoft.com
* @since 1.0.0
*/
@Getter
@Setter
@ConfigurationProperties("pengsoft.transaction")
public class TransactionProperties {
private List<String> readonly;
private List<String> required = List.of("*");
}
| 18.807692 | 75 | 0.760736 |
041f3d3ee4db13659001023d6b82e9d0472e96eb | 2,188 | package org.jesperancinha.std.mastery2.portuguese.music.services;
import org.jesperancinha.std.mastery2.portuguese.music.api.ArtistService;
import org.jesperancinha.std.mastery2.portuguese.music.configuration.TestDatabaseConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.sql.SQLException;
import static org.assertj.core.api.Assertions.assertThat;
@Transactional
@SpringBootTest
@ContextConfiguration
@Import(TestDatabaseConfiguration.class)
@ExtendWith(SpringExtension.class)
class ArtistServiceImplDbPopulatorTest {
@Autowired
private ArtistService artistService;
@Autowired
private DatabasePopulator databasePopulator;
@Autowired
private DataSource dataSource;
@Test
void testListArtistsWithSQLWhenListAllThenGetAList() throws SQLException {
databasePopulator.populate(dataSource.getConnection());
final var artists = artistService.listArtists();
assertThat(artists).hasSize(4);
final var actual = artists.get(0);
assertThat(actual.getName()).isEqualTo("UHF");
assertThat(actual.getNationality()).isEqualTo("Portuguese");
final var actual2 = artists.get(1);
assertThat(actual2.getName()).isEqualTo("Radio Macau");
assertThat(actual2.getNationality()).isEqualTo("Portuguese");
final var actual3 = artists.get(2);
assertThat(actual3.getName()).isEqualTo("Humanos");
assertThat(actual3.getNationality()).isEqualTo("Portuguese");
final var actual4 = artists.get(3);
assertThat(actual4.getName()).isEqualTo("Mler Ife Dada");
assertThat(actual4.getNationality()).isEqualTo("Portuguese");
}
} | 39.071429 | 95 | 0.772395 |
4697728677296b9eed8984947f8db81772190c1e | 849 |
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Queue;
import java.util.Set;
import java.util.HashSet;
import java.util.HashMap;
import java.util.LinkedList;
class Solution {
public String reverseVowels(String s) {
char[] list1 = s.toCharArray();
String vowels = "aeiouAEIOU";
int j = list1.length - 1;
int i = 0;
while (i < j) {
if (vowels.indexOf(s.charAt(j)) == -1)
j -= 1;
else if (vowels.indexOf(s.charAt(i)) == -1)
i += 1;
else{
char tmp = list1[i];
list1[i] = list1[j];
list1[j] = tmp;
i += 1;
j -= 1;
}
}
return new String(list1);
}
}
| 23.583333 | 55 | 0.500589 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.