blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
c7b23202a324f8288a3a37e84f93a793ff9e50d7 | Java | ethol/Cellular-Automata | /src/CA/ReplicationPartalModel.java | UTF-8 | 399 | 2.890625 | 3 | [] | no_license | package CA;
public class ReplicationPartalModel implements Comparable{
int x;
int y;
double value;
public ReplicationPartalModel(int x, int y, double value) {
this.x = x;
this.y = y;
this.value = value;
}
@Override
public int compareTo(Object partial) {
return (int) (((ReplicationPartalModel)partial).value - this.value);
}
public String toString(){
return "" + value;
}
}
| true |
ded5b4c1fbb51631b08e8abc37286762103aa420 | Java | T45K/kyopuro | /AtCoder/other/DDCC2020/C/Main.java | UTF-8 | 1,810 | 3.15625 | 3 | [] | no_license | package AtCoder.other.DDCC2020.C;
import java.util.Scanner;
public class Main {
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
final int h = scanner.nextInt();
final int w = scanner.nextInt();
final int k = scanner.nextInt();
final int[][] table = new int[h][w];
int count = 1;
for (int i = 0; i < h; i++) {
final char[] array = scanner.next().toCharArray();
for (int j = 0; j < w; j++) {
if (array[j] == '#') {
table[i][j] = count++;
}
}
}
for (int i = 0; i < h; i++) {
for (int j = 1; j < w; j++) {
if (table[i][j] == 0 && table[i][j - 1] != 0) {
table[i][j] = table[i][j - 1];
}
}
}
for (int i = 0; i < h; i++) {
for (int j = w - 2; j >= 0; j--) {
if (table[i][j] == 0 && table[i][j + 1] != 0) {
table[i][j] = table[i][j + 1];
}
}
}
for (int i = 1; i < h; i++) {
for (int j = 0; j < w; j++) {
if (table[i][j] == 0 && table[i - 1][j] != 0) {
table[i][j] = table[i - 1][j];
}
}
}
for (int i = h - 2; i >= 0; i--) {
for (int j = 0; j < w; j++) {
if (table[i][j] == 0 && table[i + 1][j] != 0) {
table[i][j] = table[i + 1][j];
}
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
| true |
77eb2f785c2198d2fcf81d32752e85f7f4824a00 | Java | dotronghai/commacoffeeshop | /src/supportclass/Pair.java | UTF-8 | 864 | 3.0625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package supportclass;
/**
*
* @author DELL
* @param <T1> first item that Pair object contain
* @param <T2> second item that Pair object contain
*/
public class Pair<T1, T2> implements java.io.Serializable{
private T1 first;
private T2 second;
public Pair() {
}
public Pair(T1 first, T2 second) {
this.first = first;
this.second = second;
}
public T1 getFirst(){
return this.first;
}
public T2 getSecond(){
return this.second;
}
public void setFirst(T1 first) {
this.first = first;
}
public void setSecond(T2 second) {
this.second = second;
}
}
| true |
1a3a335822c609c26a5be7291a4aafa7bbbeaf53 | Java | xeonye/timeTableApp | /backend/src/main/java/pl/timetable/service/GroupServiceImpl.java | UTF-8 | 2,975 | 2.203125 | 2 | [] | no_license | package pl.timetable.service;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.timetable.api.GroupRequest;
import pl.timetable.dto.GroupDto;
import pl.timetable.entity.Course;
import pl.timetable.entity.Group;
import pl.timetable.exception.EntityNotFoundException;
import pl.timetable.repository.CourseRepository;
import pl.timetable.repository.GroupRepository;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@Transactional
public class GroupServiceImpl extends AbstractService<GroupDto, GroupRequest> {
public static final Logger LOGGER = Logger.getLogger(GroupServiceImpl.class);
@Autowired
private GroupRepository groupRepository;
@Autowired
private CourseRepository courseRepository;
@Override
public List<GroupDto> findAll() {
List<Group> groupEntities = groupRepository.findAll().orElse(Collections.emptyList());
return groupEntities.stream().map(this::mapEntityToDto).collect(Collectors.toList());
}
@Override
public void create(GroupRequest groupRequest) throws EntityNotFoundException {
Group group = mapRequestToEntity(groupRequest);
if (Objects.nonNull(groupRequest.getCourseId())) {
group.setCourse(getCourse(groupRequest.getCourseId()));
}
groupRepository.create(group);
}
@Override
public GroupDto update(GroupRequest groupRequest, int id) {
Group entity = mapRequestToEntity(groupRequest);
entity.setId(id);
return mapEntityToDto(groupRepository.update(entity));
}
@Override
public void delete(int id) throws EntityNotFoundException {
Group group = Optional.ofNullable(groupRepository.getById(id))
.orElseThrow(() -> new EntityNotFoundException(id, "Group"));
groupRepository.remove(group);
}
@Override
public GroupDto get(int id) throws EntityNotFoundException {
return mapEntityToDto(Optional.ofNullable(groupRepository.getById(id))
.orElseThrow(() -> new EntityNotFoundException(id, "Group")));
}
private Course getCourse(Integer courseId) throws EntityNotFoundException {
return Optional.ofNullable(courseRepository.getById(courseId))
.orElseThrow(() -> new EntityNotFoundException(courseId, "Course"));
}
private GroupDto mapEntityToDto(Group group) {
GroupDto dto = new GroupDto();
dto.setCourse(group.getCourse());
dto.setId(group.getId());
dto.setName(group.getName());
return dto;
}
private Group mapRequestToEntity(GroupRequest groupRequest) {
Group entity = new Group();
entity.setName(groupRequest.getName());
return entity;
}
}
| true |
61d51a5ca595c4c3ada32e7ef4aa929c90cb5893 | Java | jerzh/IdeaProjects | /untitled/src/TransformationAnimation.java | UTF-8 | 32,040 | 2.453125 | 2 | [] | no_license | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.Stack;
/*
todo: figure out java update (get variables to only reset after second paint is complete)
todo: separate domain and range panning for range coloring
todo: finish and implement new pan function
*/
public class TransformationAnimation {
private JPanel panel;
private JTextField textField;
private JTextArea textArea;
private JScrollBar scrollBar;
private JRadioButton domainButton, rangeButton;
private int width = 500, height = 500;
private final Object drawLock = new Object();
private int dotsSizeStart = 120;
private int dotsSize = dotsSizeStart;
private P[][] dots;
private P[][] dots2;
private boolean canUpdate = false;
private int dotWidth;
private final double kMin = 0.0000001;
private final double dStart = 2;
private P k = new P(kMin);
private double domainSize = dStart;
private P center = new P();
private P center2 = center;
private double argBound = 0;
private String typed = "preset2";
private Stack<P> out = new Stack<>();
private Stack<Operator> ops = new Stack<>();
private byte valJump = 0;
private byte drawType = 0;
private boolean quickPan = false;
{
resetArray();
}
public static void main(String[] args) {
new TransformationAnimation().go();
}
private void go() {
JFrame frame = new JFrame("Transformation Animation");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
panel = new TransformationPanel();
panel.setPreferredSize(new Dimension(width, height));
contentPane.add(panel, BorderLayout.CENTER);
KeyListener keyListener = new TransformationKeyListener();
panel.addKeyListener(keyListener);
textField = new JTextField(20);
textField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
textField.selectAll();
}
@Override
public void focusLost(FocusEvent e) {
}
});
textField.addActionListener(e -> {
// textArea.append("I sense input!\n");
String input = textField.getText();
if (!input.equals("")) {
typed = input;
}
panel.requestFocusInWindow();
initTextArea();
resetIt();
});
contentPane.add(textField, BorderLayout.NORTH);
textArea = new JTextArea(10, 15);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollBar = scrollPane.getVerticalScrollBar();
contentPane.add(scrollPane, BorderLayout.WEST);
initTextArea();
domainButton = new JRadioButton("Domain Coloring");
domainButton.setActionCommand("domain");
domainButton.setSelected(true);
rangeButton = new JRadioButton("Range Coloring");
rangeButton.setActionCommand("range");
ButtonGroup group = new ButtonGroup();
group.add(domainButton);
group.add(rangeButton);
ActionListener buttonListener = e -> {
switch (e.getActionCommand()) {
case "domain": drawType = 0;
break;
case "range": drawType = 1;
break;
}
panel.requestFocusInWindow();
move();
};
domainButton.addActionListener(buttonListener);
rangeButton.addActionListener(buttonListener);
JPanel radioPanel = new JPanel();
radioPanel.add(domainButton);
radioPanel.add(rangeButton);
contentPane.add(radioPanel, BorderLayout.EAST);
panel.setFocusable(true);
textArea.setFocusable(false);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
panel.requestFocusInWindow();
move();
}
private void initTextArea() {
textArea.setText("This is the debug column.");
}
class TransformationKeyListener implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
double rateConstant = 0.01;
double rangeConstant = 0.1;
// additive
double rate = rateConstant * (k.getR() + 1);
double rotRate = 4 * rateConstant;
double rRate = rangeConstant * domainSize;
double panRate = rateConstant * (center.getR() + 1) * domainSize;
switch (e.getKeyCode()) {
case KeyEvent.VK_SEMICOLON:
// textArea.append("\nI'm resetting everything!");
resetIt();
return;
case KeyEvent.VK_BACK_QUOTE:
// textArea.append("\nI'm asking for input!");
textField.requestFocusInWindow();
textField.setText("f(z) = ");
return;
case KeyEvent.VK_QUOTE:
// textArea.append("\nI'm resetting k!");
k = new P(kMin);
break;
case KeyEvent.VK_OPEN_BRACKET:
// textArea.append("\nI'm resetting mag(k)!");
k.polarSet(kMin, k.getTheta());
break;
case KeyEvent.VK_CLOSE_BRACKET:
// textArea.append("\nI'm resetting arg(k)!");
k.polarSet(k.getR(), 0);
break;
case KeyEvent.VK_LEFT:
// textArea.append("\nI'm increasing arg(k)!");
k.polarSet(k.getR(), k.getTheta() + rotRate);
break;
case KeyEvent.VK_RIGHT:
// textArea.append("\nI'm decreasing arg(k)!");
k.polarSet(k.getR(), k.getTheta() - rotRate);
break;
case KeyEvent.VK_UP:
// textArea.append("\nI'm increasing mag(k)!");
k.polarSet(k.getR() + rate, k.getTheta());
break;
case KeyEvent.VK_DOWN:
// textArea.append("\nI'm decreasing mag(k)!");
k.polarSet(k.getR() - rate, k.getTheta());
break;
case KeyEvent.VK_1:
// textArea.append("\nI'm resetting the zoom!");
domainSize = dStart;
break;
case KeyEvent.VK_E:
// textArea.append("\nI'm zooming in!");
domainSize -= rRate;
break;
case KeyEvent.VK_Q:
// textArea.append("\nI'm zooming out!");
domainSize += rRate;
break;
case KeyEvent.VK_2:
// textArea.append("\nI'm resetting to the center!");
center = new P();
break;
case KeyEvent.VK_A:
// textArea.append("\nI'm panning left!");
domainPan(new P(-panRate));
return;
case KeyEvent.VK_D:
// textArea.append("\nI'm panning right!");
domainPan(new P(panRate));
return;
case KeyEvent.VK_W:
// textArea.append("\nI'm panning up!");
domainPan(new P(0, panRate));
return;
case KeyEvent.VK_S:
// textArea.append("\nI'm panning down!");
domainPan(new P(0, -panRate));
return;
case KeyEvent.VK_X:
// textArea.append("\nI'm resetting the quality!");
dotsSize = dotsSizeStart;
setDotWidth();
break;
case KeyEvent.VK_C:
// textArea.append("\nI'm decreasing the quality!");
dotsSize -= 2;
setDotWidth();
break;
case KeyEvent.VK_Z:
// textArea.append("\nI'm increasing the quality!");
dotsSize += 2;
setDotWidth();
break;
case KeyEvent.VK_SLASH:
stopFocus();
break;
case KeyEvent.VK_PERIOD:
// textArea.append("\nI'm focusing on the local minimum value!");
valJump = -1;
move();
break;
case KeyEvent.VK_COMMA:
// textArea.append("\nI'm focusing on the local maximum value!");
valJump = 1;
move();
break;
case KeyEvent.VK_ENTER:
// textArea.append("\nI'm rounding k!");
long x = Math.round(k.getX());
long y = Math.round(k.getY());
k.set(x, y);
break;
case KeyEvent.VK_L:
// textArea.append("\nI'm resetting the arg bound!");
argBound = 0;
break;
case KeyEvent.VK_O:
// textArea.append("\nI'm increasing the arg bound!");
argBound += rotRate;
break;
case KeyEvent.VK_P:
// textArea.append("\nI'm decreasing the arg bound!");
argBound -= rotRate;
break;
case KeyEvent.VK_BACK_SLASH:
// textArea.append("\nI'm rounding the arg bound!");
long arg = Math.round(argBound / Math.PI * 2);
argBound = arg * Math.PI / 2;
break;
case KeyEvent.VK_MINUS:
// textArea.append("\nI'm switching to domain coloring!");
domainButton.doClick();
return;
case KeyEvent.VK_EQUALS:
// textArea.append("\nI'm switching to range coloring!");
rangeButton.doClick();
return;
case KeyEvent.VK_3:
// textArea.append("\nI'm toggling quick pan!");
quickPan = !quickPan;
return;
default:
return;
}
move();
}
@Override
public void keyReleased(KeyEvent e) {}
}
private void setDotWidth() {
dotWidth = width / dots.length / 2 + 1;
}
private void stopFocus() {
if (valJump != 0) {
// textArea.append("\nI'm no longer focusing on a value!");
valJump = 0;
}
}
private void domainPan(P z) {
stopFocus();
if (quickPan) {
double unit = width / dotWidth * domainSize;
int panX = (int) Math.round(z.getX() / unit);
int panY = (int) Math.round(z.getY() / unit);
int xMin = Math.max(0, panX);
int xMax = dots2.length - Math.min(0, panX);
int yMin = Math.max(0, panY);
int yMax = dots2[0].length - Math.min(0, panY);
center2 = add(center, new P(panX * unit, panY * unit));
dots2 = new P[dotsSize][dotsSize];
for (int i = xMin; i < xMax; i++) {
if (yMax - yMin >= 0) System.arraycopy(dots[i - panX], yMin - panY, dots2[i], yMin, yMax - yMin);
}
callF(xMin, xMax, yMin, yMax);
synchronized (drawLock) {
textArea.append("\nI'm trying to repaint!");
panel.repaint();
}
} else {
center2 = add(center, z);
move();
}
}
class TransformationPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
textArea.append("\nI'm repainting!");
width = this.getWidth();
height = this.getHeight();
synchronized (drawLock) {
textArea.append("\ncanUpdate is " + canUpdate + "!");
if (canUpdate) {
dots = dots2.clone();
center = center2;
}
setDotWidth();
// textArea.append("\ndrawType is " + drawType + "!");
switch (drawType) {
case 0:
domainColoring(g);
break;
case 1:
rangeColoring(g);
break;
}
g.setColor(Color.GRAY);
DecimalFormat format = new DecimalFormat("0.########");
int x = 10, y = 30;
g.drawString(getFuncName(), x, y);
y += 20;
g.drawString("k x: " + format.format(k.getX()), x, y);
y += 10;
g.drawString("k y: " + format.format(k.getY()), x, y);
y += 10;
g.drawString("k r: " + format.format(k.getR()), x, y);
y += 10;
g.drawString("k theta: " + format.format(k.getTheta()), x, y);
y += 10;
g.drawString("domainSize: " + domainSize, x, y);
y += 10;
g.drawString("center x: " + format.format(center.getX()), x, y);
y += 10;
g.drawString("center y: " + format.format(center.getY()), x, y);
y += 10;
g.drawString("quality: " + dotsSize + "p", x, y);
y += 10;
g.drawString("arg bound: " + format.format(argBound / Math.PI) + "pi", x, y);
g.drawLine(width / 2 - 10, height / 2, width / 2 + 10, height / 2);
g.drawLine(width / 2, height / 2 - 10, width / 2, height / 2 + 10);
DrawP drawCenter = new DrawP(new P());
// textArea.append("\ndrawCenter is " + drawCenter + "!");
g.drawLine(0, drawCenter.getY(), width, drawCenter.getY());
g.drawLine(drawCenter.getX(), 0, drawCenter.getX(), height);
DrawP drawK = new DrawP(k);
// textArea.append("\nkx is " + kx + " and ky is " + ky + "!");
int kWidth = 3;
g.setColor(Color.BLACK);
g.fillOval(drawK.getX() - kWidth, drawK.getY() - kWidth, 2 * kWidth, 2 * kWidth);
g.setColor(Color.WHITE);
g.drawOval(drawK.getX() - kWidth, drawK.getY() - kWidth, 2 * kWidth, 2 * kWidth);
scrollBar.setValue(scrollBar.getMaximum());
}
}
}
private String getFuncName() {
switch (typed) {
case "preset1": return "f(z) = (z^2-1)*(z-2-i)^2/(z^2+2+2i)";
case "preset2": return "f(z) = (z^k-1)/(z-1)";
default: return typed;
}
}
private void domainColoring(Graphics g) {
for (int i = 0; i < dots.length; i++) {
for (int j = 0; j < dots[i].length; j++) {
P colorPoint = dots[i][j];
DrawP draw = new DrawP(getPoint(i, j));
g.setColor(getColor(colorPoint));
g.fillRect(draw.getX() - dotWidth, draw.getY() - dotWidth, 2 * dotWidth, 2 * dotWidth);
// textArea.append("\nCurrently drawing at: (" + getPoint(i, j).getX() + ", " + getPoint(i, j).getY() + ")");
// textArea.append("\nwhich maps to: (" + colorPoint.getX() + ", " + colorPoint.getY() + ")");
}
}
}
private void rangeColoring(Graphics g) {
// g.setColor(Color.WHITE);
// g.fillRect(0, 0, width, height);
for (int i = 0; i < dots.length; i++) {
for (int j = 0; j < dots[i].length; j++) {
P colorPoint = getPoint(i, j);
DrawP draw = new DrawP(dots[i][j]);
int drawX = draw.getX();
int drawY = draw.getY();
// if (drawX < 0 || drawX > width || drawY < 0 || drawY > height)
// continue;
g.setColor(getColor(colorPoint));
int dotWidth = width / dots.length / 2 + 1;
g.fillRect(drawX - dotWidth, drawY - dotWidth, 2 * dotWidth, 2 * dotWidth);
}
}
int numLines = 10;
for (int i = 0; i < dots.length; i += dots.length / numLines) {
for (int j = 0; j < dots[i].length - 1; j += 1) {
DrawP draw1 = new DrawP(dots[i][j]);
DrawP draw2 = new DrawP(dots[i][j + 1]);
int drawX1 = draw1.getX();
int drawY1 = draw1.getY();
int drawX2 = draw2.getX();
int drawY2 = draw2.getY();
// if (drawX1 < 0 || drawX1 > width || drawY1 < 0 || drawY1 > height
// || drawX2 < 0 || drawX2 > width || drawY2 < 0 || drawY2 > height)
// continue;
g.setColor(Color.getHSBColor(1, 1, 0));
g.drawLine(drawX1, drawY1, drawX2, drawY2);
}
}
for (int j = 0; j < dots[0].length; j += dots[0].length / numLines) {
for (int i = 0; i < dots.length - 1; i += 1) {
DrawP draw1 = new DrawP(dots[i][j]);
DrawP draw2 = new DrawP(dots[i + 1][j]);
int drawX1 = draw1.getX();
int drawY1 = draw1.getY();
int drawX2 = draw2.getX();
int drawY2 = draw2.getY();
// if (drawX1 < 0 || drawX1 > width || drawY1 < 0 || drawY1 > height
// || drawX2 < 0 || drawX2 > width || drawY2 < 0 || drawY2 > height)
// continue;
g.setColor(Color.getHSBColor(1, 1, 0));
g.drawLine(drawX1, drawY1, drawX2, drawY2);
}
}
}
private class DrawP {
int drawX, drawY;
DrawP(double x, double y) {
drawX = (int) ((x - center.getX()) * width / domainSize / 2) + width / 2;
drawY = -(int) ((y - center.getY()) * height / domainSize / 2) + height / 2;
}
DrawP(P point) {
this(point.getX(), point.getY());
}
int getX() {
return drawX;
}
int getY() {
return drawY;
}
@Override
public String toString() {
return "(" + drawX + ", " + drawY + ")";
}
}
private Color getColor(P point) {
float hue = (float) (point.getTheta() / Math.PI / 2);
double mag = point.getR();
double minSat = 0.1;
float saturation = (float) (minSat + (1 - minSat) / (mag / 1000 + 1));
double magFactor = Math.log(mag) / Math.log(2);
double magConstant = 1 - 1 / (mag + 1);
float brightness = 1 - (float) Math.pow(2, -3 * (magFactor - Math.floor(magFactor) + magConstant));
return Color.getHSBColor(hue, saturation, brightness);
}
private void resetIt() {
// textArea.append("\nI see input! " + typed);
k = new P(kMin);
domainSize = dStart;
center2 = new P();
dotsSize = dotsSizeStart;
valJump = 0;
argBound = 0;
move();
}
private void resetArray() {
canUpdate = false;
dots2 = new P[dotsSize][dotsSize];
for (int i = 0; i < dots2.length; i++) {
for (int j = 0; j < dots2[i].length; j++) {
dots2[i][j] = getPoint2(i, j);
}
}
}
private void move() {
textArea.append("\nI'm here!");
resetArray();
// textArea.append("\nI'm calculating values!");
callF();
if (valJump != 0) {
jump();
}
synchronized (drawLock) {
canUpdate = true;
textArea.append("\nI'm trying to repaint!");
panel.repaint();
}
// textArea.append("\nI made it!");
}
private void jump() {
if (valJump == -1) {
double minMag = dots2[0][0].getR();
int minI = 0;
int minJ = 0;
for (int i = 0; i < dots2.length; i++) {
for (int j = 0; j < dots2[i].length; j++) {
double mag = dots2[i][j].getR();
if (mag < minMag) {
minMag = mag;
minI = i;
minJ = j;
}
}
}
center2 = getPoint2(minI, minJ);
} else if (valJump == 1) {
double maxMag = dots2[0][0].getR();
int maxI = 0;
int maxJ = 0;
for (int i = 0; i < dots2.length; i++) {
for (int j = 0; j < dots2[i].length; j++) {
double mag = dots2[i][j].getR();
if (mag > maxMag) {
maxMag = mag;
maxI = i;
maxJ = j;
}
}
}
center2 = getPoint2(maxI, maxJ);
}
}
private void callF() {
callF(0, dots2.length, 0, dots2[0].length);
}
// calls f for everything EXCEPT between starts and ends
private void callF(int rStart, int rEnd, int cStart, int cEnd) {
// textArea.append("\ntyped is " + typed + "!");
switch (typed) {
case "lorentz": calcF(this::lorentz, rStart, rEnd, cStart, cEnd);
break;
case "preset1": calcF(this::preset1, rStart, rEnd, cStart, cEnd);
break;
case "preset2": calcF(this::preset2, rStart, rEnd, cStart, cEnd);
break;
default: if (typed.matches("f\\(z\\) = .+")) {
calcF(this::custom, rStart, rEnd, cStart, cEnd);
} else {
calcF(this::error, rStart, rEnd, cStart, cEnd);
}
}
}
private P getPoint(int i, int j) {
double x = (i - dots.length / 2) * 2 * domainSize / dots.length + center.getX();
double y = (j - dots[i].length / 2) * 2 * domainSize / dots.length + center.getY();
return new P(x, y);
}
private P getPoint2(int i, int j) {
double x = (i - dots2.length / 2) * 2 * domainSize / dots2.length + center2.getX();
double y = (j - dots2[i].length / 2) * 2 * domainSize / dots2.length + center2.getY();
return new P(x, y);
}
private void calcF(Function f, int rStart, int rEnd, int cStart, int cEnd) {
for (int i = 0; i < dots2.length; i++) {
for (int j = 0; j < dots2[0].length; j++) {
if (!(i > rStart && i < rEnd && j > cStart && j < cEnd)) {
f.f(dots2[i][j]);
}
}
}
}
interface Function {
void f(P point);
}
private void lorentz(P point) {
if (k.getY() != 0) {
point.set(0, 0);
return;
}
double kMax = 10;
double kx = k.getX();
double x = point.getX();
double t = point.getY();
double gamma = 1 / Math.sqrt(1 - Math.pow(kx / kMax, 2));
double xPrime = gamma * (x - kx * t);
double tPrime = gamma * (t - kx * x / kMax / kMax);
point.set(xPrime, tPrime);
}
private void preset1(P z) {
z.set(mul(mul(add(pow(z, new P(2)), new P(-1)), pow(add(z, new P(-2, -1)), new P(2))), rec(add(pow(z, new P(2)), new P(2, 1)))));
}
private void preset2(P z) {
z.set(mul(add(pow(z, k), new P(-1)), rec(add(z, new P(-1)))));
}
private void custom(P z) {
String formula = typed.substring(7);
out = new Stack<>();
ops = new Stack<>();
boolean negative = false;
for (int i = 0; i < formula.length(); i++) {
char c = formula.charAt(i);
if (Character.isDigit(c)) {
int j = i;
i++;
while (i <= formula.length() && formula.substring(j, i).matches("[0-9]*\\.?[0-9]*")) {
i++;
}
i--;
double num = Double.parseDouble(formula.substring(j, i));
if (negative) {
num = -num;
}
if (i < formula.length() && formula.charAt(i) == 'i') {
out.push(new P(0, num));
i++;
}
else {
out.push(new P(num));
i--;
}
} else {
switch (c) {
case 'i':
if (negative) {
out.push(new P(0, -1));
}
out.push(new P(0, 1));
break;
case 'z':
out.push(z);
break;
case 'k':
out.push(k);
break;
case 'e':
out.push(new P(Math.E));
break;
case '(':
ops.push(Operator.L_PAREN);
if (formula.charAt(i + 1) == '-') {
negative = true;
i++;
}
break;
case ')':
Operator op = ops.pop();
while (op != Operator.L_PAREN) {
outPush(op);
op = ops.pop();
}
break;
case '+':
opPush(Operator.PLUS);
break;
case '-':
opPush(Operator.MINUS);
break;
case '*':
opPush(Operator.TIMES);
break;
case '/':
opPush(Operator.DIV);
break;
case '^':
opPush(Operator.POW);
break;
case '|':
opPush(Operator.LOG);
break;
default:
error(z);
return;
}
}
}
while (!ops.isEmpty()) {
Operator op = ops.pop();
outPush(op);
}
z.set(out.get(0));
}
private void opPush(Operator op) {
while (!ops.isEmpty()) {
Operator op2 = ops.peek();
if (op2.getPrecedence() <= op.getPrecedence()) {
break;
}
ops.pop();
outPush(op2);
}
ops.push(op);
// textArea.append("\nThe ops stack is " + ops + "!");
}
private void outPush(Operator op) {
switch (op) {
case PLUS: out.push(add(out.pop(), out.pop())); break;
case MINUS: out.push(add(neg(out.pop()), out.pop())); break;
case TIMES: out.push(mul(out.pop(), out.pop())); break;
case DIV: out.push(mul(rec(out.pop()), out.pop())); break;
case POW: P b = out.pop();
P a = out.pop();
out.push(pow(a, b)); break;
case LOG: b = out.pop();
a = out.pop();
out.push(log(a, b)); break;
}
}
private enum Operator {
L_PAREN(0), PLUS(1), MINUS(1), TIMES(2), DIV(2), POW(3), LOG(3);
private int precedence;
Operator(int precedence) {
this.precedence = precedence;
}
public int getPrecedence() {
return precedence;
}
}
private void error(P z) {
z.set(0, 0);
}
private P pow(P z1, P z2) {
return exp(mul(z2, ln(z1)));
}
private P log(P z1, P z2) {
return mul(ln(z1), rec(ln(z2)));
}
private P exp(P z) {
double a = z.getX();
double b = z.getY();
double mag = Math.exp(a);
double xNew = mag * Math.cos(b);
double yNew = mag * Math.sin(b);
return new P(xNew, yNew);
}
private P ln(P z) {
return new P(Math.log(z.getR()), z.getTheta());
}
private P neg(P z) {
return mul(z, new P(-1));
}
private P mul(P z1, P z2) {
return new P(true, z1.getR() * z2.getR(), z1.getTheta() + z2.getTheta());
}
private P add(P z1, P z2) {
return new P(z1.getX() + z2.getX(), z1.getY() + z2.getY());
}
// reciprocate
private P rec(P z) {
return new P(true, 1 / z.getR(), -z.getTheta());
}
// p for point
private class P {
double x, y, r, theta;
P() {
this(0, 0);
}
P(double x) {
this(x, 0);
}
P(double x, double y) {
set(x, y);
}
P(boolean polar, double r, double theta) {
if (polar) {
polarSet(r, theta);
}
}
void set(double x, double y) {
this.x = x;
this.y = y;
r = Math.sqrt(x * x + y * y);
theta = arg(x, y);
}
void polarSet(double r, double theta) {
this.r = r;
this.theta = theta;
x = r * Math.cos(theta);
y = r * Math.sin(theta);
}
void set(P z) {
set(z.getX(), z.getY());
}
double getX() {
return x;
}
double getY() {
return y;
}
double getR() {
return r;
}
double getTheta() {
return theta;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
private double arg(double x, double y) {
double arg;
if (x == 0) {
if (y == 0) {
arg = 0;
} else if (y > 0) {
arg = Math.PI / 2;
} else {
arg = Math.PI * 3 / 2;
}
} else if (x < 0) {
arg = Math.atan(y / x) + Math.PI;
} else {
arg = Math.atan(y / x);
}
while (true) {
if (arg < argBound) {
arg += 2 * Math.PI;
} else if (arg > argBound + 2 * Math.PI) {
arg -= 2 * Math.PI;
} else {
break;
}
}
return arg;
}
} | true |
2ee3da5c3b219be1f7a570a689cdb67b8b942b91 | Java | Malynovsky-Ivan/PPM-util | /parser-api/src/main/java/com/malynovsky/api/subscription/GameReadyEvent.java | UTF-8 | 513 | 2.234375 | 2 | [] | no_license | package com.malynovsky.api.subscription;
import java.time.LocalTime;
/**
* Created by Ivan on 31.05.2019 - 22:30.
* ppm-telegram-bot
*/
public class GameReadyEvent implements Event<LocalTime> {
private LocalTime gameTime;
public void setGameTime(LocalTime gameTime) {
this.gameTime = gameTime;
}
@Override
public EventType getEventType() {
return EventType.GAME_IS_CALCULATED;
}
@Override
public LocalTime getEventInfo() {
return gameTime;
}
}
| true |
f3556ea8f31f3f8e448f08cfd5766f35c1fba134 | Java | xrogzu/forexroo | /src/main/java/com/github/xuzw/forexroo/app/api/MasterTraderRankings_QueryAll_Api.java | UTF-8 | 2,478 | 2.1875 | 2 | [] | no_license | package com.github.xuzw.forexroo.app.api;
import static com.github.xuzw.forexroo.entity.Tables.USER;
import java.util.ArrayList;
import java.util.List;
import org.jooq.impl.DSL;
import com.github.xuzw.api_engine_runtime.api.Api;
import com.github.xuzw.api_engine_runtime.api.Request;
import com.github.xuzw.api_engine_runtime.api.Response;
import com.github.xuzw.api_engine_sdk.annotation.GenerateByApiEngineSdk;
import com.github.xuzw.forexroo.database.Jooq;
import com.github.xuzw.forexroo.entity.tables.pojos.User;
import com.github.xuzw.modeler_runtime.annotation.Comment;
import com.github.xuzw.modeler_runtime.annotation.Required;
@Comment(value = "交易大师排行榜 - 查询全部")
@GenerateByApiEngineSdk(time = "2017.06.16 02:57:35.249", version = "v1.0.7")
public class MasterTraderRankings_QueryAll_Api implements Api {
@Override()
public Response execute(Request request) throws Exception {
Resp resp = new Resp();
List<User> users = DSL.using(Jooq.buildConfiguration()).selectFrom(USER).orderBy(USER.MASTER_TRADER_TOTAL_PROFIT).limit(10).fetch().into(User.class);
List<MasterTraderRankings> list = new ArrayList<>();
for (User user : users) {
MasterTraderRankings rankings = new MasterTraderRankings();
rankings.setUserId(user.getId());
rankings.setAvatar(user.getAvatar());
rankings.setNickname(user.getNickname());
rankings.setFollowerCount(0L);
rankings.setSingleProfit(user.getMasterTraderSingleProfit());
rankings.setSuccessRate(user.getMasterTraderSuccessRate());
rankings.setTotalProfit(user.getMasterTraderTotalProfit());
list.add(rankings);
}
resp.setList(list);
return resp;
}
public static class Req extends Request {
@Comment(value = "用户唯一标识码")
@Required(value = true)
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
public static class Resp extends Response {
@Comment(value = "列表")
@Required(value = true)
private List<MasterTraderRankings> list;
public List<MasterTraderRankings> getList() {
return list;
}
public void setList(List<MasterTraderRankings> list) {
this.list = list;
}
}
}
| true |
79fccd4b917f1ceb56d6da1758132479e91e507f | Java | sulevsky/Education_1 | /src/main/java/com/courses/jdbcdao_11/factory/AccountDao.java | UTF-8 | 412 | 2.265625 | 2 | [] | no_license | package com.courses.jdbcdao_11.factory;
import com.courses.jdbcdao_11.businessobjects.Account;
import java.util.Collection;
/**
* Created by VSulevskiy on 14.09.2015.
*/
public interface AccountDao {
boolean insertAccount(Account account);
boolean deleteAccount(Account account);
Account findAccount(long id);
boolean updateAccount(Account account);
Collection<Account> getAccounts();
}
| true |
97ce78ca72a6684a80c32808c8418b0bbb46bdd4 | Java | JoshEngels/2016-Minibots | /2016-Minibots/src/arduinoControl/Victor.java | UTF-8 | 365 | 2.9375 | 3 | [] | no_license | package arduinoControl;
import java.io.IOException;
public class Victor{
Servo servo;
public Victor(int pin) {
this.servo=new Servo(pin);
}
public void set(double pwr){
if(pwr<-1){
pwr=-1;
}
if(pwr>1){
pwr=1;
}
try {
servo.send((int) (pwr * 90 + 90));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
f1f24604cf4c6b88dd475d706ac0e2d23bec9488 | Java | rafagcamargo/TwitterAppClient2 | /app/src/main/java/com/codepath/apps/twitterappclient/adapter/TweetsArrayAdapter.java | UTF-8 | 6,682 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package com.codepath.apps.twitterappclient.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.codepath.apps.twitterappclient.R;
import com.codepath.apps.twitterappclient.models.Tweet;
import com.codepath.apps.twitterappclient.ui.RoundedTransformation;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Date;
import java.util.TreeSet;
public class TweetsArrayAdapter extends RecyclerView.Adapter<TweetsArrayAdapter.ViewHolder> {
private final Context context;
private ArrayList<Tweet> tweets;
private OnImageProfileClickListener imageProfileClickListener;
public TweetsArrayAdapter(Context context, ArrayList<Tweet> tweets) {
this.context = context;
this.tweets = tweets;
}
@Override
public TweetsArrayAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.item_tweet, parent, false);
return new ViewHolder(contactView);
}
@Override
public void onBindViewHolder(TweetsArrayAdapter.ViewHolder holder, int position) {
Tweet tweet = tweets.get(position);
Date date = tweet.getCreatedAtInDate();
String createdTime = "";
if (date != null) {
createdTime = DateUtils.getRelativeTimeSpanString(date.getTime(),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL).toString();
}
holder.ivProfile.setImageResource(R.drawable.ic_person_white_48dp);
holder.tvScreenName.setText(context.getString(R.string.screen_name, tweet.getUser().getScreenName()));
holder.tvName.setText(tweet.getUser().getName());
holder.tvText.setText(tweet.getText());
createdTime = formatCreatedTime(createdTime);
holder.tvCreatedAt.setText(createdTime);
Linkify.addLinks(holder.tvText, Linkify.ALL);
Picasso.with(context)
.load(tweet.getUser().getProfileImageUrlOriginal())
.placeholder(R.drawable.ic_person_white_48dp)
.resize(140, 140)
.transform(new RoundedTransformation(5, 0))
.into(holder.ivProfile);
}
@Override
public int getItemCount() {
return tweets.size();
}
public void updateList(ArrayList<Tweet> tweets) {
this.tweets = tweets;
notifyDataSetChanged();
}
public void addAll(ArrayList<Tweet> tweets) {
TreeSet<Tweet> tweetTreeSet = new TreeSet<>(this.tweets);
tweetTreeSet.addAll(tweets);
updateList(new ArrayList<>(tweetTreeSet));
}
public Tweet getItem(int position) {
return tweets.get(position);
}
private String formatCreatedTime(String createdTime) {
if (createdTime.contains("ago")) {
createdTime = createdTime.replace("ago", "");
if (createdTime.contains("days")) {
createdTime = createdTime.replace("days", "d");
}
if (createdTime.contains("secs") || createdTime.contains("sec")) {
createdTime = createdTime.replace("secs", "s");
createdTime = createdTime.replace("sec", "s");
}
if (createdTime.contains("mins") || createdTime.contains("min")) {
createdTime = createdTime.replace("mins", "m");
createdTime = createdTime.replace("min", "m");
}
if (createdTime.contains("hours") || createdTime.contains("hour")) {
createdTime = createdTime.replace("hours", "h");
createdTime = createdTime.replace("hour", "h");
}
return deleteWhitespace(createdTime);
} else if (createdTime.contains("in")) {
createdTime = createdTime.replace("in", "");
return deleteWhitespace(createdTime);
}
if (createdTime.contains("secs") || createdTime.contains("sec")) {
createdTime = createdTime.replace("secs", "s");
createdTime = createdTime.replace("sec", "s");
return deleteWhitespace(createdTime);
}
if (createdTime.contains("mins") || createdTime.contains("min")) {
createdTime = createdTime.replace("mins", "m");
createdTime = createdTime.replace("min", "m");
return deleteWhitespace(createdTime);
}
return createdTime;
}
private String deleteWhitespace(final String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
final int sz = str.length();
final char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
public interface OnImageProfileClickListener {
void onImageProfileClick(View itemView, int position);
}
public void setImageProfileClickListener(OnImageProfileClickListener imageProfileClickListener) {
this.imageProfileClickListener = imageProfileClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView ivProfile;
public TextView tvScreenName;
public TextView tvName;
public TextView tvText;
public TextView tvCreatedAt;
public ViewHolder(View itemView) {
super(itemView);
ivProfile = (ImageView) itemView.findViewById(R.id.ivProfile);
tvScreenName = (TextView) itemView.findViewById(R.id.tvScreenName);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvText = (TextView) itemView.findViewById(R.id.tvText);
tvCreatedAt = (TextView) itemView.findViewById(R.id.tvCreatedAt);
ivProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (imageProfileClickListener != null) {
imageProfileClickListener.onImageProfileClick(ivProfile, getLayoutPosition());
}
}
});
}
}
}
| true |
2336c2bb025aff0934c3ed686c144379ad463b56 | Java | qreon/PacDoge | /src/Doge/SuperDoge.java | UTF-8 | 931 | 3.09375 | 3 | [] | no_license | package Doge;
import Jeu.PacDoge;
import iut.Game;
import iut.Objet;
/**
* Invincible. Transforme les grumpyTueur en GrumpyMangeable pour une certaine dur�e. Un super doge ne peut exister qu'apr�s avoir mang� une super boulette.
*/
public class SuperDoge extends Doge {
private long timer;
private long duration;
public SuperDoge(Game g, String nom, int x, int y, PacDoge p) {
super(g, nom, x, y, p);
timer = 0;
duration = p.getDuration();
}
public void resetTimer()
{
timer = 0;
}
@Override
public void move(long dt)
/* Avec cette méthode, on ne va pas bouger le doge,
* mais elle nous permet d'avoir une notion du temps écoulé grâce au paramètre.
* On va donc s'en servir pour redevenir un doge normal après quelques instants
*/
{
timer += dt;
if(timer > duration)
{
p.downgradePlayer();
p.restoreGrumpy();
}
}
public void effect(Objet o) {
}
} | true |
393829f786e0d2cf952ffd0ba764fbf9b68c647e | Java | Cornstarch1025/brianbot-discord | /src/main/java/niflheim/commands/chess/engine/StockfishQueue.java | UTF-8 | 5,919 | 2.875 | 3 | [] | no_license | package niflheim.commands.chess.engine;
import net.dv8tion.jda.core.EmbedBuilder;
import niflheim.Okita;
import niflheim.rethink.UserOptions;
import java.awt.*;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
public class StockfishQueue {
private BlockingQueue<PlayerMove> queue = new LinkedBlockingDeque<>();
public StockfishQueue() {
Thread t = new Thread(() -> {
while (true) {
try {
PlayerMove move = queue.poll(1000, TimeUnit.MILLISECONDS);
if (move != null) {
UserOptions options = Okita.registry.ofUser(move.getId());
EmbedBuilder embed = new EmbedBuilder().setColor(Color.CYAN)
.setAuthor(move.ctx.user.getName() + "'s Game", null, move.ctx.user.getEffectiveAvatarUrl())
.setFooter("Pawn promotion works by adding q, b, n, or r to end of a move.", null);
switch (move.getCommandType()) {
case 0:
//get Legal moves
String legal = Okita.stockfish.getLegalMoves(move.getFen()).replaceAll(": 1\n", ", ");
move.ctx.channel.sendMessage(embed.setDescription("Legal moves: `" + legal.substring(0, legal.length() - 2) + "`")
.setThumbnail("http://www.fen-to-image.com/image/24/single/coords/" + move.getFen().split("\\s+")[0])
.build()).queue();
break;
case 1:
String[] legalMoves = Okita.stockfish.getLegalMoves(move.getFen()).split(": 1\n");
if (!Arrays.asList(legalMoves).contains(move.getMove().toLowerCase())) {
move.ctx.channel.sendMessage("Illegal move!").queue();
break;
}
options.setFEN(Okita.stockfish.movePiece(move.getFen(), move.getMove().toLowerCase()).split("Fen: ")[1].split("\n")[0]);
options.save();
if (!Okita.stockfish.getLegalMoves(options.getFen()).contains(":")) {
move.ctx.channel.sendMessage(embed.setDescription("Player moves " + move.getMove() + " for checkmate! Player wins!")
.setThumbnail("http://www.fen-to-image.com/image/24/single/coords/" + options.getFen().split("\\s+")[0])
.build()).queue();
options.setFEN(null);
options.save();
break;
}
Okita.stockfish.sendCommand("setoption name Skill Level value " + options.getDifficulty() * 4);
String bestMove = Okita.stockfish.getBestMove(options.getFen(), 100);
options.setFEN(Okita.stockfish.movePiece(options.getFen(), bestMove).split("Fen: ")[1].split("\n")[0]);
options.save();
if (!Okita.stockfish.getLegalMoves(options.getFen()).contains(":")) {
move.ctx.channel.sendMessage(embed.setDescription("Computer moves " + bestMove + " for checkmate! Computer wins!")
.setThumbnail("http://www.fen-to-image.com/image/24/single/coords/" + options.getFen().split("\\s+")[0])
.build()).queue();
options.setFEN(null);
options.save();
break;
}
move.ctx.channel.sendMessage(embed.setDescription("Player moved " + move.getMove().toLowerCase() + ". Computer moved " + bestMove)
.setThumbnail("http://www.fen-to-image.com/image/24/single/coords/" + options.getFen().split("\\s+")[0])
.build()).queue();
break;
case 2:
EmbedBuilder embed2 = new EmbedBuilder().setColor(Color.CYAN)
.setAuthor(move.ctx.user.getName() + "'s Game", null, move.ctx.user.getEffectiveAvatarUrl())
.setFooter("Chess powered by Stockfish 8", null);
Okita.stockfish.sendCommand("setoption name Skill Level value " + options.getDifficulty());
String bestMove1 = Okita.stockfish.getBestMove(options.getFen(), 100);
options.setFEN(Okita.stockfish.movePiece(options.getFen(), bestMove1).split("Fen: ")[1].split("\nKey")[0]);
options.save();
move.ctx.channel.sendMessage(embed2.setDescription("Player has started game as black. Computer moved " + bestMove1)
.setThumbnail("http://www.fen-to-image.com/image/24/single/coords/" + options.getFen().split("\\s+")[0])
.build()).queue();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
}
public void playerMove(PlayerMove move) {
queue.add(move);
}
}
| true |
dde5da9302c89b0b6f653f91262991da289e2f68 | Java | Elspar2/PeculiarFantasy | /src/main/java/com/elspar2/fantasymod/blocks/AngeliteOre.java | UTF-8 | 678 | 2.203125 | 2 | [] | no_license | package com.elspar2.fantasymod.blocks;
import java.util.Random;
import com.elspar2.fantasymod.init.ModItems;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.Item;
public class AngeliteOre extends GemOre {
public AngeliteOre(String name, Material material)
{
super(name, material);
}
@Override
public Item getItemDropped(IBlockState state, Random rand, int fortune)
{
return ModItems.ANGELITE;
//or return ITEMS.STICK; for vanilla items
}
@Override
public int quantityDropped(Random rand)
{
return 1;
}
}
| true |
24451303b143447dfdc424057e69cab3a223fa2d | Java | SunnySuGitHub/Algorithm | /src/GOF/Bridge/Memory16G.java | UTF-8 | 221 | 1.992188 | 2 | [] | no_license | package GOF.Bridge;
/**
* Description:Algorithm
* Created by Administrator on 2020/3/1
*/
class Memory16G implements Memory {
@Override
public void showMemory() {
System.out.println("是16G");
}
}
| true |
1514ff678b48467070b845a9f7c66f96a7f3ce20 | Java | swatinavghare04/MKPITS_Swati_Navghare_Java_Nov_2020 | /Core_Java_Practice/src/com/mkpits/java/string/StringIndexOf1.java | UTF-8 | 286 | 3.265625 | 3 | [] | no_license | // int indexOf(int ch, int fronindex) - return the specified char value index starting with given index;
class StringIndexOf1
{
public static void main(String[] args)
{
String fname = "Swatiekta,sonu";
int arr = fname.indexOf("sonu",1);
System.out.println(arr);
}
} | true |
9827500f77f5cc115e8a4f257e18ba436e2e8502 | Java | newSue/pzjstock | /stock-job/src/main/java/com/pzj/core/stock/job/DailyStockJob.java | UTF-8 | 2,115 | 2.296875 | 2 | [] | no_license | package com.pzj.core.stock.job;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.pzj.core.stock.service.StockBottomService;
import com.pzj.framework.context.Result;
import com.pzj.framework.context.ServiceContext;
/**
* 库存定时任务
* @author dongchunfu
*/
@Component(value = "dailyStockJob")
public class DailyStockJob {
private final static Logger logger = LoggerFactory.getLogger(DailyStockJob.class);
@Resource(name = "stockBottomService")
private StockBottomService stockBottomService;
public void autoCreateStockJob() {
ServiceContext context = ServiceContext.getServiceContext();
try {
long startTime = System.currentTimeMillis();
//1.同步产品与库存规则的关联关系只库存服务的临时表中:tmp_sku_rule_rel.
if (logger.isDebugEnabled()) {
logger.debug(" syncing sku and stock rule relation,context:{}.", context);
}
Result<Integer> count = stockBottomService.syncSkuAndRuleRel(context);
if (logger.isDebugEnabled()) {
logger.debug(" sync sku and stock rule relation success ,response:{},context:{}.", count.getData(), context);
}
//2.启动创建库存记录
if (logger.isDebugEnabled()) {
logger.debug(" auto creating stock record ,context:{}.", context);
}
Result<Integer> result = stockBottomService.autoCreateDailyStock(context);
long endTime = System.currentTimeMillis();
if (result.isOk()) {
if (logger.isDebugEnabled()) {
logger.debug(" auto create stock record success,elapsedTime:{},context:{}.", endTime - startTime, context);
}
} else {
logger.error("auto create stock failed ,message:{}.", result.getErrorMsg());
}
} catch (Throwable t) {
logger.error("auto create stock fail.", t);
}
}
}
| true |
e94733e6bf420bfea5b8d9d5fc586545f0ad8c4c | Java | g2vinay/azure-sdk-for-java | /sdk/spring/azure-spring-boot-test-aad-webapp-and-resource-server-with-obo/src/test/java/com/azure/test/aad/selenium/AADWebAppAndWebApiInOneAppIT.java | UTF-8 | 9,461 | 1.5 | 2 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"CC0-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later"
] | permissive | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.test.aad.selenium;
import com.azure.spring.aad.webapi.AADResourceServerWebSecurityConfigurerAdapter;
import com.azure.spring.aad.webapp.AADWebSecurityConfigurerAdapter;
import com.azure.spring.test.aad.AADWebApiITHelper;
import com.azure.spring.utils.AzureCloudUrls;
import com.azure.test.aad.common.AADSeleniumITHelper;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import java.security.Principal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.azure.spring.test.Constant.MULTI_TENANT_SCOPE_GRAPH_READ;
import static com.azure.spring.test.EnvironmentVariable.AAD_MULTI_TENANT_CLIENT_ID;
import static com.azure.spring.test.EnvironmentVariable.AAD_MULTI_TENANT_CLIENT_SECRET;
import static com.azure.spring.test.EnvironmentVariable.AAD_TENANT_ID_1;
import static com.azure.spring.test.EnvironmentVariable.AAD_USER_NAME_2;
import static com.azure.spring.test.EnvironmentVariable.AAD_USER_PASSWORD_2;
import static com.azure.spring.test.EnvironmentVariable.AZURE_CLOUD_TYPE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class AADWebAppAndWebApiInOneAppIT {
private static final Logger LOGGER = LoggerFactory.getLogger(AADWebAppAndWebApiInOneAppIT.class);
private static final String GRAPH_ME_ENDPOINT = "https://graph.microsoft.com/v1.0/me";
private Map<String, String> properties;
@BeforeAll
public void beforeAll() {
properties = new HashMap<>();
properties.put("azure.activedirectory.tenant-id", AAD_TENANT_ID_1);
properties.put("azure.activedirectory.client-id", AAD_MULTI_TENANT_CLIENT_ID);
properties.put("azure.activedirectory.client-secret", AAD_MULTI_TENANT_CLIENT_SECRET);
properties.put("azure.activedirectory.user-group.allowed-groups", "group1");
properties.put("azure.activedirectory.post-logout-redirect-uri", "http://localhost:${server.port}");
properties.put("azure.activedirectory.base-uri", AzureCloudUrls.getBaseUrl(AZURE_CLOUD_TYPE));
properties.put("azure.activedirectory.graph-base-uri", AzureCloudUrls.getGraphBaseUrl(AZURE_CLOUD_TYPE));
properties.put("azure.activedirectory.application-type", "web_application_and_resource_server");
properties.put("azure.activedirectory.app-id-uri", "api://" + AAD_MULTI_TENANT_CLIENT_ID);
properties.put("azure.activedirectory.authorization-clients.graph.scopes",
"https://graph.microsoft.com/User.Read");
properties.put("azure.activedirectory.authorization-clients.graph.authorization-grant-type", "on_behalf_of");
}
@Test
public void testHomeApiOfWebApplication() {
AADSeleniumITHelper aadSeleniumITHelper = new AADSeleniumITHelper(
DumbApp.class,
properties,
AAD_USER_NAME_2,
AAD_USER_PASSWORD_2);
aadSeleniumITHelper.logIn();
String httpResponse = aadSeleniumITHelper.httpGet("home");
assertTrue(httpResponse.contains("home"));
aadSeleniumITHelper.destroy();
}
@Test
public void testCallGraphApiOfResourceServer() {
AADWebApiITHelper aadWebApiITHelper = new AADWebApiITHelper(
DumbApp.class,
properties,
AAD_MULTI_TENANT_CLIENT_ID,
AAD_MULTI_TENANT_CLIENT_SECRET,
Collections.singletonList(MULTI_TENANT_SCOPE_GRAPH_READ));
assertEquals("Graph response success.",
aadWebApiITHelper.httpGetStringByAccessToken("/api/call-graph"));
}
@Test
public void testSelfDefinedAuthorizationGrantTypeCanBeSavedAndLoaded() {
AADWebApiITHelper aadWebApiITHelper = new AADWebApiITHelper(
DumbApp.class,
properties,
AAD_MULTI_TENANT_CLIENT_ID,
AAD_MULTI_TENANT_CLIENT_SECRET,
Collections.singletonList(MULTI_TENANT_SCOPE_GRAPH_READ));
assertEquals("Graph response success.",
aadWebApiITHelper.getCookieAndAccessByCookie("/api/call-graph", "/api/call-graph"));
}
@SpringBootApplication
@ImportAutoConfiguration(AADWebApplicationAndResourceServerITConfig.class)
public static class DumbApp {
@Autowired
private WebClient webClient;
@Bean
public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
return WebClient.builder()
.apply(oauth2Client.oauth2Configuration())
.build();
}
@RestController
class WebApplicationController {
@GetMapping(value = "/home")
public ResponseEntity<String> home(Principal principal) {
LOGGER.info(((OAuth2AuthenticationToken) principal).getAuthorities().toString());
return ResponseEntity.ok("home");
}
}
@RestController
@RequestMapping("/api")
class ResourceServerController {
/**
* Call the graph resource only with annotation, return user information
*
* @param graphClient authorized client for Graph
* @return Response with graph data
*/
@GetMapping("/call-graph")
@PreAuthorize("hasAuthority('SCOPE_ResourceAccessGraph.Read')")
public String callGraph(@RegisteredOAuth2AuthorizedClient("graph") OAuth2AuthorizedClient graphClient) {
return callMicrosoftGraphMeEndpoint(graphClient);
}
/**
* Call microsoft graph me endpoint
*
* @param graph Authorized Client
* @return Response string data.
*/
private String callMicrosoftGraphMeEndpoint(OAuth2AuthorizedClient graph) {
String body = webClient
.get()
.uri(GRAPH_ME_ENDPOINT)
.attributes(oauth2AuthorizedClient(graph))
.retrieve()
.bodyToMono(String.class)
.block();
LOGGER.info("Response from Graph: {}", body);
return "Graph response " + (null != body ? "success." : "failed.");
}
}
}
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public static class AADWebApplicationAndResourceServerITConfig {
@Order(1)
@Configuration
public static class ApiWebSecurityConfigurationAdapter extends AADResourceServerWebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.antMatcher("/api/**")
.authorizeRequests().anyRequest().authenticated();
}
}
@Configuration
public static class HtmlWebSecurityConfigurerAdapter extends AADWebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
// @formatter:off
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated();
// @formatter:on
}
}
}
}
| true |
ec2baa249a7ac29193a4166c2a86d37324b24d33 | Java | LivTel/operations-ui-basic | /ngat/opsgui/services/ServiceDistributionThread.java | UTF-8 | 1,956 | 2.421875 | 2 | [] | no_license | /**
*
*/
package ngat.opsgui.services;
import ngat.util.ControlThread;
import ngat.util.logging.LogGenerator;
import ngat.util.logging.LogManager;
import ngat.util.logging.Logger;
/**
* @author eng
*
*/
public class ServiceDistributionThread extends ControlThread {
/** The service to manage. */
private ServiceProvider svc;
/** the service manager.*/
private ServiceManager svcMgr;
/** Logging. */
private LogGenerator logger;
/**
* @param svc
* The service to manage.
*/
public ServiceDistributionThread(ServiceProvider svc, ServiceManager svcMgr) {
super(svc.getServiceProviderName(), true);
this.svc = svc;
this.svcMgr = svcMgr;
Logger alogger = LogManager.getLogger("GUI");
logger = alogger.generate().system("GUI").subSystem("Services").srcCompClass(this.getClass().getSimpleName())
.srcCompId(svc.getServiceProviderName());
}
/*
* (non-Javadoc)
*
* @see ngat.util.ControlThread#initialise()
*/
@Override
protected void initialise() {
}
/*
* (non-Javadoc)
*
* @see ngat.util.ControlThread#mainTask()
*/
@Override
protected void mainTask() {
try {
Thread.sleep(svc.getCycleInterval());
} catch (InterruptedException ix) {
}
// Re-register for service
logger.create().info().level(3).extractCallInfo()
.msg("Request status distribution for service handler: " + svc.getServiceProviderName()).send();
long time = System.currentTimeMillis();
try {
int ns = svc.broadcastStatus();
svcMgr.serviceDataUpdate(svc.getServiceProviderName(), time, ns);
// TODO maybe: we dont know the bytes or packets size for last parameter.
} catch (Exception e) {
logger.create().info().level(1).extractCallInfo().msg("Distribution failed, stack trace follows: " + e).send();
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see ngat.util.ControlThread#shutdown()
*/
@Override
protected void shutdown() {
}
}
| true |
6bbd0853896d5bbb0d0a29479241eb2752d40729 | Java | saurabh2590/NIST-Voting-Tablet | /src/org/easyaccess/nist/HomeActivity.java | UTF-8 | 31,805 | 1.734375 | 2 | [
"Apache-2.0"
] | permissive | package org.easyaccess.nist;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends Activity implements OnInitListener{
// flags
int gFocusPosition = 1;
int gMaxFocusableItem = 12;
static boolean isButtonPressed = false;
boolean isResultScan = false;
Context gContext = null;
AudioManager audioManager = null;
HeadsetListener gHeadsetListener = null;
// views
TextToSpeech gTTS = null;
TextView gHelpText = null , gBallotPage = null;
ImageButton gHelp = null;
ImageButton gNavigateRight = null;//gNavigateLeft = null,
ImageButton gGoToSummary = null;// gGoToStart = null;
ImageButton gFontDecrease = null, gFontIncrease = null;
ImageButton gVolumeIncrease = null, gVolumeDecrease = null;
Button gQrSetting = null, gNfcSetting = null, gPaperSetting = null, gManualSetting = null;
View gBtmView = null,gTopView = null;
ProgressDialog gDialog = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.frnt_scrn);
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("org.easyaccess.qrapp");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, Constants.REQUESTCODE_CAPTUREACTIVITY);
gContext = HomeActivity.this;
gTopView = findViewById(R.id.v_scrn_top);
gBtmView = findViewById(R.id.v_scrn_btm);
gBallotPage = (TextView) findViewById(R.id.ballot_page);
gHelpText = (TextView) findViewById(R.id.textView1);
gHelp = (ImageButton) findViewById(R.id.btn_help);
gNavigateRight = (ImageButton) findViewById(R.id.btn_right);
// gNavigateLeft = (ImageButton) findViewById(R.id.btn_left);
gFontDecrease = (ImageButton) findViewById(R.id.btn_font_decrease);
gFontIncrease = (ImageButton) findViewById(R.id.btn_font_increase);
gGoToSummary = (ImageButton) findViewById(R.id.btn_goto_end);
// gGoToStart = (ImageButton) findViewById(R.id.btn_goto_start);
gVolumeIncrease = (ImageButton) findViewById(R.id.btn_volume_increase);
gVolumeDecrease = (ImageButton) findViewById(R.id.btn_volume_decrease);
gQrSetting = (Button) findViewById(R.id.btn_qrcode_setting);
gNfcSetting = (Button) findViewById(R.id.btn_nfctag_setting);
gPaperSetting = (Button) findViewById(R.id.btn_paper_setting);
gManualSetting = (Button) findViewById(R.id.btn_manual_setting);
gGoToSummary.setVisibility(View.GONE);
}
private OnClickListener sOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_left:
resetActivityVariable();
navigateLeft();
break;
case R.id.btn_right:
resetActivityVariable();
navigateRight();
isButtonPressed = false;
break;
case R.id.btn_qrcode_setting:
resetActivityVariable();
readQRSettings();
break;
case R.id.btn_nfctag_setting:
resetActivityVariable();
readNFCSettings();
isButtonPressed = false;
break;
case R.id.btn_manual_setting:
resetActivityVariable();
setManualSettings();
break;
case R.id.btn_paper_setting:
resetActivityVariable();
readPaperSettings();
isButtonPressed = false;
break;
case R.id.btn_goto_end:
loadSummary();
break;
case R.id.btn_font_decrease:
setFontSize(Constants.DECREASE);
break;
case R.id.btn_font_increase:
setFontSize(Constants.INCREASE);
break;
case R.id.btn_help:
resetActivityVariable();
launchHelp();
isButtonPressed = false;
break;
case R.id.btn_volume_decrease:
setVolume(Constants.DECREASE);
break;
case R.id.btn_volume_increase:
setVolume(Constants.INCREASE);
break;
}
}
};
private OnTouchListener gOnTouchListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
switch (v.getId()) {
case R.id.textView1:
v.setBackgroundResource(R.drawable.focused);
if(HeadsetListener.isHeadsetConnected){
speakWord(gHelpText.getText().toString(), null);
}
break;
case R.id.btn_qrcode_setting:
if(HeadsetListener.isHeadsetConnected){
}
break;
case R.id.btn_nfctag_setting:
if(HeadsetListener.isHeadsetConnected){
}
break;
case R.id.btn_manual_setting:
if(HeadsetListener.isHeadsetConnected){
}
break;
case R.id.btn_paper_setting:
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.btn_vol_dec), null);
}
break;
case R.id.btn_volume_decrease:
v.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.btn_vol_dec), null);
}
break;
case R.id.btn_volume_increase:
v.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.btn_vol_inc), null);
}
break;
case R.id.btn_font_decrease:
v.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.btn_font_dec), null);
}
break;
case R.id.btn_font_increase:
v.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.btn_font_inc), null);
}
break;
case R.id.btn_left:
v.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.btn_exit), null);
}
break;
case R.id.btn_right:
v.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.next_ballot), null);
}
break;
case R.id.btn_help:
v.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.btn_help), null);
}
break;
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
switch (v.getId()) {
case R.id.textView1:
resetDeviceVarOnStateChange();
v.setBackground(null);
break;
case R.id.btn_qrcode_setting:
// v.performClick();
break;
case R.id.btn_nfctag_setting:
// v.performClick();
break;
case R.id.btn_manual_setting:
// v.performClick();
break;
case R.id.btn_paper_setting:
// v.performClick();
break;
case R.id.btn_volume_decrease:
resetDeviceVarOnStateChange();
v.setBackgroundColor(getResources().getColor(android.R.color.black));
// v.performClick();
break;
case R.id.btn_volume_increase:
resetDeviceVarOnStateChange();
v.setBackgroundColor(getResources().getColor(android.R.color.black));
// v.performClick();
break;
case R.id.btn_font_decrease:
resetDeviceVarOnStateChange();
v.setBackgroundColor(getResources().getColor(android.R.color.black));
// v.performClick();
break;
case R.id.btn_font_increase:
resetDeviceVarOnStateChange();
v.setBackgroundColor(getResources().getColor(android.R.color.black));
// v.performClick();
break;
case R.id.btn_goto_end:
resetActivityVariable();
v.setBackgroundColor(getResources().getColor(android.R.color.black));
// v.performClick();
break;
case R.id.btn_help:
resetActivityVariable();
v.setBackgroundColor(getResources().getColor(android.R.color.black));
// v.performClick();
break;
case R.id.btn_left:
resetActivityVariable();
v.setBackgroundColor(getResources().getColor(android.R.color.black));
// v.performClick();
break;
case R.id.btn_right:
resetActivityVariable();
v.setBackgroundColor(getResources().getColor(android.R.color.black));
// v.performClick();
break;
}
}
return false;
}
};
protected void navigateLeft() {
if(HeadsetListener.isHeadsetConnected){
}
}
protected void readPaperSettings() {
}
protected void setManualSettings() {
Intent intent = new Intent(this, PreferencActivity.class);
startActivity(intent);
}
protected void readNFCSettings() {
}
protected void readQRSettings() {
new Thread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("org.easyaccess.qrapp");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, Constants.QR_REQUEST_CODE);
}
}).start();
}
protected void navigateRight() {
// Toast.makeText(gContext, "from navigate right", Toast.LENGTH_SHORT).show();
writeToFile(" right button pressed, focus position = " + gFocusPosition);
SharedPreferences preferences = getSharedPreferences(Constants.PREFERENCE_NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.clear();
editor.commit();
startActivity(new Intent(this,ContestActivity.class));
}
protected void launchHelp() {
Intent intent = new Intent(this, HelpScreen.class);
intent.putExtra(Constants.MESSAGE, "homepage");
startActivity(intent);
}
private void setVolume(int controlFlag) {
// TODO Auto-generated method stub
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
switch (controlFlag) {
case Constants.DECREASE :
if(curVolume == Constants.MIN_VOLUME){
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume, 0);
if(HeadsetListener.isHeadsetConnected){
}
}else{
curVolume = curVolume - Constants.V0LUME_DIFFERENCE;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume, 0);
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.softer), null);
}
}
break;
case Constants.INCREASE :
if(curVolume == maxVolume){
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume, 0);
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.loudest), null);
}
}else{
curVolume = curVolume + Constants.V0LUME_DIFFERENCE;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume, 0);
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.louder), null);
}
}
break;
}
}
protected void setFontSize(int controlFlag) {
// TODO Auto-generated method stub
switch (controlFlag) {
case Constants.DECREASE:
if(Constants.SETTING_FONT_SIZE == Constants.MIN_FONT_SIZE){
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.font_smallest), null);
}
}else{
Constants.SETTING_FONT_SIZE = Constants.SETTING_FONT_SIZE - Constants.FONT_DIFFERENCE;
gHelpText.setTextSize(Constants.SETTING_FONT_SIZE);
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.font_smaller), null);
}
}
break;
case Constants.INCREASE :
if(Constants.SETTING_FONT_SIZE == Constants.MAX_FONT_SIZE){
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.font_largest), null);
}
}else{
Constants.SETTING_FONT_SIZE = Constants.SETTING_FONT_SIZE + Constants.FONT_DIFFERENCE;
gHelpText.setTextSize(Constants.SETTING_FONT_SIZE);
if(HeadsetListener.isHeadsetConnected){
speakWord(getString(R.string.font_larger), null);
}
}
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM);
if(keyCode == KeyEvent.KEYCODE_UNKNOWN){
switch (event.getScanCode()) {
case KeyEvent.KEYCODE_APP_SWITCH:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
gHelp.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
break;
case KeyEvent.KEYCODE_BUTTON_1:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
break;
case KeyEvent.KEYCODE_BUTTON_2:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
break;
case KeyEvent.KEYCODE_BUTTON_3:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
selectCurrentFocusItem(gFocusPosition, Constants.REACH_NEW_ITEM);
break;
case KeyEvent.KEYCODE_BUTTON_4:
break;
case KeyEvent.KEYCODE_BUTTON_5:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
gNavigateRight.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
break;
case KeyEvent.KEYCODE_BUTTON_6:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
gVolumeDecrease.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
break;
case KeyEvent.KEYCODE_BUTTON_7:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
gVolumeIncrease.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
break;
}
}else{
switch (keyCode) {
case KeyEvent.KEYCODE_F1:
gHelp.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
break;
case KeyEvent.KEYCODE_DPAD_UP:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
break;
case KeyEvent.KEYCODE_ENTER:
// if(!HomePage.isButtonPressed){
// HomePage.isButtonPressed = true;
// }
selectCurrentFocusItem(gFocusPosition, Constants.REACH_NEW_ITEM);
break;
case KeyEvent.KEYCODE_PAGE_DOWN:
gNavigateRight.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
break;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// if(HomePage.isButtonPressed){
// HomePage.isButtonPressed = false;
// }
if (keyCode == KeyEvent.KEYCODE_UNKNOWN) {
switch (event.getScanCode()) {
case KeyEvent.KEYCODE_APP_SWITCH:
gHelp.setBackground(null);
gHelp.performClick();
break;
case KeyEvent.KEYCODE_BUTTON_1:
gFocusPosition--;
if (gFocusPosition <= 0) {
gFocusPosition = gMaxFocusableItem;
}
navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM);
break;
case KeyEvent.KEYCODE_BUTTON_2:
gFocusPosition++;
if (gFocusPosition >= gMaxFocusableItem + 1) {
gFocusPosition = 1;
}
navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM);
break;
case KeyEvent.KEYCODE_BUTTON_3:
selectCurrentFocusItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM);
break;
case KeyEvent.KEYCODE_BUTTON_5:
gNavigateRight.setBackground(null);
gNavigateRight.performClick();
break;
case KeyEvent.KEYCODE_BUTTON_6:
gFocusPosition = 3;
gVolumeDecrease.performClick();
gVolumeDecrease.setBackground(getResources().getDrawable(R.drawable.focused));
break;
case KeyEvent.KEYCODE_BUTTON_7:
gFocusPosition = 4;
gVolumeIncrease.performClick();
gVolumeIncrease.setBackground(getResources().getDrawable(R.drawable.focused));
break;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_F1:
gHelp.setBackground(null);
gHelp.performClick();
break;
case KeyEvent.KEYCODE_DPAD_UP:
gFocusPosition--;
if (gFocusPosition <= 0) {
gFocusPosition = gMaxFocusableItem;
}
navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM);
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
gFocusPosition++;
if (gFocusPosition >= gMaxFocusableItem + 1) {
gFocusPosition = 1;
}
navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM);
break;
case KeyEvent.KEYCODE_ENTER:
selectCurrentFocusItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM);
break;
case KeyEvent.KEYCODE_PAGE_DOWN:
gNavigateRight.setBackground(null);
gNavigateRight.performClick();
break;
}
}
return super.onKeyUp(keyCode, event);
}
private void navigateToOtherItem(int focusPosition, int reach_jump) {
switch (reach_jump) {
case Constants.JUMP_FROM_CURRENT_ITEM:
if(focusPosition == 1){
gHelpText.setBackground(null);
}else if(focusPosition == 2){
gHelp.setBackground(null);
}else if(focusPosition == 3){
gVolumeDecrease.setBackground(null);
}else if(focusPosition == 4){
gVolumeIncrease.setBackground(null);
}else if(focusPosition == 5){
gFontDecrease.setBackground(null);
}else if(focusPosition == 6){
gFontIncrease.setBackground(null);
}else if(focusPosition == 7){
gBtmView.setBackgroundColor(getResources().getColor(android.R.color.black));
}else if(focusPosition == 8){
gTopView.setBackgroundColor(getResources().getColor(android.R.color.black));
}else if(focusPosition == 9){
gNavigateRight.setBackground(null);
}
break;
case Constants.REACH_NEW_ITEM:
if (focusPosition == 1) {
gHelpText.setBackground(getResources().getDrawable(R.drawable.focused));
gHelpText.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(gHelpText.getText().toString(), null);
}
} else if (focusPosition == 2) {
gHelp.setBackground(getResources().getDrawable(R.drawable.focused));
gHelp.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(getString(R.string.btn_help), null);
}
} else if (focusPosition == 3) {
gVolumeDecrease.setBackground(getResources().getDrawable(R.drawable.focused));
gVolumeDecrease.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(getString(R.string.btn_vol_dec), null);
}
} else if (focusPosition == 4) {
gVolumeIncrease.setBackground(getResources().getDrawable(R.drawable.focused));
gVolumeIncrease.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(getString(R.string.btn_vol_inc), null);
}
} else if (focusPosition == 5) {
gFontDecrease.setBackground(getResources().getDrawable(R.drawable.focused));
gFontDecrease.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(getString(R.string.btn_font_dec), null);
}
} else if (focusPosition == 6) {
gFontIncrease.setBackground(getResources().getDrawable(R.drawable.focused));
gFontIncrease.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(getString(R.string.btn_font_inc), null);
}
} else if (focusPosition == 7) {
gBtmView.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
gBtmView.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(getString(R.string.scrn_bottom), null);
}
} else if(focusPosition == 8){
gTopView.setBackgroundColor(getResources().getColor( android.R.color.holo_orange_dark));
gTopView.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(getString(R.string.scrn_top), null);
}
} else if(focusPosition == 9){
gNavigateRight.setBackground(getResources().getDrawable(R.drawable.focused));
gNavigateRight.requestFocus();
if (HeadsetListener.isHeadsetConnected) {
speakWord(getString(R.string.next_ballot), null);
}
}
break;
}
}
private void selectCurrentFocusItem(int focusPosition, int pressed_released) {
switch (pressed_released) {
case Constants.REACH_NEW_ITEM:
if (focusPosition == 1) {
gHelpText.setBackground(getResources().getDrawable(R.drawable.focused));
if (HeadsetListener.isHeadsetConnected && !HomeActivity.isButtonPressed) {
speakWord(gHelpText.getText().toString(), null);
}
} else if (focusPosition == 2) {
gHelp.setBackgroundColor(getResources().getColor(
android.R.color.holo_orange_dark));
} else if (focusPosition == 3) {
gVolumeDecrease.setBackgroundColor(getResources().getColor(
android.R.color.holo_orange_dark));
} else if (focusPosition == 4) {
gVolumeIncrease.setBackgroundColor(getResources().getColor(
android.R.color.holo_orange_dark));
} else if (focusPosition == 5) {
gFontDecrease.setBackgroundColor(getResources().getColor(
android.R.color.holo_orange_dark));
} else if (focusPosition == 6) {
gFontIncrease.setBackgroundColor(getResources().getColor(
android.R.color.holo_orange_dark));
} else if (focusPosition == 7) {
gBtmView.setBackgroundColor(getResources().getColor(
android.R.color.holo_orange_dark));
} else if (focusPosition == 8) {
gTopView.setBackgroundColor(getResources().getColor(
android.R.color.holo_orange_dark));
} else if (focusPosition == 9) {
gNavigateRight.setBackgroundColor(getResources().getColor(
android.R.color.holo_orange_dark));
}
HomeActivity.isButtonPressed = true;
break;
case Constants.JUMP_FROM_CURRENT_ITEM:
HomeActivity.isButtonPressed = false;
if(focusPosition == 1){
}else if(focusPosition == 2){
gHelp.setBackground(null);
gHelp.performClick();
}else if (focusPosition == 3 ) {
gVolumeDecrease.setBackground(getResources().getDrawable(R.drawable.focused));
gVolumeDecrease.performClick();
} else if (focusPosition == 4 ) {
gVolumeIncrease.setBackground(getResources().getDrawable(R.drawable.focused));
gVolumeIncrease.performClick();
} else if (focusPosition == 5 ) {
gFontDecrease.setBackground(getResources().getDrawable(R.drawable.focused));
gFontDecrease.performClick();
} else if (focusPosition == 6 ) {
gFontIncrease.setBackground(getResources().getDrawable(R.drawable.focused));
gFontIncrease.performClick();
} else if(focusPosition == 9 ){
gNavigateRight.setBackground(null);
gNavigateRight.performClick();
}
break;
}
}
protected void loadSummary() {
// TODO Auto-generated method stub
if(HeadsetListener.isHeadsetConnected){
}
}
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
if(Constants.SETTING_LANGUAGE == Constants.DEFAULT_LANG_SETTING){
gTTS.setLanguage(Locale.US);
}else{
gTTS.setLanguage(new Locale("spa","ESP"));
}
gTTS.setSpeechRate(Constants.SETTING_TTS_SPEED);
speakWord(gHelpText.getText().toString(), null);
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(gContext, getString(R.string.failed),
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.TTS_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
if(Constants.SETTING_TTS_VOICE == Constants.DEFAULT_TTS_VOICE){
gTTS = new TextToSpeech(gContext, this, "com.svox.classic");
}else{
gTTS = new TextToSpeech(gContext, this, "com.ivona.tts");
}
} else {
Intent ttsInstallIntent = new Intent();
ttsInstallIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(ttsInstallIntent);
}
} else if(requestCode == Constants.REQUESTCODE_CAPTUREACTIVITY){
if (resultCode == Activity.RESULT_OK) {
String capturedQrValue = data.getStringExtra("SCAN_RESULT");
gDialog = ProgressDialog.show(gContext, "", "Applying settings...");
gHelpText.setText(capturedQrValue);
try {
setUserSettings(new JSONObject(capturedQrValue));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(gContext, "Scan canceled", Toast.LENGTH_SHORT).show();
}
resetPreferences();
Intent intent = new Intent(this,ContestActivity.class);
startActivity(intent);
finish();
}
}
private void resetPreferences() {
SharedPreferences preferences = getSharedPreferences(Constants.PREFERENCE_NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.clear();
editor.commit();
}
private void setUserSettings(JSONObject jsonObject) {
try {
if (jsonObject.has(Constants.LANGUAGE)) {
Constants.SETTING_LANGUAGE = Integer.valueOf(jsonObject.getString(Constants.LANGUAGE));
Resources standardResources = this.getResources();
AssetManager assets = standardResources.getAssets();
DisplayMetrics metrics = standardResources.getDisplayMetrics();
Configuration config = new Configuration(standardResources.getConfiguration());
// config.locale = Locale.US;
config.locale = new Locale("spa", "ESP");
Resources defaultResources = new Resources(assets, metrics, config);
}
if (jsonObject.has(Constants.TOUCH_PRESENT)) {
Constants.SETTING_TOUCH_PRESENT = Boolean.valueOf(jsonObject.getString(Constants.TOUCH_PRESENT));
}
if (jsonObject.has(Constants.FONT_SIZE)) {
Constants.SETTING_FONT_SIZE = Integer.valueOf(jsonObject.getString(Constants.FONT_SIZE));
}
if (jsonObject.has(Constants.REVERSE_SCREEN)) {
Constants.SETTING_REVERSE_SCREEN = Boolean.valueOf(jsonObject.getString(Constants.REVERSE_SCREEN));
}
if (jsonObject.has(Constants.TTS_VOICE)) {
Constants.SETTING_TTS_VOICE = Integer.valueOf(jsonObject.getString(Constants.TTS_VOICE));
}
if (jsonObject.has(Constants.TTS_SPEED)) {
Constants.SETTING_TTS_SPEED = Float.valueOf(jsonObject.getString(Constants.TTS_SPEED));
gTTS.setSpeechRate(Constants.SETTING_TTS_SPEED);
}
if (jsonObject.has(Constants.SCAN_MODE)) {
Constants.SETTING_SCAN_MODE = Boolean.valueOf(jsonObject.getString(Constants.SCAN_MODE));
if(Constants.SETTING_SCAN_MODE){
if (jsonObject.has(Constants.SCAN_MODE_SPEED)) {
Constants.SETTING_SCAN_MODE_SPEED = Integer.valueOf(jsonObject.getString(Constants.SCAN_MODE_SPEED));
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onResume() {
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(gHeadsetListener, filter);
if(gDialog != null && gDialog.isShowing()){
gDialog.cancel();
}
super.onResume();
}
@Override
public void onPause() {
unregisterReceiver(gHeadsetListener);
super.onPause();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (gTTS != null) {
gTTS.stop();
gTTS.shutdown();
}
}
public void speakWord(String word, HashMap<String, String> utteranceId) {
// if (gTTS != null && utteranceId != null) {
// gTTS.speak(word, TextToSpeech.QUEUE_FLUSH, utteranceId);
// }else{
// gTTS.speak(word, TextToSpeech.QUEUE_FLUSH, null);
// }
}
@Override
protected void onStart() {
super.onStart();
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, Constants.TTS_DATA_CHECK_CODE);
gHeadsetListener = new HeadsetListener();
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
gQrSetting.setOnClickListener(sOnClickListener);
gQrSetting.setOnTouchListener(gOnTouchListener);
gNfcSetting.setOnClickListener(sOnClickListener);
gNfcSetting.setOnTouchListener(gOnTouchListener);
gPaperSetting.setOnClickListener(sOnClickListener);
gPaperSetting.setOnTouchListener(gOnTouchListener);
gManualSetting.setOnClickListener(sOnClickListener);
gManualSetting.setOnTouchListener(gOnTouchListener);
gHelp.setOnClickListener(sOnClickListener);
gHelp.setOnTouchListener(gOnTouchListener);
gNavigateRight.setOnClickListener(sOnClickListener);
gNavigateRight.setOnTouchListener(gOnTouchListener);
// gNavigateLeft.setOnClickListener(sOnClickListener);
// gNavigateLeft.setOnTouchListener(gOnTouchListener);
gFontDecrease.setOnClickListener(sOnClickListener);
gFontDecrease.setOnTouchListener(gOnTouchListener);
gFontIncrease.setOnClickListener(sOnClickListener);
gFontIncrease.setOnTouchListener(gOnTouchListener);
// gGoToStart.setOnClickListener(sOnClickListener);
// gGoToStart.setOnTouchListener(gOnTouchListener);
gGoToSummary.setOnClickListener(sOnClickListener);
gGoToSummary.setOnTouchListener(gOnTouchListener);
gVolumeIncrease.setOnClickListener(sOnClickListener);
gVolumeIncrease.setOnTouchListener(gOnTouchListener);
gVolumeDecrease.setOnClickListener(sOnClickListener);
gVolumeDecrease.setOnTouchListener(gOnTouchListener);
// gHelpText.setText(getString(R.string.help_message));
gHelpText.setTextSize(Constants.SETTING_FONT_SIZE);
gHelpText.setOnTouchListener(gOnTouchListener);
gHelpText.setBackgroundResource(R.drawable.focused);
gHelpText.requestFocus();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(HomeActivity.this, PreferencActivity.class));
break;
}
return true;
}
private void writeToFile(String string) {
// TODO Auto-generated method stub
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS) + File.separator + "preference_file.txt"), true));
bufferedWriter.write(string);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
protected void resetActivityVariable(){
gFocusPosition = 1;
}
protected void resetDeviceVarOnStateChange() {
navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM);
gFocusPosition = 0;
}
} | true |
c40a561364fe7b568c2cce103dd83c3a0cc7645c | Java | Bikino/enrolee-service | /src/main/java/com/collabera/enroleesservice/model/Enrollee.java | UTF-8 | 1,796 | 2.125 | 2 | [] | no_license | package com.collabera.enroleesservice.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.annotation.Generated;
import java.time.LocalDate;
import java.util.List;
@Document()
public class Enrollee {
@Id
private Integer id;
private String name;
private Boolean status;
private LocalDate birthDate;
private String phoneNumber;
private List<Dependent> listDependents;
public Enrollee() {
}
public Enrollee(Integer id, String name, Boolean status, LocalDate birthDate, String phoneNumber, List<Dependent> listDependents) {
this.id = id;
this.name = name;
this.status = status;
this.birthDate = birthDate;
this.phoneNumber = phoneNumber;
this.listDependents = listDependents;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public List<Dependent> getListDependents() {
return listDependents;
}
public void setListDependents(List<Dependent> listDependents) {
this.listDependents = listDependents;
}
}
| true |
3bbfeda830edfa8ae201b14ac305a4690c042668 | Java | carlex05/prueba01 | /ItemWeightService/src/main/java/co/carlex/item/dtos/LogDTO.java | UTF-8 | 593 | 1.953125 | 2 | [] | no_license | package co.carlex.item.dtos;
import java.time.LocalDateTime;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.TypeAlias;
import org.springframework.data.mongodb.core.mapping.Document;
/**
*
* @author Carlex
*/
@Data
@Document(collection = "logs")
@TypeAlias("log")
public class LogDTO {
/**
* Fecha del registro de auditoria
*/
private LocalDateTime date;
@Id
private String id;
/**
* Número de documento de la persona que ejecutó
*/
private String document;
}
| true |
d334f1fcefc17624750586febb613bbba63c52c4 | Java | joseildofilho/SisBula | /interfaces/SisBula.java | UTF-8 | 1,960 | 2.703125 | 3 | [] | no_license | package interfaces;
import entidades.*;
import excecoes.JaExisteException;
import excecoes.NaoAchouException;
import java.util.List;
public interface SisBula {
void cadastrarMedicamento(Medicamento m) throws JaExisteException;
void cadastrarMedicamento(String m) throws JaExisteException;
void cadastrarMedicamentoParaDoenca(String nome,String doenca);
void cadastrarMedicamentoParaSintoma(String medicamento, String sintoma);
Medicamento pesquisarMedicamento(String m, Fabricante fab);
Medicamento pesquisarMedicamento(String nome);
List<Medicamento> pesquisarMedicamentoParaSintoma(Sintoma i);
List<Medicamento> pesquisarMedicamentoParaDoenca(Doenca i);
List<Medicamento> pesquisaMedicamentosDoFabricante(Fabricante fab);
void removerMedicamento(Medicamento m);
boolean existeMedicamento(Medicamento m);
List<Medicamento> pesquisarRemediosComSusbstancia(Substancia s);
List<Medicamento> pesquisarPorInteracao(Medicamento medicamento);
public List<Medicamento> pesquisarMedicamentosPara(String nome);
List<Medicamento> getListMedicamento();
void cadastrarSintoma(String nome) throws JaExisteException;
void cadastrarSintoma(Sintoma sintoma) throws JaExisteException;
List<Sintoma> getTodosSintomas();
Sintoma getSintoma(String sintoma) throws NaoAchouException;
void cadastrarDoenca(String doenca) throws JaExisteException;
void cadastrarDoenca(Doenca doenca) throws JaExisteException;
List<Doenca> getTodasDoencas();
void cadastraSintomaDeDoenca(String doenca, String sintoma) throws JaExisteException;
Doenca getDoenca(String nome);
/**
* Grava todos as entidades de deus gerentes em algo
*/
void carregarTodos();
/**
* Carrega todos as entidades em seus respectivos gerentes
*/
void gravarTodos();
void cadastraPossivelCausaDeDoenca(String doenca, String causa) throws JaExisteException;
}
| true |
70dd824ccf83e5a19d7ec7ebc59d17195a9d3baf | Java | FASTTRACKSE/FFSE1704.JavaWeb | /Project/FBMS/src/fasttrackse/ffse1704/fbms/entity/quanlytailieu/dung/TrangThaiDung.java | UTF-8 | 1,418 | 2.078125 | 2 | [] | no_license | package fasttrackse.ffse1704.fbms.entity.quanlytailieu.dung;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "trang_thai_tai_lieu")
public class TrangThaiDung implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6931934795016309418L;
@OneToMany(mappedBy="maTrangThai")
private List<DocumentDung> DocumentDung;
public List<DocumentDung> getDocument() {
return DocumentDung;
}
public void setDocument(List<DocumentDung> documentDung) {
DocumentDung = documentDung;
}
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "ma_trang_thai")
private String maTrangThai;
@Column(name = "ten_trang_thai")
private String tenTrangThai;
//
//
public int getId() {
return id;
}
public String getMaTrangThai() {
return maTrangThai;
}
public void setMaTrangThai(String maTrangThai) {
this.maTrangThai = maTrangThai;
}
public String getTenTrangThai() {
return tenTrangThai;
}
public void setTenTrangThai(String tenTrangThai) {
this.tenTrangThai = tenTrangThai;
}
public void setId(int id) {
this.id = id;
}
}
| true |
72396a1e49b05b32455747125dcc0a42c957c3da | Java | Woodbin/Numerix | /src/ItkenNevill.java | UTF-8 | 1,669 | 3.328125 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Woodbin on 5.10.2014.
*/
public class ItkenNevill {
private ArrayList<Double> polynome = new ArrayList<Double>();
private Double x;
public ItkenNevill(){
}
public ArrayList<Double> count(){
ArrayList<Double> newVals = new ArrayList<Double>(polynome);
for(int i = 1; i<newVals.size();i++){
for(int j = newVals.size()-1; j>=i;j--){
System.out.println(j+" "+i+" :(x)o-(o)o / o ;"+" :x-(j-i): "+(x-(j-i)));
System.out.println(j+" "+i+" :(o)x-(o)o / o ;"+" :get(j): "+newVals.get(j));
System.out.println(j+" "+i+" :(o)o-(x)o / o ;"+" :x-j: "+(x-j));
System.out.println(j+" "+i+" :(o)o-(o)x / o ;"+" :get(j-1): "+newVals.get(j-1));
System.out.println(j+" "+i+" :(o)o-(o)o / x ;"+" :j-(j-i): "+(j-(j-i)));
double itken= (((x-(j-i))*newVals.get(j))-((x-j)*newVals.get(j - 1)))/((j-(j-i)));
System.out.println("ITKEN "+j+" "+i+" :: "+itken);
newVals.set(j, itken);
}
}
return newVals;
}
public void fill(ArrayList<Double> values){
polynome = new ArrayList<Double>(values);
}
public void setX(double newx){
x = new Double(newx);
}
public void test(){
ArrayList<Double> vals = new ArrayList<Double>(Arrays.asList(new Double(3),new Double(4),new Double(4),new Double(3),new Double(0)));
fill(vals);
setX(new Double(2.5));
for (Double aDouble : count()) {
System.out.println(aDouble);
};
}
}
| true |
41289415ba8e112b2640fa0d98200ed4b677d9cb | Java | oscarib/7Turnos | /7Turnos/src/es/edm/services/IOtherServices.java | UTF-8 | 554 | 2 | 2 | [] | no_license | package es.edm.services;
import es.edm.domain.entity.ConfigurationEntity;
import es.edm.domain.entity.StatisticsEntity;
import es.edm.domain.middle.LoginCredentials;
import es.edm.domain.middle.LoginStatus;
public interface IOtherServices {
ConfigurationEntity getConfiguration();
LoginStatus getLoggedUser();
LoginStatus login(LoginCredentials credentials);
StatisticsEntity getStatistics();
String getChainName(int chainNumber);
boolean setConfiguration(ConfigurationEntity conf);
boolean saveChainName(long chainNumber, String chainName);
}
| true |
dd5cf9cf803ae629163c78c410720c7dcfe8d982 | Java | 43ndr1k/Mappinng-Cryptocurrencies-with-News | /backend/src/main/java/de/uni_leipzig/crypto_news_docs/dto/country/CountryCurrencyOutDto.java | UTF-8 | 961 | 2.46875 | 2 | [
"Apache-2.0"
] | permissive | package de.uni_leipzig.crypto_news_docs.dto.country;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class CountryCurrencyOutDto {
/*private static final SimpleDateFormat dateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private Date date;
private Double value;
public CountryCurrencyOutDto() {
}
public CountryCurrencyOutDto(Double value, Date date) {
this.value = value;
this.date = date;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
/*public Date getSubmissionDateConverted() throws ParseException {
return dateFormat.parse(this.date);
}
public void setSubmissionDate(Date date) {
this.date = dateFormat.format(date);
}*/
}
| true |
bc840ad5beb649e471c649a0029b34e7f5f4b67b | Java | elifatagul/kampOdev | /ınterfaceAbstractsDemo/src/ınterfaceAbstractsDemo/Concrete/BaseCustomerService.java | ISO-8859-9 | 169 | 2.03125 | 2 | [] | no_license | package nterfaceAbstractsDemo.Concrete;
import nterfaceAbstractsDemo.Entities.Customer;
public interface BaseCustomerService {
void save (Customer customer);
}
| true |
b2f72be5ef36b467c773e23eed3a4016168a8902 | Java | CodeYuan94/ChantPlatform | /src/main/java/com/github/chant/dao/UserDao.java | UTF-8 | 141 | 1.796875 | 2 | [] | no_license | package com.github.chant.dao;
import com.github.chant.entity.User;
public interface UserDao {
User findByUsername(String username);
}
| true |
4630ce86e64f81807a90d1e501ec47576b238251 | Java | Duthris/AntalyaBilimUniversity | /QuizSolution/src/TestCircle.java | UTF-8 | 271 | 3.0625 | 3 | [] | no_license |
public class TestCircle {
public static void main(String[] args) {
Circle c1 = new Circle();
Circle c2 = new Circle(3,5,10);
System.out.println(c1);
System.out.println(c2);
System.out.println("The Number of Objects is " + Circle.getCount());
}
}
| true |
102a164bda729b132589f0550234f768d52e5775 | Java | Louvivien/Alix | /java/alix/frdo/Mythographies.java | UTF-8 | 1,903 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | package alix.frdo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import alix.fr.Lexik;
import alix.fr.Tokenizer;
import alix.fr.dic.Tag;
import alix.util.Occ;
public class Mythographies
{
PrintWriter csv;
public Mythographies(PrintWriter csv) {
this.csv = csv;
}
/**
* Traverser le texte, ramasser les infos et cracher à la fin
*
* @param code
* @param text
* @throws IOException
*/
public void parse(String text, String source) throws IOException
{
Tokenizer toks = new Tokenizer(text);
Occ occ;
;
while ((occ = toks.word()) != null) {
if (!occ.tag().isName())
continue;
if (occ.tag().equals(Tag.NAMEauthor))
csv.println(source + ";" + occ.orth());
if (occ.tag().equals(Tag.NAME))
System.out.println(occ);
}
csv.flush();
}
/**
* Test the Class
*
* @param args
* @throws IOException
* @throws ParseException
*/
public static void main(String args[]) throws IOException, ParseException
{
// charger le dictionnaire local
Lexik.loadFile("_mythographies/mythographies_dic.csv", Lexik._NAME);
PrintWriter csv = new PrintWriter("_mythographies/mythographies_edges.csv");
csv.println("Source;Target");
Mythographies parser = new Mythographies(csv);
for (final File src : new File("../mythographies").listFiles()) {
if (src.isDirectory())
continue;
String filename = src.getName();
if (filename.startsWith("."))
continue;
if (!filename.endsWith(".xml"))
continue;
parser.parse(new String(Files.readAllBytes(Paths.get(src.toString())), StandardCharsets.UTF_8),
src.getName().substring(0, filename.length() - 4));
}
}
}
| true |
4cf7641c07282526cd9947c806e1070f45926d46 | Java | zhangbin666888/Common-Lib | /src/com/xdg/util/hibernate/UpdateLogic.java | UTF-8 | 156 | 1.8125 | 2 | [] | no_license | package com.xdg.util.hibernate;
import org.hibernate.Session;
public interface UpdateLogic {
void execute(Session session) throws Exception;
}
| true |
3241d95eb91babb4a0188e577d18350f551bfc36 | Java | tnagelkerke/dropwizard-config-encrypt | /src/main/java/com/tn/dw/ConfigDecrypter.java | UTF-8 | 3,256 | 2.703125 | 3 | [
"MIT"
] | permissive | package com.tn.dw;
import com.tn.dw.util.ThrowingConsumer;
import io.dropwizard.Configuration;
import io.dropwizard.jackson.Discoverable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Scans the given object and its children for String fields that match the pattern ENC[enc-val], and attempts to decrypt them.
*
* @author tnagelkerke
*/
public class ConfigDecrypter {
private final EncryptionClient encryptionClient;
public ConfigDecrypter(EncryptionClient encryptionClient) {
this.encryptionClient = encryptionClient;
}
public void decrypt(Object config) {
String scanPackage = getPackage(config);
// get all fields in the (super)class hierarchy
List<Class<?>> classHierarchy = getClassHierarchy(config);
List<Field> fields = classHierarchy.stream().flatMap(clazz -> Stream.of(clazz.getDeclaredFields())).collect(Collectors.toList());
fields.forEach((ThrowingConsumer<Field>) field -> {
field.setAccessible(true);
Object o = field.get(config);
if (o instanceof String) {
String original = (String) o;
Pattern pattern = Pattern.compile("ENC\\[(.*?)\\]");
Matcher matcher = pattern.matcher(original);
if (matcher.find()) {
String decrypted = encryptionClient.decrypt(matcher.group(1));
field.set(config, decrypted);
}
} else {
if (isConfigBean(o, scanPackage)) { // object
decrypt(o);
} else if (o != null && o instanceof Object[]) { // array
Stream.of((Object[]) o).forEach(element -> {
if (isConfigBean(element, scanPackage)) {
decrypt(element);
}
});
} else if (o != null && o instanceof Collection<?>) { // collection
((Collection<?>) o).forEach(element -> {
if (isConfigBean(element, scanPackage)) {
decrypt(element);
}
});
}
}
});
}
private static boolean isConfigBean(Object o, String scanPackage) {
return o != null && !o.getClass().isEnum()
&& (getPackage(o).startsWith(scanPackage) || getPackage(o).startsWith("io.dropwizard") || o instanceof Configuration || o instanceof Discoverable);
}
private static String getPackage(Object o) {
return o != null && o.getClass().getPackage() != null ? o.getClass().getPackage().getName() : "";
}
private static List<Class<?>> getClassHierarchy(Object config) {
List<Class<?>> classes = new ArrayList<>();
Class<?> clazz = config.getClass();
classes.add(clazz);
while (clazz.getSuperclass() != null) {
classes.add(clazz.getSuperclass());
clazz = clazz.getSuperclass();
}
return classes;
}
}
| true |
d2cea041a457fc339ae1dd9e9ce9986275c349e1 | Java | newSue/SFABASE | /src/main/java/com/winchannel/sfa/service/CommonMultiLevelImporter.java | UTF-8 | 1,003 | 1.984375 | 2 | [] | no_license | package com.winchannel.sfa.service;
import java.util.Map;
import com.winchannel.core.importer.ImpConfigurator;
import com.winchannel.core.importer.MultiLevelDataImporter;
/**
*
* @author chenxiangguo
*
*/
public class CommonMultiLevelImporter extends MultiLevelDataImporter {
public CommonMultiLevelImporter(ImpConfigurator conf,
Map<String, Object> params) throws Exception {
super(conf, params);
parentKeyField = conf.getMlParentKey();
KeyField = conf.getMlKey();
parentKeyName = parentKeyField.getName();
keyName = KeyField.getName();
if (conf.getEntityClass().getSimpleName().equals("BaseOrg")) {
name = "orgName";
} else if (conf.getEntityClass().getSimpleName().equals("BaseEmployee")) {
name = "empName";
} else if (conf.getEntityClass().getSimpleName().equals("BaseDictItem")) {
name = "itemName";
} else if (conf.getEntityClass().getSimpleName()
.equals("CommonEntityWithParent")) {
name = "itemName";
}
}
}
| true |
9d447c30a0241bdea3b72774323236180d6f66eb | Java | IZaiarnyi/randomnessBeaconSolution | /src/main/java/beacon/api/entity/Record.java | UTF-8 | 1,187 | 2.453125 | 2 | [] | no_license | package beacon.api.entity;
/**
* Created by Yupa on 24.02.2016.
*/
public class Record {
String version;
String frequency;
String timeStamp;
String seedValue;
String previousOutputValue;
String outputValue;
String signatureValue;
int statusCode;
public Record(){}
public Record( String version, String frequency, String timeStamp, String seedValue, String previousOutputValue, String outputValue, String signatureValue, int statusCode) {
this.version = version;
this.frequency = frequency;
this.timeStamp = timeStamp;
this.seedValue = seedValue;
this.previousOutputValue = previousOutputValue;
this.outputValue = outputValue;
this.signatureValue = signatureValue;
this.statusCode = statusCode;
}
public String getOutputValue() {
return outputValue;
}
public void setOutputValue(String outputValue) {
this.outputValue = outputValue;
}
public String getPreviousOutputValue() {
return previousOutputValue;
}
public void setPreviousOutputValue(String outputValue) {
this.previousOutputValue = outputValue;
}
} | true |
e9164760655cb5cff71c23fe2963f9c0e6df9be3 | Java | IDragonfire/DynamicMarket | /src/bukkitutil/Format.java | UTF-8 | 4,403 | 3.328125 | 3 | [] | no_license | /*
BukkitUtil
Copyright (C) 2011 Klezst
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bukkitutil;
/**
* Provides convenience functions for casting strings to other classes.
*
* @author Klezst
*/
public class Format {
/**
* Returns true, if arg is any of the following; yes, y, true, t, positive, +, affirmative, indubitably, YaY.
*
* @param arg
* The String to turn into a boolean.
*
* @return true, if arg is any of the following; yes, y, true, t, positive, +, affirmative, indubitably, YaY.
*
* @author Klezst
*/
@SuppressWarnings("boxing")
public static Boolean parseBoolean(String arg) {
boolean result = false;
if (Util.isAny(arg, "yes", "y", "true", "t", "positive", "+",
"affirmative", "indubitably", "YaY")) {
result = true;
}
return result;
}
/**
* Returns a Double of the value represented by arg
*
* @param arg
* The String to turn into a Double.
*
* @return a Double of the value represented by arg.
*
* @throws NumberFormatException
* If arg is not a valid Double.
*
* @author Klezst
*/
@SuppressWarnings("boxing")
public static Double parseDouble(String arg) throws NumberFormatException {
Double result;
if (Util.isAny(arg, "inf", "+inf")) {
result = Double.MAX_VALUE;
} else if (arg.equalsIgnoreCase("-inf")) {
result = Double.MIN_VALUE;
} else {
// throws NumberFormatException, if arg isn't a valid Double.
result = Double.parseDouble(arg);
}
return result;
}
/**
* Returns an Integer of the value represented by arg.
*
* @param arg
* The String to turn into an Integer.
*
* @return an Integer of the value represented by arg.
*
* @throws NumberFormatException
* If arg is not a valid Integer.
*
* @author Klezst
*/
@SuppressWarnings("boxing")
public static Integer parseInteger(String arg) throws NumberFormatException {
Integer result;
if (Util.isAny(arg, "inf", "+inf")) {
result = Integer.MAX_VALUE;
} else if (arg.equalsIgnoreCase("-inf")) {
result = Integer.MIN_VALUE;
} else {
// throws NumberFormatException, if arg isn't a valid Integer.
result = Integer.parseInt(arg);
}
return result;
}
/**
* Returns a String representing arg.
*
* @param arg
* The boolean to turn into a String.
*
* @return a String representing arg.
*
* @author Klezst
*/
public static String parseString(boolean arg) {
String result = "'False'";
if (arg) {
result = "'True'";
}
return result;
}
/**
* Returns a String representing arg.
*
* @param arg
* The double to turn into a String.
*
* @return a String representing arg.
*
* @author Klezst
*/
public static String parseString(double arg) {
String result;
if (arg == Double.MAX_VALUE) {
result = "'+INF'";
} else if (arg == Double.MIN_VALUE) {
result = "'-INF'";
} else {
result = "" + arg;
}
return result;
}
/**
* Returns a String representing arg.
*
* @param arg
* The int to turn into a String.
*
* @return a String representing arg.
*
* @author Klezst
*/
public static String parseString(int arg) {
String result;
if (arg == Integer.MAX_VALUE) {
result = "'+INF'";
} else if (arg == Integer.MIN_VALUE) {
result = "'-INF'";
} else {
result = "" + arg;
}
return result;
}
}
| true |
033fff725781c6fb5ac187189ae4a5b659148abb | Java | Samsaralife/MyPersonalLearning | /src/main/java/com/cugb/dao/ProductMapper.java | UTF-8 | 664 | 2.078125 | 2 | [] | no_license | package com.cugb.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.cugb.entity.Product;
@Mapper
public interface ProductMapper {
//插入商品
public int insertProduct(Product product);
//获取产品
public Product getProduct(@Param("id")Long id);
//扣减产品
public int decreaseProduct(@Param("id")Long id, @Param("quantity")int quantity,@Param("version")int version);
//批量插入产品
public int batchInsertProduct(List<Product> products);
//更新产品
public int updateProduct(Product product);
//删除产品
public int deleteProduct(Long productId);
}
| true |
89709f7543a23311a7faf6d08da7ac506873ed97 | Java | FranciscoValadez/Course-Work | /Java/HW 11/Phone.java | UTF-8 | 2,768 | 4.03125 | 4 | [] | no_license | //Written by: Francisco Valadez
//Assignment: HW 11 - Pg. 150 - #4.15
//Class: CS 113
//Date: 5/26/2021
//Description: This program displays the corresponding number of a letter
import java.util.Scanner;
public class Phone
{
public static void main(String[] args)
{
String letter = "";
Scanner input = new Scanner(System.in);
System.out.println("This program displays the corresponding number for a letter");
System.out.print("Enter a letter: ");
letter = input.next();
//These else if statements check the value of the users input
if(letter.equals("A") || letter.equals("a") || letter.equals("B") || letter.equals("b") || letter.equals("C") || letter.equals("c"))
{
System.out.println("The corresponding number is " + 2);
}
else if(letter.equals("D") || letter.equals("d") || letter.equals("E") || letter.equals("e") || letter.equals("F") || letter.equals("f"))
{
System.out.println("The corresponding number is " + 3);
}
else if(letter.equals("G") || letter.equals("g") || letter.equals("H") || letter.equals("h") || letter.equals("I") || letter.equals("i"))
{
System.out.println("The corresponding number is " + 4);
}
else if(letter.equals("J") || letter.equals("j") || letter.equals("K") || letter.equals("k") || letter.equals("L") || letter.equals("l"))
{
System.out.println("The corresponding number is " + 5);
}
else if(letter.equals("M") || letter.equals("m") || letter.equals("N") || letter.equals("n") || letter.equals("O") || letter.equals("o"))
{
System.out.println("The corresponding number is " + 6);
}
else if(letter.equals("P") || letter.equals("p") || letter.equals("Q") || letter.equals("q") || letter.equals("R") || letter.equals("r") || letter.equals("S") || letter.equals("s"))
{
System.out.println("The corresponding number is " + 7);
}
else if(letter.equals("T") || letter.equals("t") || letter.equals("U") || letter.equals("u") || letter.equals("V") || letter.equals("v"))
{
System.out.println("The corresponding number is " + 8);
}
else if(letter.equals("W") || letter.equals("w") || letter.equals("X") || letter.equals("x") || letter.equals("Y") || letter.equals("y") || letter.equals("Z") || letter.equals("z"))
{
System.out.println("The corresponding number is " + 9);
}
else if(letter.equals(" "))
{
System.out.println("The corresponding number is " + 0);
}
else
System.out.println(letter + " is an invalid input");
}
}
| true |
23871dbef61b283f634d1580e7f8f8366394eefe | Java | mgrxf/leetcode | /src/lc1018.java | UTF-8 | 533 | 2.578125 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.List;
public class lc1018 {
public List<Boolean> prefixesDivBy5(int[] A) {
int n = A.length;
List<Boolean> list = new ArrayList<>();
if(n==0)return list;
int p=0;
for(int i=0;i<A.length;i++)
{
p =((p<<1)+A[i])%5;
if(p==0)list.add(true);
else list.add(false);
}
// System.out.println(judge(A,1));
return list;
}
}
| true |
83e7029edec91f1b74a4366e3d079e3daa6a68c0 | Java | AntonSimeonov/firebase-messging | /app/src/main/java/ninja/paranoidandroid/firebasemessaging/models/Task.java | UTF-8 | 2,085 | 2.296875 | 2 | [] | no_license | package ninja.paranoidandroid.firebasemessaging.models;
/**
* Created by anton on 25.08.16.
*/
public class Task {
private String name;
private String projectID;
private String parentTaskID;
private int priority;
private String dateOfCreation;
private String dateOfExecution;
private String dateOfCompletion;
private String problem;
private String notes;
private boolean status;
public Task(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentTaskID() {
return parentTaskID;
}
public void setParentTaskID(String parentTaskID) {
this.parentTaskID = parentTaskID;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public String getDateOfCreation() {
return dateOfCreation;
}
public void setDateOfCreation(String dateOfCreation) {
this.dateOfCreation = dateOfCreation;
}
public String getDateOfExecution() {
return dateOfExecution;
}
public void setDateOfExecution(String dateOfExecution) {
this.dateOfExecution = dateOfExecution;
}
public String getDateOfCompletion() {
return dateOfCompletion;
}
public void setDateOfCompletion(String dateOfCompletion) {
this.dateOfCompletion = dateOfCompletion;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getProjectID() {
return projectID;
}
public void setProjectID(String projectID) {
this.projectID = projectID;
}
}
| true |
6c3bc631505438aa8a613d429880a693954e8075 | Java | ardi87/JavaProjectsArdi | /detyratEshtepise/src/detyra1/Detyra1.java | UTF-8 | 275 | 2.4375 | 2 | [] | no_license | package detyra1;
public class Detyra1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] numbers = { "*", "**", "***", "****", "*****" };
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
| true |
fccc4225a79a86ecb95c28542282352c1e99d0f9 | Java | terasolunaorg/terasoluna-gfw | /terasoluna-gfw-common-libraries/terasoluna-gfw-codepoints/src/test/java/org/terasoluna/gfw/common/codepoints/validator/Name_Collection.java | UTF-8 | 1,445 | 1.8125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright(c) 2013 NTT DATA Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.terasoluna.gfw.common.codepoints.validator;
import java.util.List;
import org.terasoluna.gfw.common.codepoints.ConsistOf;
public class Name_Collection {
private List<@ConsistOf(AtoF.class) String> firstNames;
private List<@ConsistOf(GtoL.class) String> lastNames;
public Name_Collection(List<String> firstNames, List<String> lastNames) {
this.firstNames = firstNames;
this.lastNames = lastNames;
}
public Name_Collection() {
}
public List<String> getFirstNames() {
return firstNames;
}
public void setFirstNames(List<String> firstNames) {
this.firstNames = firstNames;
}
public List<String> getLastNames() {
return lastNames;
}
public void setLastNames(List<String> lastNames) {
this.lastNames = lastNames;
}
}
| true |
f6f109207929214fba0471474e1e7d517ea5eb76 | Java | Liuguozhu/MyWork | /src/main/java/iyunu/NewTLOL/net/TLOLMessageHandler.java | UTF-8 | 3,136 | 2.03125 | 2 | [] | no_license | package iyunu.NewTLOL.net;
import iyunu.NewTLOL.base.net.socket.ProtocolHandler;
import iyunu.NewTLOL.manager.ServerManager;
import iyunu.NewTLOL.model.role.Role;
import iyunu.NewTLOL.redis.Redis;
import iyunu.NewTLOL.service.iface.auction.AuctionService;
import iyunu.NewTLOL.service.iface.bulletin.BulletinService;
import iyunu.NewTLOL.service.iface.gang.GangService;
import iyunu.NewTLOL.service.iface.mail.MailService;
import iyunu.NewTLOL.service.iface.payActivity.PayBackService;
import iyunu.NewTLOL.service.iface.role.RoleServiceIfce;
import iyunu.NewTLOL.service.iface.user.UserService;
import org.jboss.netty.channel.Channel;
public abstract class TLOLMessageHandler extends Redis implements ProtocolHandler {
protected Role online;
protected Channel channel;
protected RoleServiceIfce roleService;
protected AuctionService auctionService;
protected BulletinService bulletinService;
protected MailService mailService;
protected GangService gangService;
protected UserService userService;
protected PayBackService payBackService;
@Override
public void preHandle(Channel channel) {
this.channel = channel;
online = ServerManager.instance().getOnlinePlayer(channel);
if (online != null) {
// 暂时无操作
}
}
public RoleServiceIfce getRoleService() {
return roleService;
}
public void setRoleService(RoleServiceIfce roleService) {
this.roleService = roleService;
}
/**
* @return the auctionService
*/
public AuctionService getAuctionService() {
return auctionService;
}
/**
* @param auctionService
* the auctionService to set
*/
public void setAuctionService(AuctionService auctionService) {
this.auctionService = auctionService;
}
public BulletinService getBulletinService() {
return bulletinService;
}
public void setBulletinService(BulletinService bulletinService) {
this.bulletinService = bulletinService;
}
/**
* @return the mailService
*/
public MailService getMailService() {
return mailService;
}
/**
* @param mailService
* the mailService to set
*/
public void setMailService(MailService mailService) {
this.mailService = mailService;
}
/**
* @return the gangService
*/
public GangService getGangService() {
return gangService;
}
/**
* @param gangService
* the gangService to set
*/
public void setGangService(GangService gangService) {
this.gangService = gangService;
}
/**
* @return the userService
*/
public UserService getUserService() {
return userService;
}
/**
* @param userService
* the userService to set
*/
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* @return the payBackService
*/
public PayBackService getPayBackService() {
return payBackService;
}
/**
* @param payBackService
* the payBackService to set
*/
public void setPayBackService(PayBackService payBackService) {
this.payBackService = payBackService;
}
}
| true |
fd314de74c56ffcfbe9ca311929c15d4d1c0b099 | Java | CS151-KGB/MazeSolver | /src/test/Maze.java | UTF-8 | 4,332 | 2.984375 | 3 | [] | no_license | package test;
import org.eclipse.wb.swt.widgets.Display;
import org.eclipse.wb.swt.widgets.Label;
import org.eclipse.wb.swt.widgets.Shell;
//Just adding some code to test committing through eclipse
import org.eclipse.wb.swt.events.MouseEvent;
import org.eclipse.wb.swt.events.MouseAdapter;
import org.eclipse.wb.swt.SWT;
import org.eclipse.wb.swt.SWTResourceManager;
public class Maze {
protected Shell shell;
int height;
int width;
int matrixSize = 6;
int index = 0;
final Label[] wallw = new Label[36];
final Label[] wallh = new Label[36];
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
Maze window = new Maze();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(600, 800);
shell.setText("SWT Application");
shell.setLayout(null);
height = 4;
width = 4;
//Dimension wallDim = new Dimension(150,20);
for(int k = 0; k < matrixSize; k++)
{
for(int i = 0; i < matrixSize; i++)
{
index = i + matrixSize * k;
//System.out.println(index);
wallw[index]=new Label(shell, SWT.None);
wallw[index].setText(Integer.toString(index));
//set Colors
wallw[index].setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
wallw[index].setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
//set Locations
wallw[index].setBounds(150*k, 150*i, 150, 15);
wallw[index].addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e)
{
String mouseE = e.toString();
System.out.println(mouseE);
String[] info = mouseE.split(" ");
System.out.println(info[1]);
String deta[] = info[1].split("\\{");
String deta1[] = deta[1].split("\\}");
System.out.println("deta = "+ deta[1]);
System.out.println("deta1 = "+ deta1[0]);
int newIndex = Integer.parseInt(deta1[0]);
System.out.println("in wallw, index = " + index);
System.out.println("before if wallw");
if(wallw[newIndex].getBackground().equals(SWTResourceManager.getColor(SWT.COLOR_BLACK)))
{
System.out.println("in if wallw");
wallw[newIndex].setBackground(SWTResourceManager.getColor(SWT.COLOR_DARK_MAGENTA));
}
else
{
System.out.println("in else wallw");
wallw[newIndex].setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
}
}
});//addMouseListener
}//for-i
}//for-k
for(int k = 0; k < matrixSize; k++)
{
for(int i = 0; i < matrixSize; i++)
{
index = i + matrixSize*k;
wallh[index] = new Label(shell, SWT.None);
wallh[index].setText(Integer.toString(index));
wallh[index].setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
wallh[index].setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
wallh[index].setBounds(150*k, 150*i, 20, 150);
wallh[index].addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e)
{
String mouseE = e.toString();
System.out.println(mouseE);
String[] info = mouseE.split(" ");
System.out.println(info[1]);
String deta[] = info[1].split("\\{");
String deta1[] = deta[1].split("\\}");
System.out.println("deta = "+ deta[1]);
System.out.println("deta1 = "+ deta1[0]);
int newIndex = Integer.parseInt(deta1[0]);
System.out.println("in wallw, index = " + index);
System.out.println("before if wallw");
if(wallh[newIndex].getBackground().equals(SWTResourceManager.getColor(SWT.COLOR_BLACK)))
{
System.out.println("in if wallw");
wallh[newIndex].setBackground(SWTResourceManager.getColor(SWT.COLOR_DARK_MAGENTA));
}
else
{
System.out.println("in else wallw");
wallh[newIndex].setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
}
}
});//addMouseListener
}//for i
}//for k
}
}
| true |
e4a23790e1599d0f595ce3dcdf5c5926872bea87 | Java | AlievShamil/TestNg | /src/test/java/MyTest.java | UTF-8 | 1,614 | 2 | 2 | [] | no_license | import org.testng.annotations.Test;
import steps.*;
import java.util.LinkedHashMap;
public class MyTest extends BaseSteps {
MainPageSteps mainPageSteps = new MainPageSteps();
RegistrationPageSteps registrationPageSteps = new RegistrationPageSteps();
MailPageSteps mailPageSteps = new MailPageSteps();
LoginPageSteps loginPageSteps = new LoginPageSteps();
LinkedHashMap<String,String> testData = new LinkedHashMap<>();
@Test(description = "Регистрация на ebay и поиск товара")
public void test() {
testData.put("Эл. почта","aplanatestng1@mail.ru");
testData.put("Подтверждение эл. почты","aplanatestng1@mail.ru");
testData.put("Пароль","123N123_nb");
testData.put("Имя","Иван");
testData.put("Фамилия","Иванов");
mainPageSteps.goToRegistrationPage();
registrationPageSteps.fillFields(testData);
registrationPageSteps.clickToRegistration();
registrationPageSteps.gotoMail();
testData.put("Password","123N123_nb");
mailPageSteps.signInMail(testData);
mailPageSteps.checkRelevanceOfLetter();
mailPageSteps.gotoEbay();
mainPageSteps.goToLoginPage();
testData.clear();
testData.put("Эл. почта","aplanatestng1@mail.ru");
testData.put("Пароль","123N123_nb");
loginPageSteps.fillFields(testData);
loginPageSteps.login();
mainPageSteps.searchBlackberry();
mainPageSteps.displayAmount();
mainPageSteps.signOut();
mainPageSteps.checkSignOut();
}
}
| true |
89db3e619f451f40d40ca9c99ea2f6dff55970e7 | Java | arikwex/maslab-sim-2015 | /src/map/geom/Obstacle.java | UTF-8 | 2,779 | 2.71875 | 3 | [] | no_license | package map.geom;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.LinkedList;
import java.util.List;
import core.Config;
import map.Map;
public abstract class Obstacle extends Polygon {
private Polygon minCSpace = null;
private Polygon maxCSpace = null;
public abstract Color getColor();
public abstract void generateObstacleData();
public void paint(Graphics2D g) {
g.setColor(getColor());
g.fill(getPath());
}
public Polygon getMaxCSpace() {
if (maxCSpace == null) {
double r = Map.getInstance().bot.getMaxRadius();
maxCSpace = computeNaiveCSpace(r + Config.CSPACE_EXTRA_BUFFER);
}
return maxCSpace;
}
public Polygon getMinCSpace() {
if (minCSpace == null) {
double r = Map.getInstance().bot.getMinRadius();
minCSpace = computeNaiveCSpace(r);
}
return minCSpace;
}
private Polygon computeNaiveCSpace(double r) {
List<Point> csoPoints = new LinkedList<Point>();
List<Point> roVertices = this.getVertices();
for (Point p : roVertices) {
for (double t = 0; t <= Math.PI * 2; t += Math.PI / Config.CSPACE_RADIUS_SEGMENTS)
csoPoints.add(new Point(p.x + r * Math.cos(t), p.y + r * Math.sin(t)));
}
return GeomUtils.convexHull(csoPoints);
}
public Polygon getPolyCSpace(Polygon bot) {
List<Point> csoPoints = new LinkedList<Point>();
List<Point> roVertices = getVertices();
for (Point v : roVertices)
for (Point p : bot.getVertices())
csoPoints.add(new Point(v.x - p.x, v.y - p.y));
return GeomUtils.convexHull(csoPoints);
}
public boolean intersects(Segment seg, double theta) {
if (getMaxCSpace().intersects(seg) || getMaxCSpace().contains(seg.start) || getMaxCSpace().contains(seg.end)) {
Robot bot = Map.getInstance().bot;
Polygon polyC = getPolyCSpace((bot.getRotated(seg.theta)));
if (polyC.intersects(seg)) {
return true;
}
if (polyC.contains(seg.start)) {
return true;
}
if (polyC.contains(seg.end)) {
return true;
}
for (Point p : bot.rotatedPoints(theta, seg.theta, seg.start)) {
if (this.contains(p)) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
String s = "[";
for (Point p : points) {
s += "(" + p.x + ", " + p.y + ")";
}
s = s.substring(0, s.length() - 1);
s += "]";
return s;
}
}
| true |
3768006ce1a47bfd8cd20d6579df8c47d34f6cda | Java | lj199117/OfferCode | /src/com/hnu/sort/pojo/PersonImpComparator.java | UTF-8 | 494 | 3.34375 | 3 | [] | no_license | package com.hnu.sort.pojo;
import java.util.Comparator;
public class PersonImpComparator implements Comparator<Person>{
/**
* 这个类是一个比较器,Collections.sort( personList , new PersonImpComparator()) 可以对其排序
* 对两个类,我定义一个什么样的规则进行排序
*/
public int compare(Person o1, Person o2) {
// TODO Auto-generated method stub
if(o1.getAge() > o2.getAge()) return 1;
else if(o1.getAge() < o2.getAge()) return -1;
return 0;
}
}
| true |
71351670807fa750391dc3c85e10b7e543f63649 | Java | mohit117/WebApiAutomation | /src/org/api/testcases/SolrXGNSTest.java | UTF-8 | 17,625 | 2.21875 | 2 | [] | no_license | package org.api.testcases;
import static io.restassured.RestAssured.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.List;
import java.util.Map;
import org.api.base.TestConfig;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
//import org.testng.annotations.Test;
import org.junit.Test;
import org.testng.asserts.SoftAssert;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static org.hamcrest.Matchers.*;
public class SolrXGNSTest extends TestConfig{
//Hiiting first seaech api url using path and query parameters
@Test
public void gettingResponseAsStringTestForXGNs()
{
String responseBody = given().
spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}").
asString();
System.out.println(responseBody);
}
//extracting all pps from the response
@Test
public void extractingAllPPs()
{
Response res = given().
spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}").
then().
contentType(ContentType.JSON).
extract().
response();
List<String> ppIds = res.path("organicZoneInfo.products.ppId");
for(String ppid : ppIds)
{
System.out.println(ppid);
}
}
//extracting all facetIds
@Test
public void extractingAllFacetIds()
{
Response res = given().
spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}").
then().
contentType(ContentType.JSON).
extract().
response();
List<Integer> facetIds = res.path("facets.facetList.facetId");
for(int facetId : facetIds)
{
System.out.println(facetId);
}
}
//extracting all Facet Types
@Test
public void extractingAllFacetType()
{
Response res = given().
spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}").
then().
contentType(ContentType.JSON).
extract().
response();
List<String> facetTypes = res.path("facets.facetList.facetType");
for(String facetType : facetTypes)
{
System.out.println(facetType);
}
}
//Way for Checking if first facet name is store availablility of not
@Test
public void validateFirstFacetNameUsingJava()
{
Response res = given().
spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
List<String> facetnames = res.path("facets.facetList.facetName");
//System.out.println(facetnames);
if(facetnames.get(0).equals("Store Availability"))
{
System.out.println("First facet is store availability");
}
else
{
System.out.println("First facet is not store availability");
}
}
//another way********using HAMECREST ASSERTIONS******** for Checking if first facet name is store availablility of not
@Test
public void validateFirstFacetNameUsingHemcrest()
{
given().
spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}").
then().
body("facets.facetList[0].facetName", equalTo("Store Availability"));
}
//another way********using JUNIT ASSERTIONS******** for Checking if first facet name is store availablility of not
@Test
public void validateFirstFacetNameUsingJunitAssert()
{
Response res = given().
spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
List<String> facetnames = res.path("facets.facetList.facetName");
//System.out.println(facetnames);
Assert.assertEquals(facetnames.get(0), "Store Availability");
}
//validating imageinfo for a single pp
@Test
public void validateImageInfoForSinglePP()
{
Response res = given().spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
String imageInfo = res.path("organicZoneInfo.products.find{it.ppId = 'ppr5007250974'}.imagesInfo").toString();
if(imageInfo.isEmpty())
{
System.out.println("ImageInfo is blank");
}
else
{
System.out.println(imageInfo);
}
}
//*****To get all the imageinfo details of all the PPs using Java List and Maps**********************
@Test
public void getImageInfoAttributeForAllPPs()
{
Response res = given().
spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
List<Map<String,Object>> allimageinfo = res.path("organicZoneInfo.products");
System.out.println(allimageinfo.size());
for(Map<String, Object> map : allimageinfo)
{
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if(key.equalsIgnoreCase("imagesInfo"))
{
System.out.println(key);
System.out.println(value);
}
}
}
}
//*****To get all the imageinfo details of all the PPs using Hemcrest Matchres**********************
@Test
public void validateImageInfoUsingHemcrest()
{
}
//********Validate the channel name of the response using JAVA****************
@Test
public void validateChannelNameUsingJava()
{
Response res = given().spec(solr_requestSpec).
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
String channelName = res.path("channelName");
if(channelName.equalsIgnoreCase("SOLR-API"))
{
System.out.println("Channel Name is matching and value is "+channelName);
}
else
{
System.out.println("Channel name is not matching" );
}
}
//********Validate the channel name of the response using HEMCREST MATCHERS****************
@Test
public void validateChannelNameUsingHamcrest()
{
given().spec(solr_requestSpec).
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}").
then().
body("channelName", equalTo("SOLR-API"));
}
//********Validate the channel name of the response using JUNIT ASSERT****************
@Test
public void validateChannelNameUsingJunitAssert()
{
Response res = given().spec(solr_requestSpec).
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
String channelName = res.path("channelName");
Assert.assertEquals("SOLR-API", channelName);
}
//**************validate if a specific sort option is present inside a Sort list or not
//using USE OF hasItem() METHOD ********************************
@Test
public void validateSortNameInsideListUsingHamcrest()
{
given().spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}").
then().
body("sortOptions.name", hasItem("price low - high"));
}
//**************validate if a specific sort option is present inside a Sort list or not
//using USE OF hasItem() METHOD ********************************
@Test
public void validateSortNameInsideListUsingJunitAssert()
{
Response res = given().spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
List<String> sortOptions = res.path("sortOptions.name");
Assert.assertNotNull(sortOptions); //to make sure that list is not null
//Assert.assertNull(sortOptions); // to make sure that list is null. If not null then test will fail
Assert.assertEquals(sortOptions.get(3), "price low - high");
}
/* In the above method, the probelem is, we should know already the index of the sort option we want to check.
To overcome this issue, we should use hasItem method of hemcrest as below*/
@Test
public void validateSortNameInsideListUsingHemcreast()
{
Response res = given().spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
List<String> sortOptions = res.path("sortOptions.name");
assertThat(sortOptions, hasItem("price low - high"));
}
//**************validate if a specific sort option is present inside a Sort list or not
//using JAVA ****************************************************
@Test
public void validateInfoPresentInsideListUsingJava()
{
Response res = given().spec(solr_requestSpec).log().all().
pathParam("searchTerm", "shirts").
queryParam("Ntt", "shirts").
when().
get("/s/{searchTerm}");
List<String> sortOptions = res.path("sortOptions.name");
System.out.println(sortOptions);
for(String soption : sortOptions)
{
if(soption.equalsIgnoreCase("price low - high"))
{
System.out.println("Price low to high sort option is available");
}
}
}
//Print sort option where order of sort option is 2 using Gpath find method
@Test
public void getAllSortDetailsBasedOnKeyOrOrderNumber()
{
Response res= given().spec(solr_requestSpec).log().all().
pathParam("searchTerm", "pants").queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
//Map<String,?> allSortDetailsForSingleSort = res.path("sortOptions.find{ it.order == 3 }");
Map<String,?> allSortDetailsForSingleSort = res.path("sortOptions.find{ it.key == 'NA' }");
System.out.println(allSortDetailsForSingleSort);
}
//Validate the order of all the sort options
@Test
public void validateOrderOfSortOptions()
{
}
//Print product details for single pp where oppid is given using Gpath find method
@Test
public void validateProductsWithPPID()
{
Response res= given().spec(solr_requestSpec).log().all().
pathParam("searchTerm", "pants").queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
Map<String,?> allSortDetailsForSinglePP = res.path("organicZoneInfo.products.find { it.ppId == 'pp5007530807' }");
Assert.assertNotNull(allSortDetailsForSinglePP);
System.out.println(allSortDetailsForSinglePP);
}
@Test
public void actualEndpoint() {
Response response = get("https://services.integration3a.dp-dev.jcpcloud2.net/v1/search-service/s/pants?Ntt=pants");
Map<String, ?> allDetailsForSinglePP = response.path("organicZoneInfo.products.find { it.ppId == 'pp5007530807' }");
System.out.println(allDetailsForSinglePP);
}
//Getting the name and minipdp status of the single pp whoes brand is white mark
//It will return first pp which matches with the brand when more than 1 items are available with the same brand
@Test
public void validateEnableMiniPDP()
{
Response res = given().spec(solr_requestSpec).log().all().
pathParameter("searchTerm", "pants").
queryParam("Ntt", "pants").
when().
get("/s/{searchTerm}");
String ppname = res.path("organicZoneInfo.products.find {it.brand == 'white mark'}.name");
Boolean minipdpStatus = res.path("organicZoneInfo.products.find {it.brand == 'white mark'}.enableMiniPDP");
//getting value of thumbnailImageId of a pp which is present inside imagesInfo array of a products array
String imagesInfo = res.path("organicZoneInfo.products.find {it.brand == 'white mark'}.imagesInfo.thumbnailImageId");
//NOT WORKING BELOW
String availabilityStatus = res.path("organiczoneInfo.products.find {it.brand == 'white mark'}.availabilityStatus.message");
System.out.println(ppname);
System.out.println(minipdpStatus);
System.out.println(imagesInfo);
System.out.println(availabilityStatus);
}
//Getting all pps for which minipdp is true
@Test
public void getListOfAllPPWhereMiniPDPisTrue()
{
Response res = given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
List<String> listofPPs= res.path("organicZoneInfo.products.findAll{ it.enableMiniPDP == true}.ppId");
if(listofPPs.isEmpty())
{
System.out.println("No items found with mini pdp as true");
}
else
{
for(String pp : listofPPs )
{
System.out.println(pp);
}
}
}
//Getting list of pps for which minipdp is true
@Test
public void validateSinglePDPForMiniPDP()
{
Response res = given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
String pdpurl = res.path("organicZoneInfo.products.find {it.enableMiniPDP == true}.pdpUrl");
System.out.println(pdpurl);
if(pdpurl.contains("pTmplType=regular") || pdpurl.contains("pTmplType=sephora"))
{
System.out.println("This PP is haivng mini PDP as true");
}
//String str = pdpurl.substring(pdpurl.lastIndexOf("/") + 1, url.indexOf("?"));
/*List<String> listofPPs= res.path("organicZoneInfo.products.findAll{ it.currentMin > 50}.ppId");
for(String pp : listofPPs )
{
System.out.println(pp);
}*/
}
//NEED TO WORK MORE ON THIS -------------------------Validating the template type of pps for which mini pdp is set to true
//and if it is false then get the pp id of the pp from pdp url
// need to work on how to get the pdp ids from the pdp url
@Test
public void getListOfPPsWithMiniPdpAsTrue()
{
Response res = given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
List<String> listofPDPURLs= res.path("organicZoneInfo.products.findAll {it.enableMiniPDP == true}.pdpUrl");
for(String pdpurl : listofPDPURLs)
{
if(pdpurl.contains("pTmplType=regular") || pdpurl.contains("pTmplType=sephora"))
{
System.out.println("This PP is haivng mini PDP as true");
}
}
}
//getting all the pps for which price is greater than 50
@Test
public void getListOfPPsForPriceMoreThan50()
{
Response res = given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
List<String> listofPPs= res.path("organicZoneInfo.products.findAll{ it.currentMin > 50}.ppId");
for(String pp : listofPPs )
{
System.out.println(pp);
}
}
//Get names of all pps for which price is greater than 20 and brand is worthington
@Test
public void fetListOfPPsForPriceMoreThan20AndBrandIsWorthington()
{
Response res = given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
List<String> listofPPs= res.path(
"organicZoneInfo.products.findAll{ it.currentMin > 20}.findAll{it.brand == 'worthington'}.name");
if(listofPPs.isEmpty())
{
System.out.println("There are no items mathing with the given criteria");
}
else
{
for(String pp : listofPPs )
{
System.out.println(pp);
}
}
}
//Get names of all pps for which price is greater than 20 and brand is worthington
@Test
public void fetListOfSlaePPsAndBrandIsWorthington()
{
Response res = given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
List<String> listofPPs= res.path(
"organicZoneInfo.products.findAll{ it.currentPriceLabel == 'sale'}.findAll{it.brand == 'worthington'}.name");
if(listofPPs.isEmpty())
{
System.out.println("There are no items mathing with the given criteria");
}
else
{
for(String pp : listofPPs )
{
System.out.println(pp);
}
}
}
//************Asserting a List using assertThat method to validate if currentprice label contains original************
@Test
public void assertAList()
{
Response res = given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
List<String> pricelabels = res.path("organicZoneInfo.products.currentPriceLabel");
assertThat(pricelabels, hasItem("original"));
}
//************Asserting a List using body to validate if currentprice label contains original*************************************
@Test
public void assertAListUsingBodyMethod()
{
given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}").
then().body("organicZoneInfo.products.currentPriceLabel", hasItem("original"));
}
//Asseting a List using assertThat method to validate multiple currentprice labels
@Test
public void assertMultipleValuesPresentInList()
{
Response res = given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}");
List<String> pricelabels = res.path("organicZoneInfo.products.currentPriceLabel");
assertThat(pricelabels, hasItems("original", "sale"));
}
//Asseting a List using body method to validate multiple currentprice labels
@Test
public void assertAListForMultipleValuesUsingBodyMethod()
{
given().spec(solr_requestSpec).log().all().pathParam("searchTerm", "pants").
queryParam("Ntt", "pants").
when().get("/s/{searchTerm}").
then().body("organicZoneInfo.products.currentPriceLabel", hasItems("original", "sale"));
}
}
| true |
db2f2f55540fbb4d1656fa7d993f9f16b0d50ac7 | Java | bigbilii/G-FoodShop | /gfoodshop-manager-web/src/main/Java/me/guoxin/manager/controller/ValidateController.java | UTF-8 | 1,789 | 2.078125 | 2 | [] | no_license | package me.guoxin.manager.controller;
import me.guoxin.utils.GeetestLib;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
/**
* 申请验证码
*/
@Controller
public class ValidateController {
@Resource
private GeetestLib geetestLib;
@RequestMapping(value = "/getValidate", method = RequestMethod.GET)
public void getValidateCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
GeetestLib gtSdk = geetestLib;
String resStr = "{}";
// 自定义userid
String userid = "gfsUserId";
// 用户ip
String ip_address = request.getRemoteAddr();
if (ip_address == null || "".equalsIgnoreCase(ip_address.trim())) {
ip_address = "unknow";// 这是为未知
}
HashMap<String, String> param = new HashMap<String, String>();
param.put("user_id", userid); //网站用户id
param.put("ip_address", ip_address); //传输用户请求验证时所携带的IP
// 进行验证预处理
int gtServerStatus = gtSdk.preProcess(param);
// 将服务器状态设置到session中
request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
// 将userid设置到session中
request.getSession().setAttribute("userid", userid);
resStr = gtSdk.getResponseStr();
PrintWriter out = response.getWriter();
out.println(resStr);
}
}
| true |
99835ad3c6a532ffd74631fea90c7deee0536046 | Java | lakshmi-priya-github/dice-roll-simulator-app | /src/main/java/com/diceroll/entity/DiceRollResult.java | UTF-8 | 784 | 2.125 | 2 | [] | no_license | package com.diceroll.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "dice_roll_result")
public class DiceRollResult {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "dice_roll_id", nullable = false)
private DiceRoll diceRoll;
private int sum;
private int occurence;
}
| true |
bbf5838333ce1a8e4ece345f1ccc9d945c34089a | Java | commercetools/commercetools-sdk-java-v2 | /commercetools/commercetools-sdk-java-history/src/main/java-generated/com/commercetools/history/models/common/TextLineItem.java | UTF-8 | 5,508 | 2.5 | 2 | [
"Apache-2.0",
"GPL-2.0-only",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"BSD-3-Clause",
"Classpath-exception-2.0"
] | permissive |
package com.commercetools.history.models.common;
import java.time.*;
import java.util.*;
import java.util.function.Function;
import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.*;
import io.vrap.rmf.base.client.utils.Generated;
/**
* TextLineItem
*
* <hr>
* Example to create an instance using the builder pattern
* <div class=code-example>
* <pre><code class='java'>
* TextLineItem textLineItem = TextLineItem.builder()
* .addedAt("{addedAt}")
* .custom(customBuilder -> customBuilder)
* .description(descriptionBuilder -> descriptionBuilder)
* .id("{id}")
* .name(nameBuilder -> nameBuilder)
* .quantity(1)
* .build()
* </code></pre>
* </div>
*/
@Generated(value = "io.vrap.rmf.codegen.rendering.CoreCodeGenerator", comments = "https://github.com/commercetools/rmf-codegen")
@JsonDeserialize(as = TextLineItemImpl.class)
public interface TextLineItem {
/**
*
* @return addedAt
*/
@NotNull
@JsonProperty("addedAt")
public String getAddedAt();
/**
*
* @return custom
*/
@NotNull
@Valid
@JsonProperty("custom")
public CustomFields getCustom();
/**
*
* @return description
*/
@NotNull
@Valid
@JsonProperty("description")
public LocalizedString getDescription();
/**
*
* @return id
*/
@NotNull
@JsonProperty("id")
public String getId();
/**
*
* @return name
*/
@NotNull
@Valid
@JsonProperty("name")
public LocalizedString getName();
/**
*
* @return quantity
*/
@NotNull
@JsonProperty("quantity")
public Integer getQuantity();
/**
* set addedAt
* @param addedAt value to be set
*/
public void setAddedAt(final String addedAt);
/**
* set custom
* @param custom value to be set
*/
public void setCustom(final CustomFields custom);
/**
* set description
* @param description value to be set
*/
public void setDescription(final LocalizedString description);
/**
* set id
* @param id value to be set
*/
public void setId(final String id);
/**
* set name
* @param name value to be set
*/
public void setName(final LocalizedString name);
/**
* set quantity
* @param quantity value to be set
*/
public void setQuantity(final Integer quantity);
/**
* factory method
* @return instance of TextLineItem
*/
public static TextLineItem of() {
return new TextLineItemImpl();
}
/**
* factory method to create a shallow copy TextLineItem
* @param template instance to be copied
* @return copy instance
*/
public static TextLineItem of(final TextLineItem template) {
TextLineItemImpl instance = new TextLineItemImpl();
instance.setAddedAt(template.getAddedAt());
instance.setCustom(template.getCustom());
instance.setDescription(template.getDescription());
instance.setId(template.getId());
instance.setName(template.getName());
instance.setQuantity(template.getQuantity());
return instance;
}
/**
* factory method to create a deep copy of TextLineItem
* @param template instance to be copied
* @return copy instance
*/
@Nullable
public static TextLineItem deepCopy(@Nullable final TextLineItem template) {
if (template == null) {
return null;
}
TextLineItemImpl instance = new TextLineItemImpl();
instance.setAddedAt(template.getAddedAt());
instance.setCustom(com.commercetools.history.models.common.CustomFields.deepCopy(template.getCustom()));
instance.setDescription(
com.commercetools.history.models.common.LocalizedString.deepCopy(template.getDescription()));
instance.setId(template.getId());
instance.setName(com.commercetools.history.models.common.LocalizedString.deepCopy(template.getName()));
instance.setQuantity(template.getQuantity());
return instance;
}
/**
* builder factory method for TextLineItem
* @return builder
*/
public static TextLineItemBuilder builder() {
return TextLineItemBuilder.of();
}
/**
* create builder for TextLineItem instance
* @param template instance with prefilled values for the builder
* @return builder
*/
public static TextLineItemBuilder builder(final TextLineItem template) {
return TextLineItemBuilder.of(template);
}
/**
* accessor map function
* @param <T> mapped type
* @param helper function to map the object
* @return mapped value
*/
default <T> T withTextLineItem(Function<TextLineItem, T> helper) {
return helper.apply(this);
}
/**
* gives a TypeReference for usage with Jackson DataBind
* @return TypeReference
*/
public static com.fasterxml.jackson.core.type.TypeReference<TextLineItem> typeReference() {
return new com.fasterxml.jackson.core.type.TypeReference<TextLineItem>() {
@Override
public String toString() {
return "TypeReference<TextLineItem>";
}
};
}
}
| true |
8ea7c0a3a129cc4da8327014c8d4a608c382f7e5 | Java | SabaMicheal/classProject | /src/Casses/Flag.java | UTF-8 | 812 | 3.078125 | 3 | [] | no_license | package Casses;
public class Flag {
String country;
int size;
String color;
String materials;
public void info() {
System.out.println("Contry; " + country);
System.out.println("size; " + size);
System.out.println("color; " + color);
System.out.println("materials; " + materials);
}
public void flap() {
System.out.println("Flag is flapping");
}
// Create a method called upgrade.
// method should accept int for size and String for material.
// method upgrade should reassign the current
// size and material with given new values
public void upgrade(int size, String material){
this.size = size;
this.materials = material;
}
}
//Note;- if you know its an obeject or not
//if(f2.country == null) | true |
ef31b4abfaf956561ca1b955e4b3a44bfd03dbe9 | Java | cz67998/interview | /src/com/wangzhou/leecode/Solution257.java | UTF-8 | 1,327 | 3.0625 | 3 | [] | no_license | package com.wangzhou.leecode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IDEA
* author:wangzhou
* Date:2019/7/17
* Time:17:21
* Blog:https://blog.csdn.net/qq_38522268
**/
public class Solution257 {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
if(root==null)return paths;
path(root,"",paths);
return paths;
}
private void path(TreeNode root, String s, List<String> paths) {
if(root==null)return;
s+=root.val+"";
if(root.left==null&&root.right==null){
paths.add(s);
}else {
s+="->";
path(root.right,s,paths);
path(root.left,s,paths);
}
}
public List<String> binaryTreePaths1(TreeNode root) {
List<String> paths = new ArrayList<>();
if (root == null) return paths;
path1(root, "", paths);
return paths;
}
private void path1(TreeNode root, String res, List<String> paths) {
if (root == null) return;
res += root.val + "";
if (root.left == null && root.right == null) {
paths.add(res);
} else {
res += "->";
path1(root.left, res, paths);
path1(root.right, res, paths);
}
}
}
| true |
952862f576dd7993b942839b32f8d30bc8d2a1bc | Java | Aman83770/MediFinder | /Android app/app/src/main/java/com/example/akshatsharma/medifinder/DigCContactAdapter.java | UTF-8 | 2,964 | 2.375 | 2 | [] | no_license | package com.example.akshatsharma.medifinder;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Dell on 24-11-2015.
*/
public class DigCContactAdapter extends ArrayAdapter {
List list=new ArrayList();
public DigCContactAdapter(Context context, int resource) {
super(context, resource);
}
public void add(digC object) {
super.add(object);
list.add(object);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
ListViewHolder listViewHolder;
if(row==null){
LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.dig_row_layout,parent,false);
listViewHolder=new ListViewHolder();
listViewHolder.tx_name=(TextView)row.findViewById(R.id.tx_name);
listViewHolder.tx_street=(TextView)row.findViewById(R.id.tx_street);
listViewHolder.tx_locality=(TextView)row.findViewById(R.id.tx_locality);
listViewHolder.tx_region=(TextView)row.findViewById(R.id.tx_region);
listViewHolder.tx_postalcode=(TextView)row.findViewById(R.id.tx_postalcode);
listViewHolder.tx_timings=(TextView)row.findViewById(R.id.tx_timings);
listViewHolder.tx_telno=(TextView)row.findViewById(R.id.tx_telno);
listViewHolder.tx_emailid=(TextView)row.findViewById(R.id.tx_emailid);
listViewHolder.tx_website=(TextView)row.findViewById(R.id.tx_website);
row.setTag(listViewHolder);
}
else {
listViewHolder=(ListViewHolder)row.getTag();
}
digC ob=(digC)this.getItem(position);
listViewHolder.tx_name.setText(ob.getName());
listViewHolder.tx_street.setText(ob.getStreet());
listViewHolder.tx_locality.setText(ob.getLocality());
listViewHolder.tx_region.setText(ob.getRegion());
listViewHolder.tx_postalcode.setText(ob.getPostalcode());
listViewHolder.tx_timings.setText(ob.getTimings());
listViewHolder.tx_telno.setText(ob.getTelno());
listViewHolder.tx_emailid.setText(ob.getEmailid());
listViewHolder.tx_website.setText(ob.getWebsite());
return row;
}
static class ListViewHolder{
TextView tx_name,tx_street,tx_locality,tx_region,tx_postalcode,tx_timings,tx_telno,tx_emailid,tx_website;
}
}
| true |
fbca02992cff145eaadad0b51eb1c765829e7176 | Java | apache/directory-studio | /plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/jobs/LoadConfigurationRunnable.java | UTF-8 | 5,247 | 1.992188 | 2 | [
"Apache-2.0"
] | permissive | /*
* 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.directory.studio.openldap.config.jobs;
import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor;
import org.apache.directory.studio.common.core.jobs.StudioRunnableWithProgress;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.apache.directory.studio.openldap.config.editor.ConnectionServerConfigurationInput;
import org.apache.directory.studio.openldap.config.editor.DirectoryServerConfigurationInput;
import org.apache.directory.studio.openldap.config.editor.NewServerConfigurationInput;
import org.apache.directory.studio.openldap.config.editor.OpenLdapServerConfigurationEditor;
import org.apache.directory.studio.openldap.config.model.OlcGlobal;
import org.apache.directory.studio.openldap.config.model.OpenLdapConfiguration;
import org.apache.directory.studio.openldap.config.model.io.ConfigurationReader;
/**
* This class implements a {@link Job} that is used to load a server configuration.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LoadConfigurationRunnable implements StudioRunnableWithProgress
{
/** The associated editor */
private OpenLdapServerConfigurationEditor editor;
/**
* Creates a new instance of LoadConfigurationRunnable.
*
* @param editor the editor
*/
public LoadConfigurationRunnable( OpenLdapServerConfigurationEditor editor )
{
this.editor = editor;
}
/**
* {@inheritDoc}
*/
public String getErrorMessage()
{
return "Unable to load the configuration.";
}
/**
* {@inheritDoc}
*/
public Object[] getLockedObjects()
{
return new Object[0];
}
/**
* {@inheritDoc}
*/
public String getName()
{
return "Load Configuration";
}
/**
* {@inheritDoc}
*/
public void run( StudioProgressMonitor monitor )
{
IEditorInput input = editor.getEditorInput();
try
{
final OpenLdapConfiguration configuration = getConfiguration( input, monitor );
if ( configuration != null )
{
Display.getDefault().asyncExec( () -> editor.configurationLoaded( configuration ) );
}
}
catch ( Exception e )
{
// Reporting the error to the monitor
monitor.reportError( e );
// Reporting the error to the editor
final Exception exception = e;
Display.getDefault().asyncExec( () -> editor.configurationLoadFailed( exception ) );
}
}
/**
* Gets the configuration from the input. It may come from an existing connection,
* or from an existing file/directory on the disk, or a brand new configuration
*
* @param input the editor input
* @param monitor the studio progress monitor
* @return the configuration
* @throws Exception
*/
public OpenLdapConfiguration getConfiguration( IEditorInput input, StudioProgressMonitor monitor ) throws Exception
{
if ( input instanceof ConnectionServerConfigurationInput )
{
// If the input is a ConnectionServerConfigurationInput, then we
// read the server configuration from the selected connection
ConfigurationReader.readConfiguration( ( ConnectionServerConfigurationInput ) input );
}
else if ( input instanceof DirectoryServerConfigurationInput )
{
// If the input is a DirectoryServerConfigurationInput, then we
// read the server configuration from the selected 'slapd.d' directory.
return ConfigurationReader.readConfiguration( ( DirectoryServerConfigurationInput ) input );
}
else if ( input instanceof NewServerConfigurationInput )
{
// If the input is a NewServerConfigurationInput, then we only
// need to create a server configuration and return.
// The new configuration will be pretty empty, with just
// the main container (and the olcGlobal instance
OpenLdapConfiguration configuration = new OpenLdapConfiguration();
configuration.setGlobal( new OlcGlobal() );
return configuration;
}
return null;
}
}
| true |
e806b5df0348ae6ed1063c79c6ccaf13b17e1d20 | Java | lhqingit/qmall | /qmall-sso-web/src/main/java/net/imwork/lhqing/qmall/sso/controller/LoginController.java | UTF-8 | 1,969 | 2.1875 | 2 | [] | no_license | package net.imwork.lhqing.qmall.sso.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import net.imwork.lhqing.qmall.common.pojo.QmallResult;
import net.imwork.lhqing.qmall.common.utils.CookieUtils;
import net.imwork.lhqing.qmall.sso.service.LoginService;
/**
* 用户登录处理Controller
*
* @author lhq_i
*
*/
@Controller
public class LoginController {
@Autowired
private LoginService loginService;
@Value("${COOKIES_KEY}")
private String COOKIES_KEY;
/**
* 跳转到登录界面
*
* @return
*/
@RequestMapping("/page/login")
public String showLogin(String redirect, Model model) {
model.addAttribute("redirect",redirect);
return "login";
}
/**
* 用户登录
*
* @param username
* @param password
* @param request
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public QmallResult login(HttpServletRequest request, HttpServletResponse response,
String username, String password) {
String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
QmallResult qmallResult = loginService.userLogin(username, md5Password);
// 判断是否登录成功
if (qmallResult.getStatus() == 200) {
String token = qmallResult.getData().toString();
//如果登录成功需要把token写入cookie
CookieUtils.setCookie(request, response, COOKIES_KEY, token);
}
return qmallResult;
}
}
| true |
3f5e539f70518c07953c94d539bca9bd94c95161 | Java | andrea5972/ObjectOrientedSoftwareDev | /WorkObserver/src/work_observer/WorkManagerImplementation.java | UTF-8 | 1,210 | 3.09375 | 3 | [] | no_license | package work_observer;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
public class WorkManagerImplementation implements WorkManager {
private List<Observer> observers;
private WorkItem WorkItem;
public WorkManagerImplementation() {
observers = new ArrayList<>();
}
@Override
public void addObserver(Observer o) {
this.observers.add(o);
}
@Override
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
@Override
public void notifyObservers() {
WorkItem tempWorkItem = WorkItem;
for (int i = 0; i < observers.size(); i++) {
Worker worker = (Worker) observers.get(i);
tempWorkItem = worker.update(WorkItem);
if (tempWorkItem != null) {
this.WorkItem = tempWorkItem;
System.out.println(worker.getWorkerID() + ": Completed work on WorkItem<" + WorkItem.getItemID() + ">");
}
if (WorkItem.getItemID() > 4) {
break;
}
}
}
public void setWorkItem(WorkItem workItem) {
this.WorkItem = workItem;
}
}
| true |
b8ebacd4b82b387c30173d45fac181d2c634cfb0 | Java | Michael-Kolbasov/springseptember | /src/main/java/com/epam/spring/model/Cat.java | UTF-8 | 854 | 2.875 | 3 | [] | no_license | package com.epam.spring.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "cats")
public class Cat implements Animal {
@EqualsAndHashCode.Exclude
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private int age;
public Cat(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void doAnimalStuff() {
System.out.println("meow");
}
}
| true |
8c8baf5ec24c5461de38b147ec634dc2c3bfbd4b | Java | Deagle50/DAM2 | /ProgramacionMultimedia/SOLUCIONES/VersionesAndroidRecycler/app/src/main/java/com/example/versionesandroidrecycler/MainActivity.java | UTF-8 | 1,637 | 2.34375 | 2 | [] | no_license | package com.example.versionesandroidrecycler;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.res.TypedArray;
import android.os.Bundle;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<AndroidVersion> Objetos=new ArrayList<AndroidVersion>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llenarColeccion(Objetos);
RecyclerVersionAdapter rva=new RecyclerVersionAdapter(this,R.layout.recyclerviewline,Objetos);
RecyclerView rv=findViewById(R.id.recycler);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setAdapter(rva);
}
void llenarColeccion(ArrayList <AndroidVersion> col)
{
String[] nombres;
String[] versiones;
int[] periodos;
int[] api;
TypedArray id;
nombres=getResources().getStringArray(R.array.nombres);
versiones=getResources().getStringArray(R.array.versiones);
periodos=getResources().getIntArray(R.array.periodos);
api=getResources().getIntArray(R.array.apis);
id=getResources().obtainTypedArray(R.array.drawableIds);
for (int i=0;i<periodos.length;i++)
{
AndroidVersion v=new AndroidVersion(nombres[i],versiones[i],api[i],periodos[i],id.getResourceId(i,-1));
col.add(v);
}
}
}
| true |
e1e742a0480dbe7e04b802adf8f1d2282043c9ba | Java | techmagic-team/techmagic-hr-android | /app/src/main/java/co/techmagic/hr/presentation/DefaultSubscriber.java | UTF-8 | 1,452 | 2.359375 | 2 | [] | no_license | package co.techmagic.hr.presentation;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import co.techmagic.hr.data.exception.NetworkConnectionException;
import co.techmagic.hr.presentation.mvp.view.View;
import retrofit2.HttpException;
import rx.Subscriber;
public class DefaultSubscriber<T> extends Subscriber<T> {
private View view;
/* Used to handle progress manually */
public DefaultSubscriber() {
}
public DefaultSubscriber(View view) {
this.view = view;
}
@Override
public void onCompleted() {
if (view != null) {
view.hideProgress();
}
}
@Override
public void onError(Throwable e) {
if (view == null) {
return;
}
if (e instanceof SocketTimeoutException || e instanceof NetworkConnectionException) {
view.showConnectionErrorMessage();
} else if (e instanceof HttpException) {
handleHttpErrorCodes(((HttpException) e).code());
}
}
@Override
public void onNext(T requestedTimeOffDto) {
}
private void handleHttpErrorCodes(int errorCode) {
switch (errorCode) {
case HttpURLConnection.HTTP_BAD_REQUEST:
view.showSnackBarWrongLoginCredentialsError();
break;
case HttpURLConnection.HTTP_FORBIDDEN:
view.logOut();
break;
}
}
}
| true |
cffd5d1b2f7c439016916b093dbf91618228cd3a | Java | xyn3106/Ebook | /src/com/xyn/ebook/game2.java | GB18030 | 8,437 | 3.015625 | 3 | [] | no_license | package com.xyn.ebook;
public class game2 {
public static int count=20;
public static String[][] list = { {"ѡ¼ӵûдֵһ",
"Aİװ͵ˣ˭֪һֻƳٿ",
"B¿Ƴڳһָһλˣֻܸʰ·硣",
"CζΣζϣζδôһ۾Աأ",
"B"}, {"ѡ¼ӵûдֵһ",
"AԭġԾⳡʣʧȥһľ",
"BбȷɵԾû̹ǵľģ̸ʲôʵǿѧշ壿",
"CСɽڵӣļ米¶ĵĴ",
"C"}, {"ѡ¼ӵûдֵһ",
"AһǵǷǽ˷ܵرשͷⲻ֪һ¸ǽѹ",
"BŲһŵǧлĴͳ¡ѽһ֡",
"CΪҽݵֶߵϢȴһӰ˵",
"C"}, {"ѡ¼ӵûдֵһ",
"Aëͬ־Ӣߣʦ˹ͼԳΪĻΡ",
"Bǰһôǰһͷ·ÿ춼Զ",
"CˮͷĻɰĺС׳һ֧",
"A"}, {"ѡ¼ӵûдֵһ",
"AСˡ֮Ƶǵ5 21շۣԼߵ̸Ц",
"Bй飬ϵѳΪһִͳ¹ʽѧ֮˵",
"CõԺƤ˾г֣Ȼڴ¥ǰƸ档",
"A"}, {"ѡ¼ӵûдֵһ",
"AһϣƶʱѰѷ˾⡣",
"Bƹ棬ͷܶϳеģʵƷַǷ",
"CԴӸٽʦ۱һèҲ켣Уij",
"C"}, {"ѡ¼ӵûдֵһ",
"Aʱƣһҡֵľʿһʱ",
"BдȷԺչг飬ڳְնԺʽ۽Ρ",
"CҪѧӷָǰ״̬һҪ6--8ܡ",
"C"}, {"Ķľ䲢ѡȷʹáֿȡһ",
"A. ֿץסӳѧֿȡ",
"B. תȣһЩصĹҲֿȣĿǰտ˹ԱԴгϹӦ˵λĹʡᡱ",
"C. ڹϵ©ҵʲλɣΪҵֿȵһɡ",
"D.ÿDzõȵִӵֿȵļ",
"C"}, {"ȷó족ֳ족»գΪһ˵õȮ죬ܼһְ__________________",
"Aֳ",
"B",
"B"}, {"Ķľ䲢ѡʹóǹ۶÷һ",
"A߶˵һжһʱжˣΪ֮Դϲְĸֻ֮˽ʱſɸǹ۶",
"Bڻûǹ۶ʱȱæ½ۡ",
"CȻϡϷܶǹ۶Ӧÿ϶ңѧߡ",
"DDzŵİ·Ƿ𡢵ϵġÿһοᣬᵱǹ۶۳",
"D"}, {"Ķľ䲢ȷʹáһ𡱻һ롱գˮ߲˺_______Ż30Ԫ",
"Aһ",
"Bһ",
"A"}, {"Ķľ䲢жϼӵ÷ľϵ׳϶ּᣬдһգֱȥǰһ»ȥһƪʷ",
"A",
"B",
"A"}, {"Ķľ䲢ѡȷʹüӵһ",
"Aڵ쵼£ҵҰľһȥ",
"BʱδȾָھӶȴڴʦõһ˼顣",
"CѾɺ½սװͬʱҲҪһ",
"Dϵĺö£ǶҲˡƩ磬ҵ£նģƸˣ˷",
"A"}, {"ѡ»Сơ͡Ρȷ÷____________ᡢ____________Ṳʶ",
"A/",
"B/",
"C/",
"D/",
"B"}, {"Ķľ䲢ѡûﲡһ",
"AˮԽԽԭΪȱٻʶʹȻ̬ƽƻɵĶ",
"Bأд£౨־ǻתء",
"CԮԱðΣգڴԼ200ҵȴ˽СʱŽԱתƳ",
"DΪֹdzͳһ£ذ˻Լ20شΣ˻֮",
"DABCѡʽۣAѡӦȥԭΪBѡ־ĿѾ־˼ӦֱӱΪCѡԼ͡ҡֻһ"}, {"»ѡֹ͡ơȷ÷ҪϸʵԺԼ¡____________Υ¥ùĻĸĸ糤ӵУ____________ʹܹǾͳΪˮݲɺҲظܵġ",
"A/ֹ",
"B/",
"Cֹ/",
"Dֹ/ֹ",
"A"}, {"Ķľ䲢ѡȷʹóһ",
"AЩԽӵƭԽӵĻԽƭ˳ɹԽƵΪԽľٶԽгǼֵƣ͵֡",
"BΪ˼û磬ֻԼ˵Ӳ",
"CӼйΪҶ︣Ĺ涨Ըƶ滷ԲҵĶ︣ƶơ",
"B"}, {"2004ŵ˻ᣬҶŮ˫̨10ƣ17ꡣ˶ĵ۷壬еĻԻҲȻֹ",
"A",
"B",
"B"}, {"뽨йأ",
"Aͥ",
"Bڻ",
"C",
"D֮",
"A"}, {"ѡ¼ӵûдֵһ",
"AԶԶȥһϲдǣŵڴڣ˼ࡣ",
"Bӭһ¥ʱ촩췭ظı仯",
"CȫһdzɣԼ⺧䲻֣ȴСƷеϼ֮",
"A"} };
}
| true |
ffe2dfa6840a7b1ba55e0679bc36c45c6bb32107 | Java | shixuerenxin/Jd_zpc | /app/src/main/java/com/jd_zpc/model/GoodsModel.java | UTF-8 | 1,008 | 2.0625 | 2 | [] | no_license | package com.jd_zpc.model;
import com.jd_zpc.bean.GoodsBean;
import com.jd_zpc.utils.Api;
import com.jd_zpc.utils.ApiService;
import com.jd_zpc.utils.OnNetListener;
import com.jd_zpc.utils.RetrofitUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by DELL on 2017/11/8.
*/
public class GoodsModel {
public void getGoods(int pscid, final OnNetListener onNetListener){
ApiService apiService = RetrofitUtil.getInstance().getApiService(Api.devIP, ApiService.class);
Call<GoodsBean> goodsList = apiService.getGoodsList(pscid);
goodsList.enqueue(new Callback<GoodsBean>() {
@Override
public void onResponse(Call<GoodsBean> call, Response<GoodsBean> response) {
GoodsBean goodsBean = response.body();
onNetListener.onSuccess(goodsBean);
}
@Override
public void onFailure(Call<GoodsBean> call, Throwable t) {
}
});
}
}
| true |
c81ab6e22d194ab2f6b31d6d658ff4139c3b2bb7 | Java | GoogleCloudPlatform/fda-mystudies | /response-datastore/response-server-service/src/main/java/com/google/cloud/healthcare/fdamystudies/task/ExportFHIRDataToBQScheduledTask.java | UTF-8 | 10,745 | 1.78125 | 2 | [
"MIT"
] | permissive | package com.google.cloud.healthcare.fdamystudies.task;
import static com.google.cloud.healthcare.fdamystudies.common.CommonConstants.CONSENT_TABLE_NAME;
import com.google.api.services.healthcare.v1.model.Consent;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.DatasetInfo;
import com.google.cloud.healthcare.fdamystudies.config.ApplicationConfiguration;
import com.google.cloud.healthcare.fdamystudies.mapper.BigQueryApis;
import com.google.cloud.healthcare.fdamystudies.mapper.ConsentManagementAPIs;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ExportFHIRDataToBQScheduledTask {
private XLogger logger =
XLoggerFactory.getXLogger(ExportFHIRDataToBQScheduledTask.class.getName());
@Autowired private BigQueryApis bigQueryApis;
@Autowired private ApplicationConfiguration appConfig;
@Autowired ConsentManagementAPIs consentManagementAPIs;
// 30min fixed delay and 1min initial delay
@Scheduled(
fixedDelayString = "${ingest.bigQuery.fixed.delay.ms}",
initialDelayString = "${ingest.bigQuery.initial.delay.ms}")
public void exportFHIRDataToBQTask() throws Exception {
logger.entry("begin exportFHIRConsentDataToBQTask()");
String WriteDisposition = "WRITE_TRUNCATE";
logger.debug(
"begin exportFHIRConsentDataToBQTask() IngestDataToBigQuery : "
+ appConfig.getIngestDataToBigQuery()
+ " : ");
if (appConfig.getIngestDataToBigQuery().equalsIgnoreCase("true")) {
logger.debug("Export FHIR data from Google Healthcare API to BigQuery - begin");
try {
if (appConfig.getEnableFhirApi().contains("fhir")) {
logger.debug(" getEnableFhirManagementApi fhir");
List<com.google.api.services.healthcare.v1.model.Dataset> datasets =
consentManagementAPIs.datasetList(appConfig.getProjectId(), appConfig.getRegionId());
if (null != datasets && !datasets.isEmpty()) {
for (com.google.api.services.healthcare.v1.model.Dataset data : datasets) {
String FHIRStudyId = data.getName();
FHIRStudyId = FHIRStudyId.substring(FHIRStudyId.indexOf("/datasets/") + 10);
logger.info("exportFHIRConsentDataToBQTask() FHIR study ID: " + FHIRStudyId);
createDataSetInBigQuery(FHIRStudyId + "_FHIR");
String fhirStoreLocation =
String.format(
"projects/%s/locations/%s/datasets/%s/fhirStores/%s",
appConfig.getProjectId(),
appConfig.getRegionId(),
FHIRStudyId,
"FHIR_" + FHIRStudyId);
bigQueryApis.exportFhirStoreDataToBigQuery(
fhirStoreLocation, appConfig.getProjectId(), FHIRStudyId + "_FHIR");
logger.debug(" exportFhirStoreDataToBigQuery complete");
}
}
}
} catch (Exception e) {
logger.error("exportFHIRConsentDataToBQTask() FHIR Error ", e);
}
logger.debug("Export DID data from Google Healthcare API to BigQuery - Begin ");
try {
if (appConfig.getEnableFhirApi().contains("did")) {
logger.debug(" getEnableFhirManagementApi did");
List<com.google.api.services.healthcare.v1.model.Dataset> datasets =
consentManagementAPIs.datasetList(appConfig.getProjectId(), appConfig.getRegionId());
if (null != datasets && !datasets.isEmpty()) {
for (com.google.api.services.healthcare.v1.model.Dataset data : datasets) {
String DIDStudyId = data.getName();
DIDStudyId = DIDStudyId.substring(DIDStudyId.indexOf("/datasets/") + 10);
logger.info("exportFHIRConsentDataToBQTask() DID study ID: " + DIDStudyId);
createDataSetInBigQuery(DIDStudyId);
String didStoreLocation =
String.format(
"projects/%s/locations/%s/datasets/%s/fhirStores/%s",
appConfig.getProjectId(),
appConfig.getRegionId(),
DIDStudyId,
"DID_" + DIDStudyId);
bigQueryApis.exportFhirStoreDataToBigQuery(
didStoreLocation, appConfig.getProjectId(), DIDStudyId);
logger.debug(" exportFhirStoreDataToBigQuery did");
}
}
}
} catch (Exception e) {
logger.error("exportFHIRConsentDataToBQTask() DID Error ", e);
}
}
logger.debug("Export consent data from Google Healthcare API to BigQuery - Begin ");
try {
if (appConfig.getEnableConsentManagementAPI().equalsIgnoreCase("true")) {
List<com.google.api.services.healthcare.v1.model.Dataset> datasets =
consentManagementAPIs.datasetList(appConfig.getProjectId(), appConfig.getRegionId());
if (null != datasets && !datasets.isEmpty()) {
for (com.google.api.services.healthcare.v1.model.Dataset data : datasets) {
String ConsentStudyId = data.getName();
ConsentStudyId = ConsentStudyId.substring(ConsentStudyId.indexOf("/datasets/") + 10);
logger.debug("exportFHIRConsentDataToBQTask() Consent study ID: " + ConsentStudyId);
// createDataSetInBigQuery(ConsentStudyId);
// Ingest consent data
List<Object> consentDataBQ = new ArrayList<Object>();
String consentDatasetName =
String.format(
"projects/%s/locations/%s/datasets/%s/consentStores/%s",
appConfig.getProjectId(),
appConfig.getRegionId(),
ConsentStudyId,
"CONSENT_" + ConsentStudyId);
List<Consent> consentDataList =
consentManagementAPIs.getListOfConsents("", consentDatasetName);
if (null != consentDataList && !consentDataList.isEmpty()) {
for (Consent consentList : consentDataList) {
JSONObject jsonObj = new JSONObject();
jsonObj.put(
"ParticipantId",
StringUtils.isNotEmpty(consentList.getUserId()) ? consentList.getUserId() : "");
jsonObj.put(
"ConsentState",
StringUtils.isNotEmpty(consentList.getState()) ? consentList.getState() : "");
jsonObj.put(
"ConsentType",
StringUtils.isNotEmpty(consentList.getMetadata().get("ConsentType"))
? consentList.getMetadata().get("ConsentType")
: "");
jsonObj.put(
"DataSharingPermission",
StringUtils.isNotEmpty(consentList.getMetadata().get("DataSharingPermission"))
? consentList.getMetadata().get("DataSharingPermission")
: "");
consentDataBQ.add(jsonObj);
}
}
if (appConfig.getEnableFhirApi().contains("fhir")
&& !appConfig.getDiscardFhirAfterDid().equalsIgnoreCase("true")) {
if (null != consentDataBQ && !consentDataBQ.isEmpty()) {
bigQueryApis.ingestDataToBigQueryTable(
appConfig.getProjectId(),
appConfig.getRegionId(),
ConsentStudyId + "_FHIR",
CONSENT_TABLE_NAME,
consentDataBQ,
WriteDisposition);
logger.debug("ingestDataToBigQueryTable() complete FHIR ");
}
}
if (appConfig.getEnableFhirApi().contains("did")) {
if (null != consentDataBQ && !consentDataBQ.isEmpty()) {
bigQueryApis.ingestDataToBigQueryTable(
appConfig.getProjectId(),
appConfig.getRegionId(),
ConsentStudyId,
CONSENT_TABLE_NAME,
consentDataBQ,
WriteDisposition);
logger.debug("ingestDataToBigQueryTable() complete DID ");
}
}
if (appConfig.getEnableFhirApi().contains("fhir")) {
bigQueryApis.createViewsInBigQuery(
appConfig.getProjectId(), ConsentStudyId + "_FHIR");
logger.debug(" createViewsInBigQuery complete");
}
if (appConfig.getEnableFhirApi().contains("did")) {
bigQueryApis.createViewsInBigQuery(appConfig.getProjectId(), ConsentStudyId);
logger.debug(" createViewsInBigQuery did");
}
}
}
}
} catch (Exception e) {
logger.error("exportFHIRConsentDataToBQTask() Consent Error ", e);
}
logger.exit("exportFHIRConsentDataToBQTask() completed");
}
public void createDataSetInBigQuery(String dataSetName) {
logger.entry("ExportFHIRDataToBQScheduledTask.createDataSetInBigQuery() entry");
try {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests.
BigQuery bigquery =
BigQueryOptions.newBuilder()
.setProjectId(appConfig.getProjectId())
.setLocation(appConfig.getRegionId())
.build()
.getService();
// BigQuery bigquery = gigQueryOptions.getDefaultInstance().getService();
Dataset dataset = bigquery.getDataset(DatasetId.of(dataSetName));
logger.info("FHIR dataSetName: " + dataSetName);
if (dataset == null) {
DatasetInfo datasetInfo =
DatasetInfo.newBuilder(dataSetName).setLocation(appConfig.getRegionId()).build();
Dataset newDataset = bigquery.create(datasetInfo);
String newDatasetName = newDataset.getDatasetId().getDataset();
logger.info("New Dataset created in BigQuery: " + newDatasetName);
}
} catch (BigQueryException e) {
logger.error("ExportFHIRDataToBQScheduledTask.createDataSetInBigQuery() error ", e);
}
logger.exit("ExportFHIRDataToBQScheduledTask.createDataSetInBigQuery() completed");
}
}
| true |
e240db8f9c8b49679cd5a650178858e2449cd4f8 | Java | dbrowncode/StS-ConstructMod | /src/main/java/constructmod/actions/ImplosionExhaustPileAction.java | UTF-8 | 4,609 | 2.421875 | 2 | [
"MIT"
] | permissive | package constructmod.actions;
import basemod.BaseMod;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.CardGroup;
import com.megacrit.cardcrawl.cards.CardQueueItem;
import com.megacrit.cardcrawl.cards.status.Burn;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
public class ImplosionExhaustPileAction extends AbstractGameAction
{
private AbstractPlayer p;
private boolean mega;
public ImplosionExhaustPileAction() {
this.duration = Settings.ACTION_DUR_FAST;
this.actionType = ActionType.CARD_MANIPULATION;
this.source = AbstractDungeon.player;
this.p = AbstractDungeon.player;
}
@Override
public void update() {
if (this.duration == Settings.ACTION_DUR_FAST) {
// Search through draw & discard piles, find all playable cards that aren't burns
boolean isValid = true;
final CardGroup validDrawpileCards = new CardGroup(CardGroup.CardGroupType.UNSPECIFIED);
for (final AbstractCard c : p.drawPile.group) {
for (final AbstractMonster m : AbstractDungeon.getMonsters().monsters) {
if (c.canUse(p, m) && c.cardID != Burn.ID) {
for (final CardQueueItem q : AbstractDungeon.actionManager.cardQueue) {
if (q.card.equals(c)) isValid = false;
}
if (isValid) validDrawpileCards.addToTop(c);
break; // break once we know it works with at least one monster
}
}
}
int handCount = AbstractDungeon.player.hand.size();
int burnCount = 0;
// Draw burns from piles, with the condition that we don't draw them if there isn't a matching playable card.
for (AbstractCard c : p.exhaustPile.group){
if (c.cardID == Burn.ID && handCount < BaseMod.MAX_HAND_SIZE && burnCount < validDrawpileCards.size()){
handCount++;
burnCount++;
AbstractDungeon.actionManager.addToBottom(new FetchCardToHandAction(c,p.discardPile));
}
}
// At this point, we've drawn all Burns into hand that will play a card when moved. HOWEVER, the card text
// says to put ALL burns into hand, and the play effect is secondary. So if handsize < BaseMod.MAX_HAND_SIZE, we do a second
// pass and just fill the player's hand with all the burns we can find. Mwahahaha.
// Note: we haven't ACTUALLY drawn any cards yet, just set up the actions to do so. That's why we're using
// this manual variable handCount instead of checking the actual hand size.
for (AbstractCard c : p.exhaustPile.group){
if (c.cardID == Burn.ID && handCount < BaseMod.MAX_HAND_SIZE){
handCount++;
AbstractDungeon.actionManager.addToBottom(new FetchCardToHandAction(c,p.exhaustPile));
}
}
// burnCount is now an accurate reflection of the number of cards we will PLAY from
// each pile, not necessarily the number of burns drawn.
playCards(burnCount, validDrawpileCards);
this.isDone = true;
}
}
public void playCards(int count, CardGroup validCards){
// This really shouldn't happen...
if (count > validCards.size()) count = validCards.size();
for (int i = 0; i < count; ++i) {
final AbstractCard card = validCards.getRandomCard(true);
validCards.removeCard(card);
AbstractDungeon.player.drawPile.removeCard(card);
card.freeToPlayOnce = true;
card.current_y = -200.0f * Settings.scale;
card.target_x = Settings.WIDTH / 2.0f + i * 200;
card.target_y = Settings.HEIGHT / 2.0f;
card.targetAngle = 0.0f;
card.lighten(false);
card.drawScale = 0.12f;
card.targetDrawScale = 0.75f;
AbstractMonster m = AbstractDungeon.getRandomMonster();
if (card.canUse(AbstractDungeon.player, m)){
card.applyPowers();
AbstractDungeon.actionManager.addToBottom(new QueueCardFrontAction(card, m));
}
}
}
}
| true |
b8dd5738832e88d2cc6d0a628704c6dc156b4510 | Java | dlobba/ds1_project | /src/main/java/reliable_multicast/BaseParticipant.java | UTF-8 | 13,063 | 2.359375 | 2 | [] | no_license | package reliable_multicast;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import reliable_multicast.messages.FlushMsg;
import reliable_multicast.messages.Message;
import reliable_multicast.messages.StopMulticastMsg;
import reliable_multicast.messages.ViewChangeMsg;
import reliable_multicast.utils.Config;
import scala.concurrent.duration.Duration;
public abstract class BaseParticipant extends AbstractActor {
// --- Messages for internal behavior ---
public static class SendMulticastMsg implements Serializable {};
// --------------------------------------
public static final int MAX_DELAY_TIME = 4;
public static final int MULTICAST_INTERLEAVING =
MAX_DELAY_TIME / 2;
public static final int MAX_TIMEOUT =
MAX_DELAY_TIME * 2 + 1;
protected int id;
protected int multicastId;
// the set of actors that are seen by this node
protected View view;
// temporary view established in the all-to-all
// phase. The temporary view is equal to the current view
// only when the view is effectively installed.
protected View tempView;
protected boolean canSend;
protected Set<FlushMsg> flushesReceived;
protected Set<Message> messagesBuffer;
// store the status of all participants
// from the point of view of this actor
protected final Map<Integer, Integer> processesDelivered;
protected boolean manualMode;
protected void resetParticipant() {
this.id = -1;
this.multicastId = 0;
this.canSend = false;
this.view = new View(-1);
this.tempView = new View(-1);
this.messagesBuffer = new HashSet<>();
this.flushesReceived = new HashSet<>();
}
// ------- CONSTRUCTORS ---------------------
public BaseParticipant(boolean manualMode) {
super();
this.resetParticipant();
this.manualMode = manualMode;
this.processesDelivered = new HashMap<>();
}
public BaseParticipant(Config config) {
this(config.isManual_mode());
}
public BaseParticipant() {
this(false);
}
// ------------------------------------------
private void updateProcessesDelivered(Integer processId,
Integer messageID) {
if (processId == -1)
return;
this.processesDelivered.put(processId, messageID);
}
protected void removeOldFlushes(int currentView) {
Iterator<FlushMsg> msgIterator =
this.flushesReceived.iterator();
FlushMsg flushMsg;
while (msgIterator.hasNext()) {
flushMsg = msgIterator.next();
if (flushMsg.viewID < currentView)
msgIterator.remove();
}
}
protected void scheduleMessage(Object message, int after, ActorRef receiver) {
if (message == null)
return;
this.getContext()
.getSystem()
.scheduler()
.scheduleOnce(Duration.create(after,
TimeUnit.SECONDS),
receiver,
message,
getContext().system().dispatcher(),
this.getSelf());
}
protected void sendInternalMessage(Object message, int time) {
scheduleMessage(message, time, this.getSelf());
}
/**
* An abstraction used for internal messages
* used to schedule lookup procedures, like
* alive checking.
* @param message
*/
protected void sendTimeoutMessage(Object message) {
sendInternalMessage(message,
MAX_TIMEOUT);
}
protected void sendTimeoutMessageAfter(Object message, int after) {
sendInternalMessage(message,
after + MAX_TIMEOUT);
}
/**
* Send a message after a fixed amount of time.
*
* @param message
* @param after
* @param receiver
*/
protected void sendMessageAfter(Object message, int after, ActorRef receiver) {
scheduleMessage(message, after, receiver);
}
/**
* Send a multicast simulating delays.
* Each message is sent with 1 second interleaving
* between each other.
*
* @param message
* @param baseTime time after messages start to be sent
* @return the estimated time after all messages will be
* sent.
*/
protected int delayedMulticast(Object message,
Set<ActorRef> receivers,
int baseTime) {
int time = 0;
for (ActorRef receiver : receivers) {
sendMessageAfter(message, baseTime + time, receiver);
time += 1;
}
return time;
}
protected int delayedMulticast(Object message,
Set<ActorRef> receivers) {
return this.delayedMulticast(message, receivers, 0);
}
/**
* Return the set of actors associated to the
* flush messages received.
*
* @param currentView
* @return
*/
protected Set<ActorRef> getFlushSenders(int currentView) {
Set<ActorRef> senders = new HashSet<>();
Iterator<FlushMsg> flushMsgIterator =
this.flushesReceived.iterator();
FlushMsg flushMsg;
while (flushMsgIterator.hasNext()) {
flushMsg = flushMsgIterator.next();
if (flushMsg.viewID == currentView)
senders.add(flushMsg.sender);
}
return senders;
}
protected Message getMessage(Message other) {
Iterator<Message> msgIter = this.messagesBuffer.iterator();
Message tmp;
while (msgIter.hasNext()) {
tmp = msgIter.next();
if (tmp.equals(other))
return tmp;
}
return null;
}
protected void onStopMulticast(StopMulticastMsg stopMsg) {
this.canSend = false;
System.out
.printf("%d P-%d P-%d INFO stopped_multicasting\n",
System.currentTimeMillis(),
this.id,
this.id);
}
protected void onViewChangeMsg(ViewChangeMsg viewChange) {
// do not install an old view
if (viewChange.id < this.tempView.id)
return;
System.out.printf("%d P-%d P-%d INFO started_view_change V%d\n",
System.currentTimeMillis(),
this.id,
this.id,
viewChange.id);
this.tempView = new View(viewChange.id,
viewChange.members,
viewChange.membersIds);
this.removeOldFlushes(this.tempView.id);
int waitTime = 0;
for (Message message : messagesBuffer) {
// mark the message as stable
message = new Message(message, true);
waitTime = this.delayedMulticast(message, this.tempView.members);
}
// FLUSH messages: send them after having sent
// all ViewChange messages. This is guaranteed
// by sending after waitTime (+1 to be sure)
this.delayedMulticast(new FlushMsg(this.id,
this.tempView.id,
this.getSelf()),
this.tempView.members,
waitTime + 1);
}
protected void onFlushMsg(FlushMsg flushMsg) {
/*
* if the flush is for a previous view-change then just ignore
* it.
*/
if (flushMsg.viewID < this.tempView.id)
return;
this.flushesReceived.add(flushMsg);
System.out.printf("%d P-%d P-%d received_flush V%d\n",
System.currentTimeMillis(),
this.id,
flushMsg.senderID,
flushMsg.viewID);
// if this is true then every operational
// node has received all the unstable messages
if (this.tempView.id == flushMsg.viewID &&
this.getFlushSenders(this.tempView.id)
.containsAll(this.tempView.members)) {
this.view = new View(tempView);
System.out.printf("%d install view %d %s\n",
this.id,
this.view.id,
this.view.logMembers());
System.out.printf("%d P-%d P-%d installed_view %s\n",
System.currentTimeMillis(),
this.id,
this.id,
this.view.toString());
System.out.printf("%d P-%d P-%d INFO can_send\n",
System.currentTimeMillis(),
this.id,
this.id);
// deliver all mesages up to current view
Iterator<Message> msgIter = messagesBuffer.iterator();
Message message;
while (msgIter.hasNext()) {
message = msgIter.next();
if (message.viewId <= this.view.id) {
deliverMessage(message);
msgIter.remove();
}
}
// resume multicasting
this.canSend = true;
this.scheduleMulticast();
}
}
protected void onSendMulticastMsg(SendMulticastMsg message) {
this.scheduleMulticast();
this.multicast();
}
/**
* Schedule a new multicast.
*/
protected void scheduleMulticast() {
/*
* if in manual mode, multicasts are not sent automatically,
* so block the scheduling.
*/
if (this.manualMode)
return;
sendInternalMessage(new SendMulticastMsg(),
MULTICAST_INTERLEAVING);
}
private void multicast() {
if (!this.canSend)
return;
// this node cannot send message
// until this one is completed
this.canSend = false;
Message message = new Message(
this.id,
this.multicastId,
this.view.id,
false);
System.out.printf("%d send multicast %d within %d\n",
this.id,
this.multicastId,
this.view.id);
System.out.printf("%d P-%d P-%d multicast_message %s\n",
System.currentTimeMillis(),
this.id,
this.id,
message.toString());
this.multicastId += 1;
int waitTime;
waitTime = this.delayedMulticast(message, this.view.members);
// STABLE messages
message = new Message(message, true);
this.delayedMulticast(message, this.view.members, waitTime);
this.canSend = true;
}
protected void onReceiveMessage(Message message) {
/*
* if the sender is not in the view, then do not accept the
* message
*/
if (!this.tempView.members.contains(this.getSender()))
return;
// a message is crossing the view boundary.
// ignore it
if (message.viewId > this.view.id) {
return;
}
if (message.viewId < this.view.id)
return;
/* Check if the id of the new message is greater
* than the last delivered message coming from
* the sender process. If this is the case
* then deliver the message.
*/
deliverMessage(message);
if (message.stable)
this.messagesBuffer.remove(message);
else
this.messagesBuffer.add(message);
}
/**
* Deliver the message given if there is not
* a more recent message delivered from the
* sender process with regards to the point of
* view of the current process (as in vector clocks).
* @param message
*/
protected void deliverMessage(Message message) {
if (this.processesDelivered
.get(message.senderID) == null ||
this.processesDelivered
.get(message.senderID) < message.messageID) {
System.out.printf("%d deliver multicast %d from %d within %d\n",
this.id,
message.messageID,
message.senderID,
message.viewId);
System.out.printf("%d P-%d P-%d delivered_message %s\n",
System.currentTimeMillis(),
this.id,
message.senderID,
message.toString());
// update the mapping
this.updateProcessesDelivered(message.senderID,
message.messageID);
}
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(StopMulticastMsg.class, this::onStopMulticast)
.match(ViewChangeMsg.class, this::onViewChangeMsg)
.match(FlushMsg.class, this::onFlushMsg)
.match(Message.class, this::onReceiveMessage)
.match(SendMulticastMsg.class, this::onSendMulticastMsg)
.build();
}
}
| true |
a2399cb64ef0983f1b273775a267bedc0a2fa4b4 | Java | chenps3/dynamic-proxy | /sample/src/test/java/chenps3/dynamicproxy/sample/ch04/immutablecollection/HandcodedFilterDemo.java | UTF-8 | 703 | 3.53125 | 4 | [] | no_license | package chenps3.dynamicproxy.sample.ch04.immutablecollection;
import java.util.Arrays;
/**
* @Author chenguanhong
* @Date 2021/8/24
*/
public class HandcodedFilterDemo {
public static void main(String[] args) {
ImmutableCollection<String> names = new HandcodedFilter<>(Arrays.asList("Peter", "Paul", "Mary"));
System.out.println(names);
System.out.println("Is Mary in? " + names.contains("Mary"));
System.out.println("Are there names? " + !names.isEmpty());
System.out.println("Printing the names:");
names.forEach(System.out::println);
System.out.println("Class: " + names.getClass().getSimpleName());
names.printAll();
}
}
| true |
ec2cd7ae0649274bccf2d164105a6792488dbd09 | Java | musiciancoder/Courses | /src/main/java/com/example/courses/controller/CoursesController.java | UTF-8 | 3,430 | 2.4375 | 2 | [] | no_license | package com.example.courses.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.courses.entity.Course;
import com.example.courses.entity.Student;
import com.example.courses.service.ICoursesService;
@RestController
@RequestMapping("/rest") // do not forget to add "rest" to each URL as part of all endpoints. Example: to execute method searchAllCoursesC() one must write down: http://localhost:8080/rest/courses/all
public class CoursesController {
@Autowired
private ICoursesService serviceCourses;
@GetMapping("/courses") // endpoint for fetching all courses paginate
public Page<Course> searchAllCoursesByPageC() {
return serviceCourses.searchAllOfTheCoursesByPage();
}
@GetMapping("/courses/all") //endpoint for fetching all courses
public List<Course> searchAllCoursesC() {
return serviceCourses.searchAllCourses();
}
@PostMapping("/courses") //endpoint for saving a course
public Course saveCourseC(@RequestBody Course course) {
serviceCourses.saveCourse(course);
return course;
}
@GetMapping("/courses/{id}") // endpoint for fetching a course by id
public ResponseEntity<Course> searchCourseByIdC(@PathVariable("id") Integer id) {
Course course = serviceCourses.searchCourseById(id);
if (course != null) {
return new ResponseEntity<Course>(course, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND); //Status 404
}
@PutMapping("/courses/{id}") // endpoint for editing a course by id
public ResponseEntity<Course> modifyC(@PathVariable("id") int code, @RequestBody Course courseToEdit){
Course course = serviceCourses.editCourse(courseToEdit, code);
if (course != null) {
return new ResponseEntity<Course>(course, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND); //Status 404
}
@DeleteMapping("/courses/{id}") //endpoint for deleting a course
public ResponseEntity<Course>deleteC(@PathVariable ("id") int code) {
Course course = serviceCourses.deleteCourse(code);
if (course != null) {
return new ResponseEntity<Course>(course, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND); //Status 404
}
/*@PutMapping("/courses/{id}") //endpoint for editing a course
public String modifyC(@PathVariable ("id") int code, @RequestBody Course course) {
serviceCourses.editCourse(course, code);
return "Register has been edited successfully";
}*/
/*@DeleteMapping("/courses/{id}") //endpoint for deleting a course
public String deleteC(@PathVariable ("id") int code) {
serviceCourses.deleteCourse(code);
return "Register has been deleted successfully";
}*/
}
| true |
6de4b37fb746c61db8838b407a8df162103ec1da | Java | ajaytiwari000/Habbit | /sm-core/src/main/java/com/salesmanager/core/business/repositories/RewardConsumptionCriteriaRepository.java | UTF-8 | 940 | 2.046875 | 2 | [] | no_license | package com.salesmanager.core.business.repositories;
import com.salesmanager.core.model.common.RewardConsumptionCriteria;
import com.salesmanager.core.model.common.enumerator.TierType;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface RewardConsumptionCriteriaRepository
extends JpaRepository<RewardConsumptionCriteria, Long> {
@Query("select distinct rcc from RewardConsumptionCriteria rcc where rcc.id= ?1")
Optional<RewardConsumptionCriteria> getById(Long id);
@Query("select distinct rcc from RewardConsumptionCriteria rcc where rcc.tierType= ?1")
Optional<RewardConsumptionCriteria> getRewardConsumptionCriteriaByType(TierType tierType);
@Query("select distinct rcc from RewardConsumptionCriteria rcc")
Optional<List<RewardConsumptionCriteria>> getAllRewardConsumptionCriteria();
}
| true |
5b4d44f97d869496b058328195720a7cebc4c8dc | Java | AbuBallan/aspire-final-assignment | /task-2/payment/src/main/java/com/ab/payment/adapter/message/outbound/PaidOutputChannel.java | UTF-8 | 290 | 1.648438 | 2 | [] | no_license | package com.ab.payment.adapter.message.outbound;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
public interface PaidOutputChannel {
String OUTPUT = "paid-payment";
@Output(OUTPUT)
MessageChannel output();
}
| true |
432b1c51a76e7881b91aef925312f33957e4a08b | Java | mmassey1993/QA-JavaSE-Week1 | /Battleships/src/test/java/ShipTest.java | UTF-8 | 603 | 2.671875 | 3 | [] | no_license | import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.TestCase.assertEquals;
public class ShipTest {
private int size;
private int xPos;
private int yPos;
private List<Ship> shipList;
@Before
public void setup(){
size = 2;
xPos = 1;
yPos = 1;
shipList = new ArrayList<Ship>();
}
@Test
public void createShip(){
assertEquals(true, size != 0);
assertEquals(true, xPos!= 0 && yPos != 0);
}
@Test
public void addShip(){
}
}
| true |
b2331ce1153bce8c5d0337770c40b176ee64ab68 | Java | Synature-Jitthapong/myrepo_lib | /src/syn/pos/data/dao/DocumentStatus.java | UTF-8 | 231 | 1.773438 | 2 | [] | no_license | package syn.pos.data.dao;
public class DocumentStatus {
static final int PREPARE_DOCUMENT = 0;
static final int COMPLETE_DOCUMENT = 2;
static final int WORKING_DOCUMENT = 1;
static final int CANCEL_DOCUMENT = 99;
}
| true |
bdcb99a51acc5022c75c27a2d8c562f6e1ba0e3f | Java | ritasipaque/PrototipoP31P2021 | /PrototipoP31P2021/src/dominio/Maestro.java | UTF-8 | 1,967 | 2.171875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dominio;
/**
*
* @author familia Sipaque
*/
public class Maestro {
private int codigo_maestro;
private String nombre_maestro;
private String direccion_maestro;
private String telefono_maestro;
private String email_maestro;
private String estatus_maestro;
public int getCodigo_maestro() {
return codigo_maestro;
}
public void setCodigo_maestro(int codigo_maestro) {
this.codigo_maestro = codigo_maestro;
}
public String getNombre_maestro() {
return nombre_maestro;
}
@Override
public String toString() {
return "Maestro{" + "codigo_maestro=" + codigo_maestro + ", nombre_maestro=" + nombre_maestro + ", direccion_maestro=" + direccion_maestro + ", telefono_maestro=" + telefono_maestro + ", email_maestro=" + email_maestro + ", estatus_maestro=" + estatus_maestro + '}';
}
public void setNombre_maestro(String nombre_maestro) {
this.nombre_maestro = nombre_maestro;
}
public String getDireccion_maestro() {
return direccion_maestro;
}
public void setDireccion_maestro(String direccion_maestro) {
this.direccion_maestro = direccion_maestro;
}
public String getTelefono_maestro() {
return telefono_maestro;
}
public void setTelefono_maestro(String telefono_maestro) {
this.telefono_maestro = telefono_maestro;
}
public String getEmail_maestro() {
return email_maestro;
}
public void setEmail_maestro(String email_maestro) {
this.email_maestro = email_maestro;
}
public String getEstatus_maestro() {
return estatus_maestro;
}
public void setEstatus_maestro(String estatus_maestro) {
this.estatus_maestro = estatus_maestro;
}
}
| true |
81f81cdd7c73a70115bfb383de2a071d7dc804e1 | Java | vytaut1as/newssite | /src/NArticle.java | UTF-8 | 440 | 2.40625 | 2 | [] | no_license | import lt.vtvpmc.Article;
public class NArticle implements Article {
private String brief;
private String heading;
public NArticle() {
}
public NArticle(String arg1, String arg2){
this.heading = arg1;
this.brief = arg2;
}
@Override
public String getBrief() {
// TODO Auto-generated method stub
return brief;
}
@Override
public String getHeading() {
// TODO Auto-generated method stub
return heading;
}
}
| true |
14319344af271fc14bc7bf05b3ac583fe247cd61 | Java | shellrean/management-gudang | /src/main/java/com/shellrean/management/barang/domain/dao/Shipper.java | UTF-8 | 417 | 1.875 | 2 | [] | no_license | package com.shellrean.management.barang.domain.dao;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Table(name = "tbl_shipper")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Shipper {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nama;
private String codeShipper;
}
| true |
03a88cad98f921fa537cdc871ed253a1e35aac98 | Java | rototor/jeuclid | /kas/src/main/java/cTree/cCombine/CC_StrichFracFracN.java | UTF-8 | 3,340 | 1.96875 | 2 | [
"Apache-2.0",
"BSD-2-Clause"
] | permissive | /*
* Copyright 2009 Erhard Kuenzel
*
* 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 cTree.cCombine;
import cTree.CElement;
import cTree.CFences;
import cTree.CFrac;
import cTree.CMinTerm;
import cTree.CNum;
import cTree.CRolle;
import cTree.cDefence.CD_Event;
public class CC_StrichFracFracN extends CC_Base {
private CFrac b1;
private CFrac b2;
@Override
public boolean canDo() {
final CElement cE1 = this.getFirst();
final CElement cE2 = this.getSec();
if (cE1 instanceof CFrac && cE2 instanceof CFrac) {
this.b1 = (CFrac) cE1;
this.b2 = (CFrac) cE2;
if (this.b1.hasNumberValue() && this.b2.hasNumberValue()) {
return true;
}
}
return false;
}
@Override
protected CElement createComb(final CElement parent, final CElement cE1,
final CElement cE2, final CD_Event cDEvent) {
System.out.println("Add Frac and Mixed");
final int zVal1 = ((CNum) this.b1.getZaehler()).getValue();
final int nVal1 = ((CNum) this.b1.getNenner()).getValue();
final int zVal2 = ((CNum) this.b2.getZaehler()).getValue();
final int nVal2 = ((CNum) this.b2.getNenner()).getValue();
final int vz1 = cE1.hasExtMinus() ? -1 : 1;
final int vz2 = cE2.hasExtMinus() ? -1 : 1;
final int wertZ = vz1 * zVal1 * nVal2 + vz2 * zVal2 * nVal1;
int aWertZ = Math.abs(wertZ);
int newNVal = nVal1 * nVal2;
final int newCom = CC_StrichFracFracN.ggT(aWertZ, newNVal);
aWertZ = aWertZ / newCom;
newNVal = newNVal / newCom;
final int vzWert = (wertZ < 0) ? -1 : 1;
final CFrac arg = (CFrac) cE1.cloneCElement(false);
((CNum) arg.getZaehler()).setValue(aWertZ);
((CNum) arg.getNenner()).setValue(newNVal);
CElement newChild = arg;
if (cE1.getCRolle() == CRolle.SUMMAND1) {
if (cE2.hasExtMinus() && (wertZ < 0)) {
newChild = CMinTerm.createMinTerm(arg, CRolle.SUMMAND1);
}
} else if (cE1.getCRolle() == CRolle.NACHVZMINUS) {
if (wertZ < 0) {
newChild = CMinTerm.createMinTerm(arg, CRolle.SUMMAND1);
}
} else {
if (vzWert * vz1 < 0) {
final CMinTerm minTerm = CMinTerm.createMinTerm(arg);
newChild = CFences.condCreateFenced(minTerm, cDEvent);
}
}
return newChild;
}
private static int ggT(final int a, final int b) {
int g = a;
int q = b;
int r = 0;
while (q != 0) {
r = g % q;
g = q;
q = r;
}
return g;
}
}
| true |
727c25a41bd0629dadec676fff959cf39632268a | Java | Srdjan294/JP23 | /eclipse/ProjectEuler/src/projectEuler/Problem003.java | UTF-8 | 882 | 3.96875 | 4 | [] | no_license | package projectEuler;
public class Problem003 {
// The prime factors of 13195 are 5, 7, 13 and 29.
//
// What is the largest prime factor of the number 600851475143 ?
// A function to print all prime numbers of a given number n
public static void primeFactors(long n) {
// Print the number of 2s that devide n
while(n % 2 == 0) {
System.out.println(2 + " ");
n /= 2;
}
// n must be odd at this point. So we can skip one element (Note i = i + 2)
for(int i = 3; i <= Math.sqrt(n); i += 2) {
// While i divides n, print i and divide n
while(n % i == 0) {
System.out.println(i + " ");
n /= i;
}
}
// This condition is to handle the case when n is a prime number greater than 2
if(n > 2) {
System.out.println(n);
}
}
public static void main(String[] args) {
long n = 600851475143L;
primeFactors(n);
}
}
| true |
cccd5b0e0caac390f96b297e4a78fb55fe963813 | Java | mhersc1/EVEREST | /Katmandu/ADTProject/src/pe/com/everest/adtprogram/Main.java | UTF-8 | 1,256 | 2.640625 | 3 | [] | no_license | package pe.com.everest.adtprogram;
import static pe.com.everest.adtprogram.OperationHandler.operacionesConADT;
public class Main {
public static void main(String[] args) {
ADTListHandler adtListHandler = new ADTListHandler();
ADTMapHandler adtHashTableHandler = new ADTMapHandler();
ADTSetHandler adtSetHandler = new ADTSetHandler();
ADTStackHandler adtStackHandler = new ADTStackHandler();
ADTGraphHandler adtGraphHandler = new ADTGraphHandler();
for (; ; )
switch (OperationHandler.displayMenuPrincipal()) {
case 0:
System.exit(0);
case 1: //ADT Lista
operacionesConADT(adtListHandler);
break;
case 2://ADT HashTable
operacionesConADT(adtHashTableHandler);
break;
case 3://ADT Arbol
operacionesConADT(adtSetHandler);
break;
case 4://ADT Pila
operacionesConADT(adtStackHandler);
break;
case 5://ADT Grafo
operacionesConADT(adtGraphHandler);
break;
}
}
}
| true |
7f41779c790cb847a77360dfa3ced2a5e0029d5a | Java | gintian/TimeMatrix | /src/edu/purdue/timematrix/visualization/Manager.java | UTF-8 | 3,744 | 2.546875 | 3 | [
"MIT"
] | permissive | package edu.purdue.timematrix.visualization;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import edu.purdue.timematrix.aggregation.AggGraph;
import edu.purdue.timematrix.aggregation.AggGraph.AggNode;
import edu.purdue.timematrix.overlay.OverlayManager;
import edu.purdue.timematrix.stat.StatManager;
public class Manager {
private static EdgeCompositor edgeComp = null;
private static NodeCompositor[] nodeComp = null; // 0 : Horizontal, 1: Vertical
private static FilterManager filterManager = null;
private static OverlayManager overlayManager = null;
private static StatManager statManager = null;
private static EventManager eventManager = null;
private static int maxNodeSize = 1;
static class EventManager implements PropertyChangeListener {
private AggGraph aggGraph;
public EventManager(AggGraph aggGraph) {
this.aggGraph = aggGraph;
}
@SuppressWarnings("unchecked")
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(AggGraph.PROPERTY_AGGREGATION)) {
ArrayList<AggNode> oldNodes = (ArrayList<AggNode>) evt.getOldValue();
ArrayList<AggNode> newNodes = (ArrayList<AggNode>) evt.getNewValue();
// Update Statistics
if (oldNodes.size() == 1) { // Collapse
Manager.statManager.updateStats();
if (oldNodes.get(0).getTotalItemCount() == maxNodeSize) {
Manager.maxNodeSize = aggGraph.getMaxTotalItemCount();
}
}
else if (newNodes.size() == 1) { // Aggregate
Manager.statManager.updateStats(newNodes.get(0));
if (newNodes.get(0).getTotalItemCount() > Manager.maxNodeSize) {
assert (newNodes.get(0).getTotalItemCount() == aggGraph.getMaxTotalItemCount());
Manager.maxNodeSize = newNodes.get(0).getTotalItemCount();
}
}
// Update Edges
Manager.overlayManager.invalidateAll(aggGraph);
}
}
}
private Manager() {
// empty
}
public static void setAggGraph(AggGraph aggGraph) {
assert(Manager.eventManager == null);
Manager.eventManager = new EventManager(aggGraph);
aggGraph.addPropertyChangeListener(Manager.eventManager);
}
public static void setEdgeComp(EdgeCompositor edgeComp) {
assert (Manager.edgeComp == null);
Manager.edgeComp = edgeComp;
}
public static EdgeCompositor getEdgeComp() {
assert (edgeComp != null);
return edgeComp;
}
public static void setNodeComp(NodeCompositor nodeComp, boolean horz) {
if (Manager.nodeComp == null)
Manager.nodeComp = new NodeCompositor [2];
assert (Manager.nodeComp[horz ? 0 : 1] == null);
Manager.nodeComp[horz ? 0 : 1] = nodeComp;
}
public static NodeCompositor getNodeComp(boolean horz) {
assert (nodeComp[horz ? 0 : 1] != null);
return nodeComp[horz ? 0 : 1];
}
public static void setFilterManager(FilterManager filterManager) {
assert (Manager.filterManager == null);
Manager.filterManager = filterManager;
}
public static FilterManager getFilterManager() {
assert (filterManager != null);
return filterManager;
}
public static void setOverlayManager(OverlayManager overlayManager) {
assert (Manager.overlayManager == null);
Manager.overlayManager = overlayManager;
}
public static OverlayManager getOverlayManager() {
assert (overlayManager != null);
return overlayManager;
}
public static void setStatManager(StatManager statManager) {
assert (Manager.statManager == null);
Manager.statManager = statManager;
}
public static StatManager getStatManager() {
assert (statManager != null);
return statManager;
}
public static int getMaxNodeSize() {
return Manager.maxNodeSize;
}
} | true |
06cbea23dd8277e8c5e78dcd3c3c52c717101f75 | Java | dzdevjee/mesCourses | /workspace/MesCoursesPrimefaces/src/com/lamine/metier/impl/UtilisationMetierImpl.java | UTF-8 | 900 | 2.296875 | 2 | [] | no_license | package com.lamine.metier.impl;
import java.util.List;
import com.lamine.dao.interfaces.UtilisationDAO;
import com.lamine.metier.interfaces.UtilisationMetier;
import com.lamine.dao.entite.Utilisation;
import com.lamine.dao.impl.UtilisationDAOImpl;
public class UtilisationMetierImpl implements UtilisationMetier {
private UtilisationDAO utilisationDao = new UtilisationDAOImpl();
@Override
public Integer creer(Utilisation utilisation) {
return utilisationDao.creer(utilisation);
}
@Override
public Utilisation modifier(Utilisation utilisation) {
return utilisationDao.modifier(utilisation);
}
@Override
public void supprimer(Integer idUse) {
utilisationDao.supprimer(idUse);
}
@Override
public Utilisation afficher(Integer idUse) {
return utilisationDao.afficher(idUse);
}
@Override
public List<Utilisation> toutAfficher() {
return utilisationDao.toutAfficher();
}
} | true |
159048041084403af4a5a5a075d661101faddc23 | Java | guan4015/Exchange | /Exchange.java | UTF-8 | 2,810 | 3.078125 | 3 | [] | no_license | package ExchangeTerminal;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This class defines the Exchange that is used to store and process the tickers
* being traded, resting orders and communications between clients and the exchange.
*
* @author xiaog
*
*/
public class Exchange {
// MarketId is the ticker symbol
protected HashMap<MarketId, Market> _record;
protected HashMap<ClientOrderId, RestingOrder> _processingOrders;
protected Comms _comms;
// Default constructor
public Exchange () {
_record = new HashMap<MarketId, Market>();
_processingOrders = new HashMap<ClientOrderId, RestingOrder>();
_comms = new Comms();
}
public void addMarket(Market market) {
_record.put(market.getMarketId(), market);
}
public Market getMarket(MarketId marketid) {
return _record.get(marketid);
}
// The following method is the one that make the user cancel his/her orders
public void cancel( Cancel cancelMessage ) throws Exception {
RestingOrder restingOrder = _processingOrders.get( cancelMessage.getClientOrderId() );
if( restingOrder == null ) {
_comms.sendCancelRejected( new CancelRejected( cancelMessage.getClientId(), cancelMessage.getClientOrderId() ) );
} else {
restingOrder.cancel();
_processingOrders.remove( cancelMessage.getClientOrderId() );
_comms.cancellation( new Cancellation( cancelMessage.getClientId(), cancelMessage.getClientOrderId() ) );
}
}
// Adding the resting order
public void AddingRestingOrder( RestingOrder restingOrder ) {
_processingOrders.put( restingOrder.getClientOrderId(), restingOrder );
// Send client a message about this order
RestingOrderConfirmation restingOrderConfirmation = new RestingOrderConfirmation( restingOrder );
_comms.sendRestingOrderConfirmation( restingOrderConfirmation );
}
public void sweep( SweepingOrder sweepingOrder ) throws Exception {
// Retrieve the market
Market market = _record.get( sweepingOrder.getMarketId() );
// Once the sweep has been done. We have to manipulate the order book
// If the order could be filled, then the price levels in the bid book and offer book should
// match each other.
market.sweep( sweepingOrder );
// The following should retrieve the resting order to the resting orders
}
// Getters
public RestingOrder getOrder( ClientOrderId clientorderId ) {
return _processingOrders.get( clientorderId );
}
public HashMap<ClientOrderId, RestingOrder> getProcessingOrder() {
return _processingOrders;
}
public Comms getComms() {
return _comms;
}
// Modifiers
public void removeOrder( RestingOrder restingorder ) {
_processingOrders.remove( restingorder.getClientOrderId() );
}
}
| true |
2fc07a9d30e02f9c8b8af88b23c65e1da6531004 | Java | nghiemxuanquang/shoppingmall | /update part 5/example2/src/main/java/com/common/ImageUpload.java | UTF-8 | 1,873 | 2.8125 | 3 | [] | no_license | package com.common;
import com.mortennobel.imagescaling.AdvancedResizeOp;
import com.mortennobel.imagescaling.ResampleOp;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageUpload {
public void saveImage(byte[] bytes, String imageFileName, String rootPath) throws IOException {
File serverFile = imageWrite(bytes, imageFileName, rootPath);
if(bytes.length>1000000){
imageResizing(imageFileName, rootPath, serverFile);
}
}
private File imageWrite(byte[] bytes, String imageFileName,
String rootPath) throws IOException {
File dir = new File(rootPath);
if(!dir.exists()){
dir.mkdir();
}
File serverFile = new File(dir.getAbsolutePath()+File.separator+imageFileName);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
return serverFile;
}
private void imageResizing(String imageFileName, String rootPath,File serverFile) throws IOException {
BufferedImage resizeFile = ImageIO.read(serverFile);
ResampleOp resampleOp = new ResampleOp(450,300);
resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.VerySharp);
BufferedImage rescaled = resampleOp.filter(resizeFile, null);
String thumbnailImage = "thumbnail_"+imageFileName;
File thumbnailDir = new File(rootPath);
if(!thumbnailDir.exists()){
thumbnailDir.mkdir();
}
File thumbnailImageFile = new File(thumbnailDir.getAbsolutePath()+File.separator+thumbnailImage);
ImageIO.write(rescaled,"JPG",thumbnailImageFile);
}
}
| true |
159c90495a5aecda91f161d4f327c7c0988ce779 | Java | victordrnd/java-city | /src/Fenetre.java | UTF-8 | 3,936 | 2.734375 | 3 | [] | no_license | import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
public class Fenetre extends JFrame {
private JPanel contentPane;
private JTextField TXTCountry;
private JButton btnSearch;
private JButton btnUpdate;
private JButton btnDelete;
private JButton btnDetails;
private JScrollPane scrollPane;
private JTable tableCity;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Fenetre frame = new Fenetre();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Fenetre() {
setBackground(new Color(112, 128, 144));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 526, 379);
contentPane = new JPanel();
contentPane.setBackground(new Color(119, 136, 153));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
panel.setBackground(new Color(112, 128, 144));
contentPane.add(panel, BorderLayout.NORTH);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblCountry = new JLabel("Country :");
lblCountry.setBackground(new Color(255, 255, 255));
lblCountry.setForeground(new Color(255, 255, 255));
panel.add(lblCountry);
TXTCountry = new JTextField();
TXTCountry.setForeground(new Color(0, 0, 0));
TXTCountry.setBackground(new Color(255, 255, 255));
panel.add(TXTCountry);
TXTCountry.setColumns(10);
btnSearch = new JButton("Search");
btnSearch.setName("search");
btnSearch.setForeground(Color.WHITE);
btnSearch.setBackground(new Color(100, 149, 237));
btnSearch.setFont(new Font("Courier 10 Pitch", Font.BOLD, 12));
panel.add(btnSearch);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(112, 128, 144));
contentPane.add(panel_1, BorderLayout.SOUTH);
btnUpdate = new JButton("Update");
btnUpdate.setName("update");
btnUpdate.setFont(new Font("Courier 10 Pitch", Font.BOLD, 12));
btnUpdate.setForeground(new Color(255, 255, 255));
btnUpdate.setBackground(new Color(100, 149, 237));
panel_1.add(btnUpdate);
btnDelete = new JButton("Delete");
btnDelete.setName("delete");
btnDelete.setForeground(new Color(255, 255, 255));
btnDelete.setBackground(new Color(100, 149, 237));
btnDelete.setFont(new Font("Courier 10 Pitch", Font.BOLD, 12));
panel_1.add(btnDelete);
btnDetails = new JButton("Details");
btnDetails.setName("details");
btnDetails.setForeground(new Color(255, 255, 255));
btnDetails.setBackground(new Color(100, 149, 237));
btnDetails.setFont(new Font("Courier 10 Pitch", Font.BOLD, 12));
panel_1.add(btnDetails);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
tableCity = new JTable();
tableCity.setModel(new DefaultTableModel(
new Object[][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
},
new String[] {
"New column", "New column", "New column", "New column"
}
));
scrollPane.setViewportView(tableCity);
}
public JTextField getTXTCountry() {
return TXTCountry;
}
public JButton getBtnSearch() {
return btnSearch;
}
public JButton getBtnUpdate() {
return btnUpdate;
}
public JButton getBtnDelete() {
return btnDelete;
}
public JButton getBtnDetails() {
return btnDetails;
}
public JTable getTableCity() {
return tableCity;
}
}
| true |
372517ca56efb45e047f1efe8ec4f4b6ebc94a61 | Java | Pushp1403/Timezone-store-spring-Oauth-React | /tz-store/src/main/java/com/toptal/pushpendra/utilities/Constants.java | UTF-8 | 4,310 | 2.109375 | 2 | [] | no_license | package com.toptal.pushpendra.utilities;
public class Constants {
public static final String INTERNAL_SERVER_ERROR = "Internal Server Error";
public static final String BLANK_STRING = "";
public static final String COMMA = ", ";
public static final String ROLE_USER_MANAGER = "ROLE_USER_MANAGER";
public static final String ROLE_ADMIN = "ROLE_ADMIN";
public static final String ROLE_USER = "ROLE_USER";
public static final String USER_DISABLED = "User Disabled";
public static final String INVALID_CREDENTIALS = "Invalid Credentials";
public static final String NEED_JWT_TOKEN = "You would need to provide JWT token to access this resource";
public static final String JWT_TOKEN_BEARER = "Bearer ";
public static final String USER_ALREADY_EXISTS = "User Already Exists with given username/emailId";
public static final String JWT_TOKEN_UNABLE_TO_GET_USERNAME = "JWT_TOKEN_UNABLE_TO_GET_USERNAME";
public static final String JWT_TOKEN_EXPIRED = "JWT_TOKEN_EXPIRED";
public static final String JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING = "JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING";
public static final String USER_NOT_EXIST = "User Does not exist. Please Register User first";
public static final String MISSING_INFORMATION = "Missing required information";
public static final String ADDRESS = "Address";
public static final String DESCRIPTION = "Description";
public static final String FLOOR_AREA = "Floor Area";
public static final String LATTITUDE = "Lattitude";
public static final String LONGITUDE = "Longitude";
public static final String NAME = "Name";
public static final String NUMBER_OF_ROOMS = "Number of Rooms";
public static final String PRICE = "Price";
public static final String FIRST_NAME = "First Name";
public static final String LAST_NAME = "Last Name";
public static final String USER_NAME = "User Name";
public static final String PASSWORD = "Password";
public static final String EMAIL_ADDRESS = "Email Address";
// TimeZone Error Messages
public static final String TIMEZONE_CITY = "Timezone For City";
public static final String TIMEZONE_NAME = "Name For Timezone";
public static final String TIMEZONE_DIFF = "Diference to GMT";
public static final String TIMEZONE_DOES_NOT_EXIST = "TimeZone Doesn't Exist";
public static final String EMAIL_VERIFICATION_PENDING = "Email Verification pending.Please verify your email";
public static final String ACCOUNT_LOCKED = "Account locked";
public static final String MANDATORY = " is mandatory";
public static final String SYSTEM_USER = "SYSTEM";
public static final String TEMPLATE_PATH = "/mailtemplates/";
public static final String SINGLE_SPACE = " ";
public static final String BASE_URL = "http://localhost:8080";
public static final String SIGNUP_URL = "http://localhost:3000/signup";
public static final String VERIFICATION_END_POINT = "/auth/emailverification";
public static final String QUESTION_MARK = "?";
public static final String ACCESS_TOKEN = "accessToken";
public static final String EQUAL_SIGN = "=";
public static final String INVITATION_END_POINT = "/api/invite/emailInvitation";
public static final String VERIFICATION_SUBJECT = "Please verify your account";
public static final String INVITATION_SUBJECT = "Hurray !! Invitation to join TzStore";
public static final String INVITATION_SENT = "Invitation sent successfully";
public static final String VERIFICATION_COMPLETE = "Email Verification completed. Please proceed to login.";
public static final String USER_DELETED = "User deleted successfully";
public static final String TIMEZONE_DELETED = "Timezone entry deleted successfully";
public static final String REGISTRATION_SUCCESSFUL = "User registered successfully. Please verify your email to proceed";
public static final Object VERIFICATION_FAILED = "Email Verification failed. Retry.";
public static final String LOGOUT_DONE = "You are logged out";
public static final String INACTIVE_USER_SESSION = "No Active user session";
public static final String USER_ALREADY_LOGGED_OUT = "User has been logged out. Please login again to continue";
public static final String NOT_ALLOWED = "Not allowed to register a user";
public static final String CAN_NOT_UPDATE_PASSWORD = "You are not allowed to change username/password for existing user";
}
| true |
0a76f71c813836720429b15cb8ce2d4864e7b290 | Java | Abduselam99/JavaHomeworks | /Homework1/src/JavaExercise7.java | UTF-8 | 420 | 4.03125 | 4 | [] | no_license |
public class JavaExercise7 {
public static void main(String[] args) {
/* Write a Java program to print the area and perimeter of a circle.
* Test Data:
* Hint: Use Math.PI
* Radius = 7.5
*/
double radius =7.5;
double perimetre = 2* Math.PI*radius;
double area = Math.PI*radius*radius;
System.out.println("perimetre is =" + perimetre);
System.out.println("area is =" + area);
}
}
| true |
16b508317223ebcbfe0e8293175f0fc6888e5272 | Java | delca85/puzzlesolver | /parte2/puzzlesolver/io/MalformedFileException.java | UTF-8 | 187 | 1.898438 | 2 | [] | no_license | package puzzlesolver.io;
import java.io.IOException;
/**
* Raised whenever the input file does not appear to be valid.
*/
public class MalformedFileException extends IOException {
}
| true |
1b779972c72f5bd4fd4badff233b71b0e57f327a | Java | IS908/leetcode | /src/main/java/leetcode/L083_RemoveDuplicatesFromSortedList.java | UTF-8 | 889 | 3.609375 | 4 | [] | no_license | package leetcode;
import leetcode.Utils.ListNode;
/**
* Given a sorted linked list, delete all duplicates such that each element appear only once.
* <p/>
* For example,
* Given 1->1->2, return 1->2.
* Given 1->1->2->3->3, return 1->2->3.
* <p/>
* Created by kevin on 2016/3/8.
*/
// 换一种思路,相等时向后移动指针,不相等时将指针指向当前位置
public class L083_RemoveDuplicatesFromSortedList {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
while (cur != null && cur.next != null) {
ListNode next = cur.next;
while (next != null && cur.val == next.val) {
next = next.next;
}
cur.next = next;
cur = cur.next;
}
return head;
}
}
| true |
5e30dbb919a2fda1e90a1a59246f07ef7d563b73 | Java | njanmelbin/uber-backend | /src/main/java/com/uber/uberapi/services/messagequeue/KafakeService.java | UTF-8 | 877 | 2.765625 | 3 | [] | no_license | package com.uber.uberapi.services.messagequeue;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
@Service
public class KafakeService implements MessageQueue{
private final Map<String, Queue<MQMessage>> topics = new HashMap<>();
@Override
public void sendMessage(String topic, MQMessage message) {
System.out.printf("Kafka: append to queue %s:%s", topic,message.toString());
topics.putIfAbsent(topic,new LinkedList<>());
topics.get(topic).add(message);
}
@Override
public MQMessage consumeMessage(String topic) {
MQMessage mqMessage = (MQMessage) topics.getOrDefault(topic, new LinkedList<>()).poll();
System.out.printf("Kafak consumed %s : %s",topic, mqMessage.toString());
return mqMessage;
}
}
| true |
d5d179567f43113a876ceff9d65745613b31e0e9 | Java | yugesha/codehint | /codehint-plugin/src/codehint/dialogs/StatePropertyDialog.java | UTF-8 | 3,385 | 2.46875 | 2 | [] | no_license | package codehint.dialogs;
import org.eclipse.debug.core.DebugException;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import org.eclipse.jdt.debug.eval.IAstEvaluationEngine;
import org.eclipse.jface.dialogs.IInputValidator;
import codehint.exprgen.TypeCache;
import codehint.property.Property;
import codehint.property.StateProperty;
import codehint.utils.EclipseUtils;
public class StatePropertyDialog extends PropertyDialog {
private final String pdspecMessage;
private final String initialPdspecText;
private final IInputValidator pdspecValidator;
public StatePropertyDialog(String varName, IJavaStackFrame stack, String initialValue, String extraMessage) {
super(varName, extraMessage, stack);
String myVarName = varName == null ? StateProperty.FREE_VAR_NAME : varName;
String pdspecMessage = "Demonstrate a property that should hold for " + myVarName + " after this statement is executed. You may refer to the values of variables after this statement is executed using the prime syntax, e.g., " + myVarName + "\'";
this.pdspecMessage = getFullMessage(pdspecMessage, extraMessage);
this.initialPdspecText = initialValue;
this.pdspecValidator = new StatePropertyValidator(stack, varName == null);
}
@Override
public String getPdspecMessage() {
return pdspecMessage;
}
@Override
public String getInitialPdspecText() {
return initialPdspecText;
}
@Override
public IInputValidator getPdspecValidator() {
return pdspecValidator;
}
private static class StatePropertyValidator implements IInputValidator {
private final IJavaStackFrame stackFrame;
private final IAstEvaluationEngine evaluationEngine;
private final String freeVarError;
public StatePropertyValidator(IJavaStackFrame stackFrame, boolean isFreeVar) {
this.stackFrame = stackFrame;
this.evaluationEngine = EclipseUtils.getASTEvaluationEngine(stackFrame);
this.freeVarError = isFreeVar ? "[" + StateProperty.FREE_VAR_NAME + " cannot be resolved to a variable]" : null;
}
@Override
public String isValid(String newText) {
String msg = StateProperty.isLegalProperty(newText, stackFrame, evaluationEngine);
// TODO: This allows some illegal pdspecs like "_rv'+0" because the only error we get back is about _rv, which we ignore.
if (freeVarError != null && freeVarError.equals(msg)) {
try {
// Ensure the special variable is only used prime.
if (stackFrame.findVariable(StateProperty.FREE_VAR_NAME) == null) {
for (int i = -1; (i = newText.indexOf(StateProperty.FREE_VAR_NAME, ++i)) != -1; ) {
if (i + StateProperty.FREE_VAR_NAME.length() >= newText.length() || Character.isJavaIdentifierPart(newText.charAt(i + StateProperty.FREE_VAR_NAME.length())))
return "You cannot use the pseudo-variable " + StateProperty.FREE_VAR_NAME + " without priming it.";
}
}
} catch (DebugException e) {
throw new RuntimeException(e);
}
return null;
}
return msg;
}
}
@Override
public Property computeProperty(String propertyText, TypeCache typeCache) {
if (propertyText == null)
return null;
else
return StateProperty.fromPropertyString(varName == null ? StateProperty.FREE_VAR_NAME : varName, propertyText, stack);
}
@Override
public String getHelpID() {
return "state";
}
}
| true |
c43b64469a66cdcc5eff90f6f5b1829b4699619f | Java | TubaBee/SeleniumBatchV | /src/myWork/Callender.java | UTF-8 | 1,678 | 2.3125 | 2 | [] | no_license | package myWork;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class Callender {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
WebDriver d=new ChromeDriver();
d.get("http://166.62.36.207/humanresources/symfony/web/index.php/auth");
//login into HRMS
d.findElement(By.xpath("//input[@id='txtUsername']")).sendKeys("Admin");
d.findElement(By.xpath("//input[@id='txtPassword']")).sendKeys("Hum@nhrm123");
d.findElement(By.xpath("//input[@id='btnLogin']")).click();
Thread.sleep(2000);
d.findElement(By.linkText("Leave")).click();
d.findElement(By.linkText("Leave List")).click();
Thread.sleep(1000);
d.findElement(By.xpath("//img[@class='ui-datepicker-trigger']")).click();
Thread.sleep(1000);
WebElement month=d.findElement(By.className("ui-datepicker-month"));
Select s=new Select(month);
s.selectByIndex(3);
Thread.sleep(1000);
WebElement year=d.findElement(By.className("ui-datepicker-year"));
Select y=new Select(year);
y.selectByValue("1984");
//year bolumunde kac tane secenek var bulur
List<WebElement> op=y.getOptions();
System.out.println(op.size());
Thread.sleep(2000);
List<WebElement> cells=d.findElements(By.xpath("//table[@class='ui-datepicker-calendar']/tbody/tr/td"));
for(WebElement c:cells) {
if(c.getText().equals("28")) {
c.click();
break;
}
}
// Thread.sleep(7000);
// d.quit();
}
}
| true |
bed58da061076c625e651a70dc9e186050416286 | Java | Nabarun/CrmTest | /CrmTest.ModelClasses/src/ModelRecommendUserToFollow.java | UTF-8 | 1,974 | 2.078125 | 2 | [
"ISC"
] | permissive | import java.util.List;
public class ModelRecommendUserToFollow {
private String userName;
private String companyName;
private String userId;
private String title;
private String reasonForRecommendation;
private String photoUrl;
private String accessToken;
private List<String> twitterMessages;
private List<String> linkedinMessages;
private List<String> facebookMessages;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public List<String> getTwitterMessages() {
return twitterMessages;
}
public void setTwitterMessages(List<String> twitterMessages) {
this.twitterMessages = twitterMessages;
}
public List<String> getLinkedinMessages() {
return linkedinMessages;
}
public void setLinkedinMessages(List<String> linkedinMessages) {
this.linkedinMessages = linkedinMessages;
}
public List<String> getFacebookMessages() {
return facebookMessages;
}
public void setFacebookMessages(List<String> facebookMessages) {
this.facebookMessages = facebookMessages;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getReasonForRecommendation() {
return reasonForRecommendation;
}
public void setReasonForRecommendation(String reasonForRecommendation) {
this.reasonForRecommendation = reasonForRecommendation;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}
| true |
6c99a7b645e0a9b7a5ccb8f32dfc5378639d8883 | Java | vinhha86/qlsv-project | /backend/src/main/java/com/niit/backend/entities/FileResponse.java | UTF-8 | 747 | 2.375 | 2 | [] | no_license | package com.niit.backend.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import javax.persistence.*;
@Entity
@Table(name = "avatar")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FileResponse {
public FileResponse(String fileName, String fileDownloadUri, String fileType, long size) {
this.fileName = fileName;
this.fileDownloadUri = fileDownloadUri;
this.fileType = fileType;
this.size = size;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String fileName;
private String fileDownloadUri;
private String fileType;
private long size;
}
| true |
b8ab49f50bd2377273ea87f44333f3aeb1866738 | Java | jf908/UltraEvent | /net/xyfe/ultraplugin/UltraEventBarrier.java | UTF-8 | 2,800 | 2.53125 | 3 | [
"MIT"
] | permissive | package net.xyfe.ultraplugin;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Player;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class UltraEventBarrier {
private double radius;
TrapPlayer trapPlayer;
Set<FallingBlock> blocks = new HashSet<>();
BukkitRunnable spawner;
BukkitRunnable velocitySetter;
public UltraEventBarrier(JavaPlugin plugin, UltraEvent ultraEvent) {
Location loc = ultraEvent.getLocation();
radius = ultraEvent.getRadius();
// Activate player "trap" to keep players in area
trapPlayer = new TrapPlayer(loc, radius);
trapPlayer.activate(plugin);
// Teleport players outside of event area to inside
for(Player player : plugin.getServer().getOnlinePlayers()) {
if(!trapPlayer.inRange(player.getLocation())) {
player.teleport(loc);
}
}
World world = loc.getWorld();
spawner = new BukkitRunnable() {
@Override
public void run() {
for(int i=0; i<50; i++) {
double theta = ((double)i)/50 * Math.PI * 2;
FallingBlock block = world.spawnFallingBlock(new Location(world,
loc.getX() + radius*Math.cos(theta),
128,
loc.getZ() + radius*Math.sin(theta)
), new MaterialData(Material.MAGMA));
block.setDropItem(false);
blocks.add(block);
}
}
};
spawner.runTaskTimer(plugin, 0,5);
velocitySetter = new BukkitRunnable() {
@Override
public void run() {
Iterator<FallingBlock> itr = blocks.iterator();
while(itr.hasNext()) {
FallingBlock block = itr.next();
if(!block.isValid()) {
itr.remove();
} else {
block.setVelocity(new Vector(0,-1f,0));
}
}
}
};
velocitySetter.runTaskTimer(plugin, 0,1);
}
public void deactivate() {
trapPlayer.deactivate();
velocitySetter.cancel();
spawner.cancel();
// Kill blocks
for(FallingBlock block : blocks) {
block.remove();
}
blocks.clear();
}
}
| true |
b3627504e8b7c81487c4d4353b2f2c7fc89649cb | Java | youngseonL/2020_JAVA | /Ch07(생성자)/src/exam09/RectangelEx.java | UHC | 544 | 3.53125 | 4 | [] | no_license | package exam09;
import java.util.Scanner;
public class RectangelEx {
private int width;
private int height;
public double Sum(int width, int height) {
this.height = height;
this.width = width;
return this.height*this.width;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
RectangelEx r1 = new RectangelEx();
System.out.println("ʺ, Է : ");
int n = sc.nextInt();
int m = sc.nextInt();
System.out.println("簢 : " + r1.Sum(n, m));
}
}
| true |
b6ec2c27701170b3dab1ef3b0c7f946a2776508f | Java | srilakshmi488/Mr.How | /app/src/main/java/com/volive/mrhow/activities/VideoScreenActivity.java | UTF-8 | 10,071 | 1.609375 | 2 | [] | no_license | package com.volive.mrhow.activities;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import com.bumptech.glide.Glide;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.gson.JsonElement;
import com.volive.mrhow.R;
import com.volive.mrhow.util.ApiClass;
import com.volive.mrhow.util.MainUrl;
import com.volive.mrhow.util.NetworkConnection;
import com.volive.mrhow.util.PreferenceUtils;
import com.volive.mrhow.util.RetrofitClass;
import org.json.JSONObject;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class VideoScreenActivity extends AppCompatActivity {
Button button_signin, button_signup;
NetworkConnection networkConnection;
PreferenceUtils preferenceUtils;
SimpleExoPlayerView exoPlayerView;
SimpleExoPlayer exoPlayer;
String newVideoUrl,languageToLoad,language;
ImageView image_home,image_language;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_video_screen);
preferenceUtils = new PreferenceUtils(VideoScreenActivity.this);
networkConnection = new NetworkConnection(VideoScreenActivity.this);
language = preferenceUtils.getStringFromPreference(PreferenceUtils.Language,"");
initializeUI();
initializeValues();
}
private void initializeUI() {
button_signin = findViewById(R.id.button_signin);
button_signup = findViewById(R.id.button_signup);
image_home = findViewById(R.id.image_home);
image_language = findViewById(R.id.image_language);
}
private void initializeValues() {
button_signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(VideoScreenActivity.this, LogInActivity.class));
// finish();
}
});
button_signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(VideoScreenActivity.this, SignUp.class));
// finish();
}
});
image_language.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ChangeDialog();
}
});
}
@Override
protected void onResume() {
super.onResume();
if(exoPlayerView==null){
exoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exo_player_view);
exoPlayerView.setUseController(false);
if(networkConnection.isConnectingToInternet()) {
welcomeVideo();
}else {
Toast.makeText(VideoScreenActivity.this, getResources().getText(R.string.connecttointernet), Toast.LENGTH_SHORT).show();
}
}
}
private void welcomeVideo() {
ApiClass apiClass = RetrofitClass.getRetrofitInstance().create(ApiClass.class);
Call<JsonElement> call=apiClass.welcomevideo(MainUrl.apikey,language);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
Log.e("sdfdg f",response.body().toString());
if(response.isSuccessful()){
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
String status = jsonObject.getString("status");
String base_url= jsonObject.getString("base_url");
if(status.equalsIgnoreCase("1")) {
JSONObject dataobject = jsonObject.getJSONObject("data");
String video = dataobject.getString("video");
String type = dataobject.getString("type");
if(type.equalsIgnoreCase("video")){
image_home.setVisibility(View.GONE);
exoPlayerView.setVisibility(View.VISIBLE);
}else {
image_home.setVisibility(View.VISIBLE);
exoPlayerView.setVisibility(View.GONE);
Glide.with(VideoScreenActivity.this).load(base_url+video).into(image_home);
}
newVideoUrl=base_url+video;
playVideo(newVideoUrl);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.e("dsfjdshf ",t.toString());
}
});
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
releasePlayer();
super.onDestroy();
}
private void releasePlayer() {
if (exoPlayer != null) {
exoPlayer.stop();
exoPlayer.release();
exoPlayer = null;
}
}
private void playVideo(String newVideoUrl) {
try {
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
Uri videoURI = Uri.parse(newVideoUrl);
DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource(videoURI, dataSourceFactory, extractorsFactory, null, null);
exoPlayerView.setPlayer(exoPlayer);
exoPlayer.prepare(mediaSource);
exoPlayer.setPlayWhenReady(true);
} catch (Exception e) {
Log.e("jhjghjhj", e.toString());
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private void ChangeDialog() {
final Dialog dialog = new Dialog(VideoScreenActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.change_dialog);
dialog.setCanceledOnTouchOutside(false);
Button button_english = (Button) dialog.findViewById(R.id.button_english);
Button button_arabic = (Button) dialog.findViewById(R.id.button_arabic);
dialog.show();
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button_english.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
languageToLoad = "en"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
preferenceUtils.setLanguage("en");
Intent intent = new Intent(VideoScreenActivity.this, VideoScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
button_arabic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
languageToLoad = "ar"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
preferenceUtils.setLanguage("ar");
Intent intent = new Intent(VideoScreenActivity.this, VideoScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
}
}
| true |
cc3aeb4f9318bdc11d74d3af44ad2c836735c446 | Java | Ozonek95/File-differentiator | /src/com/filedifferentiator/extension_comparison/exceptions/ContentTypeNotFitExtensionException.java | UTF-8 | 231 | 1.921875 | 2 | [] | no_license | package com.filedifferentiator.extension_comparison.exceptions;
public class ContentTypeNotFitExtensionException extends Exception {
public ContentTypeNotFitExtensionException(String message) {
super(message);
}
}
| true |
a4025b09720660824ba96744c9f22f78e6d35937 | Java | domchowit/qa-rest-api | /src/test/java/com/hello/fresh/rest/automation/framework/api/RestClient.java | UTF-8 | 1,534 | 2.4375 | 2 | [] | no_license | package com.hello.fresh.rest.automation.framework.api;
import static io.restassured.RestAssured.given;
import com.hello.fresh.rest.automation.framework.endpoint.Endpoint;
import io.restassured.http.Headers;
import io.restassured.response.Response;
public class RestClient {
protected String baseUrl;
protected RestClient(String host) {
this.baseUrl = host;
}
protected Response doGetAndReturnResponse(Endpoint endpoint) {
return given()
.baseUri(baseUrl)
.log().method()
.log().uri()
.get(endpoint.path()).andReturn();
}
protected Response doGetAndReturnResponse(String endpoint) {
return given()
.baseUri(baseUrl)
.log().method()
.log().uri()
.get(endpoint).andReturn();
}
protected Response doGetWithHeadersAndReturnResponse(String endpoint, Headers headers) {
Response response = given()
.baseUri(baseUrl)
.headers(headers)
.get(endpoint).andReturn();
return response;
}
protected Response doPostEndReturnResponse(Endpoint endpoint, String body) {
return given()
.baseUri(baseUrl)
.contentType("application/json")
.body(body)
.log().method()
.log().uri()
.log().body()
.post(endpoint.path()).andReturn();
}
protected Response doDeleteAndReturnResponse(String endpoint) {
return given()
.baseUri(baseUrl)
.log().method()
.log().uri()
.log().body()
.delete(endpoint).andReturn();
}
}
| true |
6522a5b68edc77522af4ebae9195aeec88d5330e | Java | chentouf/M1ICE_CompteurIntelligent | /ProjectOpenUp_v3/src/Compteur/SimulationCompteur.java | UTF-8 | 1,046 | 2.6875 | 3 | [] | no_license | package Compteur;
public class SimulationCompteur implements Runnable {
private ControleurCompteur controleur;
public SimulationCompteur(String id) {
// TODO Auto-generated constructor stub
controleur = new ControleurCompteur(id);
}
public ControleurCompteur getControleur() {
return controleur;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
controleur.getModeleCompteur().setHc(controleur.getModeleCompteur().getHc()+1);
controleur.getModeleCompteur().setHp(controleur.getModeleCompteur().getHp()+2);
//System.out.println(controleur.getVueCompteur().getDisplay());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
SimulationCompteur[] tab = new SimulationCompteur[3];
for(int i=0;i<3;i++){
tab[i] = new SimulationCompteur(""+i);
new Thread(tab[i]).start();
}
}
}
| true |
82f03006e66294030332150e032bef26f9797181 | Java | dennis0127/blog | /src/main/java/com/yyyow/blog/controller/TTestController.java | UTF-8 | 1,143 | 1.867188 | 2 | [] | no_license | package com.yyyow.blog.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyyow.blog.common.utils.PageUtils;
import com.yyyow.blog.common.utils.R;
import com.yyyow.blog.entity.TTestEntity;
import com.yyyow.blog.service.ITTestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author
* @since 2021-07-31
*/
@Api(tags = "测试")
@RestController
@RequestMapping("/api/v1")
public class TTestController {
@Autowired
ITTestService itTestService;
@ApiOperation(value = "测试列表", notes = "测试列表", httpMethod = "GET")
@GetMapping("/test")
public R test(){
PageHelper.startPage(1,10);
return R.ok(R.SUCCESS,"查询成功",new PageUtils(new PageInfo<>(itTestService.list())));
}
}
| true |
e3b7e50891d5b08a2033ef8affa1d6ffa47244c7 | Java | wl21st/flink-clean-architecture-example | /job/src/main/java/com/example/demo/job/infrastructure/flink/Job.java | UTF-8 | 256 | 1.8125 | 2 | [
"MIT"
] | permissive | package com.example.demo.job.infrastructure.flink;
import org.apache.flink.api.common.JobExecutionResult;
import java.io.Serializable;
public interface Job extends Serializable {
JobExecutionResult start() throws Exception;
String getName();
}
| true |
1447567c5917fa856285f830a1ddc1ddec585eb1 | Java | isis-github/project-template | /web/src/main/java/com/tianzhu/cms/controller/BaseAction.java | UTF-8 | 866 | 1.742188 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright © 2013 Changsha Shishuo Network Technology Co., Ltd. All rights reserved.
* 长沙市师说网络科技有限公司 版权所有
* http://www.shishuo.com
*/
package com.tianzhu.cms.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.tianzhu.cms.domain.service.ArticleService;
import com.tianzhu.cms.domain.service.FolderService;
import com.tianzhu.cms.domain.service.HeadlineService;
import com.tianzhu.cms.domain.service.TemplateService;
/**
*
* @author Herbert
*
*/
public class BaseAction {
@Autowired
protected FolderService folderService;
@Autowired
protected ArticleService fileService;
@Autowired
protected TemplateService themeService;
@Autowired
protected HeadlineService headlineService;
protected final Logger logger = Logger.getLogger(this.getClass());
}
| true |
008f0c738d389e37442736bceeebd221e1ed159c | Java | ossVerifier/jwala | /jwala-services/src/main/java/com/cerner/jwala/service/binarydistribution/BinaryDistributionControlService.java | UTF-8 | 2,700 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | package com.cerner.jwala.service.binarydistribution;
import com.cerner.jwala.common.exec.CommandOutput;
import com.cerner.jwala.exception.CommandFailureException;
/**
* Created by Arvindo Kinny on 10/11/2016.
*/
public interface BinaryDistributionControlService {
/**
* This method copies a resource on a remote host from source to destination folder
* @param hostname
* @param source
* @param destination
* @return
* @throws CommandFailureException
*/
CommandOutput secureCopyFile(final String hostname, final String source, final String destination) throws CommandFailureException;
/**
*
* @param hostname
* @param destination
* @return
* @throws CommandFailureException
*/
CommandOutput createDirectory(final String hostname, final String destination) throws CommandFailureException;
/**
*
* @param hostname
* @param destination
* @return
* @throws CommandFailureException
*/
CommandOutput checkFileExists(final String hostname, final String destination) throws CommandFailureException;
/**
*
* @param hostname
* @param zipPath
* @param destination
* @param exclude
* @return
* @throws CommandFailureException
*/
CommandOutput unzipBinary(final String hostname, final String zipPath, final String destination, final String exclude) throws CommandFailureException;
/**
*
* @param hostname
* @param destination
* @return
* @throws CommandFailureException
*/
CommandOutput deleteBinary(final String hostname, final String destination) throws CommandFailureException;
/**
*
* @param hostname
* @param mode
* @param targetDir
* @param target
* @return
* @throws CommandFailureException
*/
CommandOutput changeFileMode(final String hostname, final String mode, final String targetDir, final String target) throws CommandFailureException;
/**
*
* @param hostname Name of the host
* @param remotePath remote file of directory
* @throws CommandFailureException exception thrown when the command fails
*/
CommandOutput backupFileWithCopy(final String hostname, final String remotePath) throws CommandFailureException;
/**
*
* @param hostname Name of the host
* @param remotePath remote file of directory
* @throws CommandFailureException exception thrown when the command fails
*/
CommandOutput backupFileWithMove(final String hostname, final String remotePath) throws CommandFailureException;
}
| true |