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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
7fb5ff004c3380f7d0c44019b76bba314fbd5a2d | Java | moutainhigh/gomeo2o | /venus-trade-api/tags/release-1.0.0/src/main/java/cn/com/gome/trade/dto/io/split/request/ItemPriceInfoBySplitDto.java | UTF-8 | 374 | 1.804688 | 2 | [] | no_license | package cn.com.gome.trade.dto.io.split.request;
import java.io.Serializable;
public class ItemPriceInfoBySplitDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String amount; // 商品项总金额
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
| true |
d8f253727a7be3f13bd98a57e847e8aeeb82e9ac | Java | Jaceww/Java-Socket-Rogue-Game | /rouge_game/ClientHandler.java | UTF-8 | 9,691 | 2.9375 | 3 | [] | no_license | import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class ClientHandler extends Thread {
final DataInputStream dis;
final DataOutputStream dos;
final Socket s;
String playerID;
Game game;
int xPos;
int yPos;
private boolean done;
// Constructor
public ClientHandler(String playerID, Socket s, DataInputStream dis, DataOutputStream dos, int xPos, int yPos)
throws IOException {
this.s = s;
this.dis = dis;
this.dos = dos;
this.playerID = playerID;
this.game = Server.game;
this.xPos = xPos;
this.yPos = yPos;
this.done = false;
}
@Override
public void run() {
String received;
game.addPlayer(new Player(playerID, xPos, yPos, 10, false));
String allplayers = game.getPlayers();
String allSwords = game.getSwords();
try {
dos.writeUTF(playerID);
dos.writeUTF(allplayers);
dos.writeUTF(allSwords);
eventHandler("PLAYER_JOINED");
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
received = dis.readUTF();
if (received.equals("EXIT")) {
System.out.println("Client " + this.playerID + " sends exit...");
System.out.println("Closing this connection.");
this.s.close();
Server.removeThread(playerID);
Server.sendAll("GAME_OVER," + this.playerID);
System.out.println("Connection closed");
break;
}
if (received.equals("GAME_OVER") && !this.done) {
String winnerName = "none";
System.out.println("Game over for " + this.playerID);
Server.sendAll("GAME_OVER," + this.playerID);
HashMap<String, Player> playerObj = game.getAllPlayerObj();
int i = 0;
for (Map.Entry<String, Player> p : playerObj.entrySet()) {
if(!p.getValue().gameOver){
i++;
winnerName = p.getValue().getName();
}
}
if (i == 1){ Server.sendAll("PLAYER_WON," + winnerName); }
this.done = true;
}
if (!game.getPlayer(playerID).gameOver) {
eventHandler(received);
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
// closing resources
this.dis.close();
this.dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void eventHandler(String event) throws IOException {
Player p;
String command;
int xTmp;
int yTmp;
switch (event) {
case "PLAYER_JOINED":
System.out.println(playerID + " joined the game");
command = "PLAYER_JOINED," + playerID + "," + xPos + "," + yPos;
Server.sendAll(command);
break;
case "MOVE_UP":
p = game.getPlayer(playerID);
if (validMove(p.getX(), p.getY() - 10)) {
p.move_up();
moveEventHelper("MOVE_UP,", p);
}
break;
case "MOVE_DOWN":
p = game.getPlayer(playerID);
if (validMove(p.getX(), p.getY() + 10)) {
p.move_down();
moveEventHelper("MOVE_DOWN,", p);
}
break;
case "MOVE_RIGHT":
p = game.getPlayer(playerID);
if (validMove(p.getX() + 10, p.getY())) {
p.move_right();
moveEventHelper("MOVE_RIGHT,", p);
}
break;
case "MOVE_LEFT":
p = game.getPlayer(playerID);
if (validMove(p.getX() - 10, p.getY())) {
p.move_left();
moveEventHelper("MOVE_LEFT,", p);
}
break;
case "ATTACK":
p = game.getPlayer(playerID);
validAtk(p);
p.attack();
break;
}
}
private void moveEventHelper(String cmdWord, Player p) throws IOException {
String command;
game.updatePlayer(p);
command = cmdWord + playerID;
Server.sendAll(command);
}
private boolean validMove(int posX, int posY) {
HashMap<String, Player> playerList = game.getAllPlayerObj();
Player player = game.getPlayer(playerID);
String posState = player.positionState;
for (Map.Entry<String, Player> p : playerList.entrySet()) {
if (p.getValue().getName() != playerID) {
int x2 = p.getValue().getX();
int y2 = p.getValue().getY();
if (posState.equals("right") && posX + 20 >= x2 && posX < x2 + 40 && posY >= y2-50 && posY <= y2 + 40) {
System.out.println("invalid move");
return false;
} else if (posState.equals("left") && posX <= x2 + 40 && posX + 20 > x2 && posY >= y2-50 && posY <= y2 + 40) {
System.out.println("invalid move");
return false;
} else if (posState.equals("down") && posY <= y2 && posY > y2 - 20 && posX >= x2 -50 && posX <= x2 + 50) {
System.out.println("invalid move");
return false;
} else if (posState.equals("up") && posY < y2 + 20 && posY >= y2 && posX >= x2 -50 && posX <= x2 + 50) {
System.out.println("invalid move");
return false;
}
}
}
if (posX > 1 && posX < 969 && posY > 67 && posY < 653) {
return true;
} else {
System.out.println("invalid move");
return false;
}
}
private void validAtk(Player p) throws IOException {
int x = p.getX();
int y = p.getY();
String posState = p.positionState;
if (p.hasSword) {
HashMap<String, Player> playerObj = game.getAllPlayerObj();
for (Map.Entry<String, Player> otherP : playerObj.entrySet()) {
int x2 = otherP.getValue().getX();
int y2 = otherP.getValue().getY();
if (otherP.getValue().getName() != playerID) {
if (posState.equals("right") && x2 <= x + 70 && x2 >= x && y2 <= y + 50 && y2 >= y - 45) {
atkHelper(otherP.getValue(), p);
break;
} else if (posState.equals("left") && x2 >= x - 50 && x2 <= x && y2 <= y + 50 && y2 >= y - 45) {
atkHelper(otherP.getValue(), p);
break;
} else if (posState.equals("up") && x2 <= x + 60 && x2 >= x - 10 && y2 >= y - 70 && y2 <= y) {
atkHelper(otherP.getValue(), p);
break;
} else if (posState.equals("down") && x2 <= x + 60 && x2 >= x - 10 && y2 <= y + 70 && y2 >= y) {
atkHelper(otherP.getValue(), p);
break;
}
}
}
System.out.println(playerID + " attacked");
String command = "ATTACK," + playerID;
Server.sendAll(command);
} else {
ArrayList<ArrayList<Integer>> swordObj = game.getAllSwordObj();
int index = 0;
for (ArrayList<Integer> s : swordObj) {
int xS = s.get(0);
int yS = s.get(1);
if (posState.equals("right") && xS <= x + 70 && xS >= x && yS <= y + 50 && yS >= y - 45) {
pickupItem(index, p);
break;
} else if (posState.equals("left") && xS >= x - 50 && xS <= x && yS <= y + 50 && yS >= y - 45) {
pickupItem(index, p);
break;
} else if (posState.equals("up") && xS <= x + 60 && xS >= x - 10 && yS >= y - 70 && yS <= y) {
pickupItem(index, p);
break;
} else if (posState.equals("down") && xS <= x + 60 && xS >= x - 10 && yS <= y + 70 && yS >= y) {
pickupItem(index, p);
break;
}
index++;
}
}
game.updatePlayer(p);
}
public void atkHelper(Player otherP, Player p) throws IOException {
otherP.loseHealth();
game.updatePlayer(otherP);
p.playerLostSword();
System.out.println(playerID + " ATTACKED " + otherP.getName() + " total healt:" + otherP.getHealth());
String command = "LOSE_HEALTH," + otherP.getName() + "," + p.getName();
Server.sendAll(command);
}
public void pickupItem(int index, Player p) throws IOException {
game.removeSword(index);
p.playerGotSword();
System.out.println(p.getName() + " picked up an item");
String command = "PICK_UP," + p.getName() + "," + index;
Server.sendAll(command);
}
public void send(String event) throws IOException {
dos.writeUTF(event);
}
} | true |
a030311a0e4313f72fb01b40c95e6c0f300ff222 | Java | TypeMonkey/Wordy | /wordy/logic/runtime/components/StackComponent.java | UTF-8 | 484 | 2.875 | 3 | [
"MIT"
] | permissive | package wordy.logic.runtime.components;
/**
* Represents Components that can be pushed into the runtime stack, such as variables and instances
* (not frame stack, but the computation stack used when interpreting statements)
*
* @author Jose Guaro
*
*/
public abstract class StackComponent extends Component{
public StackComponent(String name) {
super(name);
}
public final boolean isCallable() {
return false;
}
public abstract boolean isAnInstance();
}
| true |
95aecdc2026d0e5018d796de6afe1fbe7e63000d | Java | Chen768959/flume-custom-extend | /merge-file-name-sink/src/main/java/pers/cly/merge_file_name_sink/MergeFileNameSink.java | UTF-8 | 5,190 | 2.46875 | 2 | [
"Apache-2.0"
] | permissive | package pers.cly.merge_file_name_sink;
import com.google.common.collect.Lists;
import org.apache.flume.Channel;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.Transaction;
import org.apache.flume.conf.Configurable;
import org.apache.flume.sink.AbstractSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Chen768959
* @date 2019/4/23
*/
public class MergeFileNameSink extends AbstractSink implements Configurable {
//本地目标路径
private String targetUrl = "";
//原始文件路径,需要正则出文件名
private String fileUrl = "";
//sink一个事务中,从queue队列中取出处理的event数量。(默认100)
private int batchSize = 100;
private static final Logger LOG = LoggerFactory.getLogger(MergeFileNameSink.class);
public Status process() throws EventDeliveryException {
Status status = Status.READY;
//获取Channel对象
Channel channel = getChannel();
//获取事务对象
Transaction transaction = channel.getTransaction();
transaction.begin();
try {
//一次性处理batch-size个event对象
List<Event> batch = Lists.newLinkedList();
for (int i = 0; i < batchSize; i++) {
Event event = channel.take();
if (event == null) {
break;
}
batch.add(event);
}
int size = batch.size();
if (size == 0) {
//BACKOFF表示让flume睡眠一段时间(因为此时已经取不出来event了)
status = Status.BACKOFF;
} else {//process
Map<String, List<Event>> relateFileEventsMap = new HashMap<>();
String fileName = "";
for (Event event : batch) {
//获取event所属文件名
String[] strings = event.getHeaders().get(fileUrl).split("/");
fileName = strings[strings.length - 1];
//判断map中是否有此文件所对应的event列表,如果没有则新建关系。
List<Event> relateEvents = relateFileEventsMap.get(fileName);
if (relateEvents == null) {
List<Event> newRelateEvents = new ArrayList<>();
newRelateEvents.add(event);
relateFileEventsMap.put(fileName, newRelateEvents);
} else {
relateEvents.add(event);
}
}
StringBuilder filePath = new StringBuilder().append(targetUrl).append("/").append(nowData()).append("/");
//迭代所有文件和其event列表,将events写入其对应文件
for (String relateFileName : relateFileEventsMap.keySet()) {
//文件路径
filePath.append(relateFileName);
//如果文件不存在,则创建新的文件
File file = new File(filePath.toString());
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
//将该文件对应的events全部写入文件
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
List<Event> events = relateFileEventsMap.get(relateFileName);
for (Event event : events) {
fileOutputStream.write(event.getBody());
// 写入一个换行
fileOutputStream.write("\r\n".getBytes());
}
fileOutputStream.close();
}
//READY表示event可以提交了
status = Status.READY;
}
//如果执行成功,最后一定要提交
transaction.commit();
} catch (IOException eIO) {
transaction.rollback();
LOG.warn("CustomLocalSink IO error", eIO);
status = Status.BACKOFF;
} catch (Throwable th) {
transaction.rollback();
LOG.error("CustomLocalSink process failed", th);
if (th instanceof Error) {
throw (Error) th;
} else {
throw new EventDeliveryException(th);
}
}finally {
//在关闭事务之前,必须执行过事务的提交或回退
transaction.close();
}
//将状态返回出去
return status;
}
/**
* 从conf文件获取定义好的常量
*
* @param context
* @return void
* @author Chen768959
* @date 2019/4/23 18:40
*/
public void configure(Context context) {
targetUrl = context.getString("targetUrl");
fileUrl = context.getString("fileUrl");
batchSize = context.getInteger("batchSize");
}
@Override
public synchronized void stop() {
super.stop();
}
@Override
public synchronized void start() {
try {
super.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private String nowData() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateNowStr = sdf.format(d);
return dateNowStr;
}
}
| true |
490cab41e567af40e16c04385fb08e02dca20dee | Java | iantal/AndroidPermissions | /apks/playstore_apps/com_ubercab/source/com/twilio/voice/impl/session/events/UnknownEvent.java | UTF-8 | 250 | 1.851563 | 2 | [
"Apache-2.0",
"GPL-1.0-or-later"
] | permissive | package com.twilio.voice.impl.session.events;
import com.twilio.voice.impl.session.Event;
import com.twilio.voice.impl.session.Event.Type;
public class UnknownEvent
extends Event
{
public UnknownEvent()
{
super(Event.Type.UNKNOWN);
}
}
| true |
ac3fee9a944d66d289d14501374e65b5a0fdde29 | Java | lukaszbinden/jmcs-pattern-recognition | /Exercise_4/src/ch/unifr/jmcs/patrec/ex04/Playground.java | UTF-8 | 230 | 1.6875 | 2 | [
"MIT"
] | permissive | package ch.unifr.jmcs.patrec.ex04;
public class Playground {
public static void main(String[] args) throws Exception {
MoleculeDataSet validSet = ValidationMain.load("data/validation/gxl");
validSet.loadAll();
}
}
| true |
f35117fe0c52499c96d052e6ba45fb861b9312d6 | Java | tkolsen/myplanner | /src/main/java/MyPlanner/exceptions/UserInfoNotSetException.java | UTF-8 | 281 | 2.359375 | 2 | [] | no_license | package MyPlanner.exceptions;
/**
* Created by TomKolse on 24-Nov-14.
*/
public class UserInfoNotSetException extends Exception{
public UserInfoNotSetException(String message) {
super(message);
}
public UserInfoNotSetException() {
super();
}
}
| true |
3f61219fe1dc15c730fa22ed0b1bae817268c08a | Java | quarkusio/quarkus | /integration-tests/redis-cache/src/test/java/io/quarkus/it/cache/redis/CacheTest.java | UTF-8 | 841 | 2.203125 | 2 | [
"Apache-2.0"
] | permissive | package io.quarkus.it.cache.redis;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
public class CacheTest {
@Test
public void testCache() {
runExpensiveRequest();
runExpensiveRequest();
runExpensiveRequest();
when().get("/expensive-resource/invocations").then().statusCode(200).body(is("1"));
when()
.post("/expensive-resource")
.then()
.statusCode(204);
}
private void runExpensiveRequest() {
when()
.get("/expensive-resource/I/love/Quarkus?foo=bar")
.then()
.statusCode(200)
.body("result", is("I love Quarkus too!"));
}
}
| true |
3b4787361fff7b2dd8da52ffb411c37ca3cb2ce1 | Java | wilfoderek/onion-architecture | /application/src/main/java/alekseybykov/portfolio/whitepappers/exceptions/WorkWithFilesException.java | UTF-8 | 358 | 2.3125 | 2 | [
"MIT"
] | permissive | package alekseybykov.portfolio.whitepappers.exceptions;
/**
* @author Aleksey Bykov
* @since 03.10.2019
*/
public class WorkWithFilesException extends RuntimeException {
public WorkWithFilesException(String message) {
super(message);
}
public WorkWithFilesException(String message, Throwable cause) {
super(message, cause);
}
}
| true |
ee42c6af223ab3bdb639159e6aa9bffe2da7f132 | Java | nicomori/CasoBusquedaEnGoogle6 | /src/test/java/com/smartfrog/pageobject/web/external/GmailHomePage.java | UTF-8 | 3,695 | 2.53125 | 3 | [] | no_license | package com.smartfrog.pageobject.web.external;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import com.smartfrog.framework.ParentPage;
public class GmailHomePage extends ParentPage {
/**
* @param driver
*/
public GmailHomePage(WebDriver driver) {
super(driver);
}
private By RECEIVED_EMAIL_ROWS = By.xpath("((//table)[5]/tbody/tr/td[6]/div/div)[1]");
private By EMAIL_RECEIVER = By.xpath("//span[contains(@email,'gmail.com')]");
private By EMAIL_RECEIVER_NEW_EMAIL = By.xpath("//td[8]");
private By GOOGLE_LOGO = By.xpath("//a[@href='#inbox']");
private By SELECT_ALL_CHECKBOX = By.xpath("//div[@role='button']//span[@role='checkbox']");
private By BAR_TRASH_BUTTON = By.xpath("(//div[@role='button' and contains(@style,'user-select: none;')])[6]");
/**
* this method make click in the checkbox select all.
*/
public void selectAllElements() {
System.out.println("Starting to make click in the icon select all.");
clickJSx2(GOOGLE_LOGO);
clickJSx2(SELECT_ALL_CHECKBOX);
}
/**
* this method make click in the icon Trash.
*/
public void clickInIconDeleteAll() {
System.out.println("Making click in the icon trash.");
clickJSx2(BAR_TRASH_BUTTON);
}
/**
* this method is going to wait until an specific email to some specific
* receiver arrive.
*
* @param String
* with the receiver email address.
*/
public void waitForAnEmailWithSpecificReceiverAndAccess(String receiverEmailAddress) {
boolean theCorrectEmailIsHere = false;
int trying = 0;
System.out.println(
"Waiting for the reception of the email with the receiver email equal to, " + receiverEmailAddress);
waitSleepingTheTread(2000);
do {
System.out.println("Verify if I can see a email.");
try {
if (verifyIfisDisplayedX2(RECEIVED_EMAIL_ROWS)) {
System.out.println("Verify if the email is the receiver email. making click in the email row.");
// inside of the email
click(RECEIVED_EMAIL_ROWS);
System.out.println("In the email body we are going to check the receiver.");
System.out.println("We are looking for this email receiver: " + receiverEmailAddress + "#");
String emailFinded = getAttributeFromLocator(EMAIL_RECEIVER, "data-hovercard-id");
System.out.println("And we find in the new email this address: " + emailFinded + "#");
if (emailFinded.contains(receiverEmailAddress)) {
System.out.println("We find the correct email and we are making click in the email.");
clickJSx2(EMAIL_RECEIVER_NEW_EMAIL);
theCorrectEmailIsHere = true;
System.out.println("We have the access to the email.");
} else {
System.out.println(
"An email is here, but not with the correct receiver. Deleting all the emails in the folder");
try {
click(GOOGLE_LOGO);
} catch (Exception e) {
click(GOOGLE_LOGO);
}
selectAllElements();
clickInIconDeleteAll();
}
} else {
if (trying < 18) {
System.out.println("We are waiting 30 sec until the correct email appear");
waitSleepingTheTread(20000);
refreshBrowser();
waitSleepingTheTread(10000);
By buttonYesGmailSecurityQuestions = By.xpath("//*[contains(text(),'Sí')]");
if (verifyIfisDisplayed(buttonYesGmailSecurityQuestions)) {
click(buttonYesGmailSecurityQuestions);
}
trying++;
} else {
System.out.println("We try more of 40 times to receive the emails, in 20 minutes.");
return;
}
}
} catch (Exception e) {
}
System.out.println("STATUS OF THE VARIABLE THECORRECTEMAILISHERE = " + theCorrectEmailIsHere);
} while (theCorrectEmailIsHere != true);
}
} | true |
8d950e21680ca5d1ce46c510645c0f86c56f40f2 | Java | sgstyjy/DT | /tpcw-nyu/src/edu/nyu/pdsg/tpcw/ejb/country/CountryModel.java | UTF-8 | 1,194 | 2.46875 | 2 | [] | no_license | package edu.nyu.pdsg.tpcw.ejb.country;
import java.io.Serializable;
/**
* Country bean.
*
* @author <a href="mailto:totok@cs.nyu.edu">Alexander Totok</a>
*
* @version $Revision: 1.4 $ $Date: 2005/02/05 21:26:28 $ $Author: totok $
*/
public class CountryModel implements Serializable {
private Integer CO_ID;
private String CO_NAME;
private Double CO_EXCHANGE;
private String CO_CURRENCY;
public CountryModel(Integer CO_ID, String CO_NAME, Double CO_EXCHANGE, String CO_CURRENCY) {
this.CO_ID = CO_ID;
this.CO_NAME = CO_NAME;
this.CO_EXCHANGE = CO_EXCHANGE;
this.CO_CURRENCY = CO_CURRENCY;
}
public CountryModel(Integer CO_ID) {
this.CO_ID = CO_ID;
}
// getters and setters
public String getCO_CURRENCY() {
return CO_CURRENCY;
}
public Double getCO_EXCHANGE() {
return CO_EXCHANGE;
}
public Integer getCO_ID() {
return CO_ID;
}
public String getCO_NAME() {
return CO_NAME;
}
public void setCO_CURRENCY(String string) {
CO_CURRENCY = string;
}
public void setCO_EXCHANGE(Double double1) {
CO_EXCHANGE = double1;
}
public void setCO_NAME(String string) {
CO_NAME = string;
}
}
| true |
718cd279727a329817d9a9645dfbcfd2a8d44a4a | Java | Nuccia95/Tesi2018 | /Catalogue/src/model/Review.java | UTF-8 | 1,130 | 2.21875 | 2 | [] | no_license | package model;
public class Review {
String id;
String placeName;
String head;
String stars;
String image;
String description;
String lastLine;
public Review() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHead() {
return head;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public void setHead(String head) {
this.head = head;
}
public String getStars() {
return stars;
}
public void setStars(String stars) {
this.stars = stars;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLastLine() {
return lastLine;
}
public void setLastLine(String lastLine) {
this.lastLine = lastLine;
}
}
| true |
c4856395fb42a296feb1cc55d25d04863ceae9fa | Java | Olivki/minecraft-clients | /GodlikeCraft [mc-1.3.2]/se/proxus/hacks/h_Breadcrumb.java | UTF-8 | 5,657 | 2.25 | 2 | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | package se.proxus.hacks;
import se.proxus.utils.placeholders.p_Breadcrum;
import net.minecraft.src.*;
import static org.lwjgl.opengl.GL11.*;
public class h_Breadcrumb extends Base_Hack {
public h_Breadcrumb() {
super('6', "Breadcrumb", "Draws lines after where you've walked.", "Render", "NONE");
}
@Override
public void onEnabled() {
}
@Override
public void onDisabled() {
}
@Override
public void onToggled() {
}
@Override
public void onUpdate() {
}
@Override
public void onRendered3D() {
if(this.getState()) {
for(p_Breadcrum var1 : this.vars.trailArray) {
double d = this.mc.thePlayer.lastTickPosX + (this.mc.thePlayer.posX - this.mc.thePlayer.lastTickPosX) * (double)this.mc.timer.renderPartialTicks;
double d1 = this.mc.thePlayer.lastTickPosY + (this.mc.thePlayer.posY - this.mc.thePlayer.lastTickPosY) * (double)this.mc.timer.renderPartialTicks;
double d2 = this.mc.thePlayer.lastTickPosZ + (this.mc.thePlayer.posZ - this.mc.thePlayer.lastTickPosZ) * (double)this.mc.timer.renderPartialTicks;
double d3 = this.vars.trailX - d;
double d4 = this.vars.trailY - d1;
double d5 = this.vars.trailZ - d2;
double x = var1.x - d;
double y = var1.y - d1;
double z = var1.z - d2;
this.enableDefaults();
//this.drawBox(d3, d4, d5, d3 + 1D, d4 + 1D, d5 + 1D);
//glBegin(GL_LINES);
//glVertex2d(0.0D, 0.0D);
/*glVertex3d(d3, d4, d5);
glVertex3d(x, y, z);*/
glColor4d(1.0D, 0.0D, 0.0D, 1.0D);
this.drawBox(x + 0.4D, y + 0.4D, z + 0.4D, x + 0.6D, y + 0.6D, z + 0.6D);
//glEnd();
this.disableDefaults();
}
}
}
@Override
public String[] getModString() {
return (new String[] {});
}
@Override
public int[] getModInteger() {
return (new int[] {});
}
@Override
public float[] getModFloat() {
return (new float[] {});
}
@Override
public long[] getModLong() {
return (new long[] {});
}
@Override
public boolean[] getModBoolean() {
return (new boolean[] {});
}
private void drawBox(double x, double y, double z, double x2, double y2, double z2) {
glBegin(GL_QUADS);
glVertex3d(x, y, z);
glVertex3d(x, y2, z);
glVertex3d(x2, y, z);
glVertex3d(x2, y2, z);
glVertex3d(x2, y, z2);
glVertex3d(x2, y2, z2);
glVertex3d(x, y, z2);
glVertex3d(x, y2, z2);
glEnd();
glBegin(GL_QUADS);
glVertex3d(x2, y2, z);
glVertex3d(x2, y, z);
glVertex3d(x, y2, z);
glVertex3d(x, y, z);
glVertex3d(x, y2, z2);
glVertex3d(x, y, z2);
glVertex3d(x2, y2, z2);
glVertex3d(x2, y, z2);
glEnd();
glBegin(GL_QUADS);
glVertex3d(x, y2, z);
glVertex3d(x2, y2, z);
glVertex3d(x2, y2, z2);
glVertex3d(x, y2, z2);
glVertex3d(x, y2, z);
glVertex3d(x, y2, z2);
glVertex3d(x2, y2, z2);
glVertex3d(x2, y2, z);
glEnd();
glBegin(GL_QUADS);
glVertex3d(x, y, z);
glVertex3d(x2, y, z);
glVertex3d(x2, y, z2);
glVertex3d(x, y, z2);
glVertex3d(x, y, z);
glVertex3d(x, y, z2);
glVertex3d(x2, y, z2);
glVertex3d(x2, y, z);
glEnd();
glBegin(GL_QUADS);
glVertex3d(x, y, z);
glVertex3d(x, y2, z);
glVertex3d(x, y, z2);
glVertex3d(x, y2, z2);
glVertex3d(x2, y, z2);
glVertex3d(x2, y2, z2);
glVertex3d(x2, y, z);
glVertex3d(x2, y2, z);
glEnd();
glBegin(GL_QUADS);
glVertex3d(x, y2, z2);
glVertex3d(x, y, z2);
glVertex3d(x, y2, z);
glVertex3d(x, y, z);
glVertex3d(x2, y2, z);
glVertex3d(x2, y, z);
glVertex3d(x2, y2, z2);
glVertex3d(x2, y, z2);
glEnd();
}
private void drawOutlinedBox(double x, double y, double z, double x2, double y2, double z2, float l1) {
glLineWidth(l1);
glBegin(GL_LINES);
glVertex3d(x, y, z);
glVertex3d(x, y2, z);
glVertex3d(x2, y, z);
glVertex3d(x2, y2, z);
glVertex3d(x2, y, z2);
glVertex3d(x2, y2, z2);
glVertex3d(x, y, z2);
glVertex3d(x, y2, z2);
glEnd();
glBegin(GL_LINES);
glVertex3d(x2, y2, z);
glVertex3d(x2, y, z);
glVertex3d(x, y2, z);
glVertex3d(x, y, z);
glVertex3d(x, y2, z2);
glVertex3d(x, y, z2);
glVertex3d(x2, y2, z2);
glVertex3d(x2, y, z2);
glEnd();
glBegin(GL_LINES);
glVertex3d(x, y2, z);
glVertex3d(x2, y2, z);
glVertex3d(x2, y2, z2);
glVertex3d(x, y2, z2);
glVertex3d(x, y2, z);
glVertex3d(x, y2, z2);
glVertex3d(x2, y2, z2);
glVertex3d(x2, y2, z);
glEnd();
glBegin(GL_LINES);
glVertex3d(x, y, z);
glVertex3d(x2, y, z);
glVertex3d(x2, y, z2);
glVertex3d(x, y, z2);
glVertex3d(x, y, z);
glVertex3d(x, y, z2);
glVertex3d(x2, y, z2);
glVertex3d(x2, y, z);
glEnd();
glBegin(GL_LINES);
glVertex3d(x, y, z);
glVertex3d(x, y2, z);
glVertex3d(x, y, z2);
glVertex3d(x, y2, z2);
glVertex3d(x2, y, z2);
glVertex3d(x2, y2, z2);
glVertex3d(x2, y, z);
glVertex3d(x2, y2, z);
glEnd();
glBegin(GL_LINES);
glVertex3d(x, y2, z2);
glVertex3d(x, y, z2);
glVertex3d(x, y2, z);
glVertex3d(x, y, z);
glVertex3d(x2, y2, z);
glVertex3d(x2, y, z);
glVertex3d(x2, y2, z2);
glVertex3d(x2, y, z2);
glEnd();
}
private void enableDefaults() {
this.mc.entityRenderer.disableLightmap(1.0D);
glEnable(3042 /*GL_BLEND*/);
glDisable(3553 /*GL_TEXTURE_2D*/);
glDisable(2896 /*GL_LIGHTING*/);
glDisable(2929 /*GL_DEPTH_TEST*/);
glDepthMask(false);
glBlendFunc(770, 771);
glEnable(2848 /*GL_LINE_SMOOTH*/);
glPushMatrix();
}
private void disableDefaults() {
glPopMatrix();
glDisable(2848 /*GL_LINE_SMOOTH*/);
glDepthMask(true);
glEnable(2929 /*GL_DEPTH_TEST*/);
glEnable(3553 /*GL_TEXTURE_2D*/);
glEnable(2896 /*GL_LIGHTING*/);
glDisable(3042 /*GL_BLEND*/);
this.mc.entityRenderer.enableLightmap(1.0D);
}
} | true |
9ef682c3f5fc2998e306f3d6ff8137e50b1d4f01 | Java | akp1989/fabric-java-sdk | /src/main/java/com/java/client/CAClient.java | UTF-8 | 5,764 | 2.25 | 2 | [] | no_license | package com.java.client;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.java.config.Config;
import com.java.user.UserContext;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallet.Identity;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric_ca.sdk.EnrollmentRequest;
import org.hyperledger.fabric_ca.sdk.HFCAClient;
import org.hyperledger.fabric_ca.sdk.RegistrationRequest;
public class CAClient {
String caUrl;
Properties caProperties;
HFCAClient instance;
UserContext adminContext;
Wallet wallet;
// Constructor
public CAClient(String caUrl, Properties caProperties) throws IllegalAccessException, InstantiationException, ClassNotFoundException, CryptoException, InvalidArgumentException, NoSuchMethodException, InvocationTargetException, IOException {
this.caUrl = caUrl;
this.caProperties = caProperties;
init();
}
// Creates a new fabric instance with the given CAURL and CA properties
public void init() throws IllegalAccessException, InstantiationException, ClassNotFoundException, CryptoException, InvalidArgumentException, NoSuchMethodException, InvocationTargetException, IOException {
instance = HFCAClient.createNewInstance(caUrl, caProperties);
CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
instance.setCryptoSuite(cryptoSuite);
wallet = Wallet.createFileSystemWallet(Config.WALLET_PATH);
}
public UserContext getAdminUserContext() {
return adminContext;
}
public void setAdminUserContext(UserContext userContext) {
this.adminContext = userContext;
}
public HFCAClient getInstance() {
return instance;
}
/**
* Enroll admin user.
*
* @param username
* @param password
* @return
* @throws Exception
*/
public UserContext enrollAdminUser(String username, String password) throws Exception {
/* Changes to remove the file structure user details to wallet level user details */
// UserContext userContext = Util.readUserContext(adminContext.getAffiliation(), username);
// if (userContext != null) {
// Logger.getLogger(CAClient.class.getName()).log(Level.WARNING, "CA -" + caUrl + " admin is already enrolled.");
// return userContext;
// }
String identityName = adminContext.getAffiliation()+"."+username;
if(!wallet.exists(identityName)) {
//Create an enrollment request to add the hostnames and enrollment type if needed
EnrollmentRequest enrollmentRequest = new EnrollmentRequest();
enrollmentRequest.addHost("localhost");
enrollmentRequest.addHost("192.168.0.175");
// Enroll the ID against the CA
Enrollment adminEnrollment = instance.enroll(username, password,enrollmentRequest);
adminContext.setIdentity(Identity.createIdentity(adminContext.getMspId(), adminEnrollment.getCert(),adminEnrollment.getKey()));
//Add the new admin identity to wallet
wallet.put(identityName, adminContext.getIdentity());
Logger.getLogger(CAClient.class.getName()).log(Level.INFO, "CA -" + caUrl + " Enrolled Admin.");
// Util.writeUserContext(adminContext);
return adminContext;
}else {
Logger.getLogger(CAClient.class.getName()).log(Level.WARNING, "CA -" + caUrl + "admin ID already enrolled");
adminContext.setIdentity(wallet.get(identityName));
return adminContext;
}
}
/**
* Register user.
*
* @param username
* @param organization
* @return
* @throws Exception
*/
public String registerUser(String username, String idType) throws Exception {
String identityName = adminContext.getAffiliation()+"_"+ username;
if(!wallet.exists(identityName)) {
RegistrationRequest registrationRequest = new RegistrationRequest(username);
if(idType == null) idType = Config.DEFAULT_CLIENT_ID;
registrationRequest.setType(idType);
String enrollmentSecret = instance.register(registrationRequest, adminContext);
Logger.getLogger(CAClient.class.getName()).log(Level.INFO, "CA -" + caUrl + " Registered User - " + username);
return enrollmentSecret;
}else {
Logger.getLogger(CAClient.class.getName()).log(Level.WARNING, "CA -" + caUrl + username + " already registered");
return null;
}
}
/**
* Enroll user.
*
* @param user
* @param secret
* @return
* @throws Exception
*/
public UserContext enrollUser(UserContext user, String secret) throws Exception {
String identityName = user.getAffiliation()+"_"+ user.getName();
if(!wallet.exists(identityName)) {
//Create an enrollment request to add the hostnames and enrollment type if needed
EnrollmentRequest enrollmentRequest = new EnrollmentRequest();
enrollmentRequest.addHost("localhost");
enrollmentRequest.addHost("192.168.0.175");
enrollmentRequest.addHost("192.168.0.66");
// Enroll the ID against the CA
Enrollment adminEnrollment = instance.enroll(user.getName(), secret,enrollmentRequest);
user.setIdentity(Identity.createIdentity(adminContext.getMspId(), adminEnrollment.getCert(),adminEnrollment.getKey()));
//Add the new admin identity to wallet
wallet.put(identityName, adminContext.getIdentity());
Logger.getLogger(CAClient.class.getName()).log(Level.INFO, "CA -" + caUrl +" Enrolled User - " + user.getName());
return user;
}else {
Logger.getLogger(CAClient.class.getName()).log(Level.WARNING, "CA -" + caUrl + user.getName() + "already enrolled");
user.setIdentity(wallet.get(identityName));
return user;
}
}
}
| true |
b6a9bb3c69c080257b9e652aa3817e9349b7814f | Java | agoshka/springDemo | /src/main/java/org/agoshka/demo/data/domain/Role.java | UTF-8 | 106 | 1.71875 | 2 | [] | no_license | package org.agoshka.demo.data.domain;
/**
*
* @author go
*/
public enum Role {
USER,
ADMIN;
}
| true |
1ac4809c1494d8145031432f6627a8ee78843f78 | Java | nekolr/lolibox | /lolibox-server/src/main/java/io/loli/box/service/impl/InvitationCodeServiceImpl.java | UTF-8 | 969 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | package io.loli.box.service.impl;
import io.loli.box.service.InvitationCodeService;
import org.hashids.Hashids;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
/**
* @author choco
*/
@Service
public class InvitationCodeServiceImpl implements InvitationCodeService {
@Autowired(required = false)
@Qualifier("invitationCodeHashIds")
private Hashids hashids;
public String generate(String email) {
return hashids.encode(Math.abs(email.hashCode()), System.currentTimeMillis());
}
public boolean verify(String email, String verificationCode) {
long decoded[] = hashids.decode(verificationCode);
if (decoded.length == 2) {
return decoded[0] == Math.abs(email.hashCode()) && (System.currentTimeMillis() - (3600 * 1000 * 24 * 7) < decoded[1]);
}
return false;
}
}
| true |
3fd2799c146652c47d5e5f796e23a8d3a523369c | Java | mikechernykh/cellular-provider | /cellular-provider-shell/src/main/java/dev/chernykh/cellular/shell/UserCommands.java | UTF-8 | 4,778 | 2.609375 | 3 | [] | no_license | package dev.chernykh.cellular.shell;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import static java.util.stream.Collectors.joining;
/**
* A set of shell commands to manage users.
*/
@ShellComponent
public class UserCommands {
private static final int MAX_FULL_NAME_LENGTH = 255;
private Map<Long, Map<String, Object>> users = new HashMap<>();
private AtomicLong idGenerator = new AtomicLong();
/**
* Add a new user.
*
* @param fullName the full name.
* @param tariffId the id of a tariff used by the user.
* @return the command output.
*/
@ShellMethod("Add new user.")
String addUser(
@ShellOption(help = "The full name.") @NotBlank @Length(max = MAX_FULL_NAME_LENGTH) String fullName,
@ShellOption(help = "The id of a tariff used by the user.") long tariffId) {
long id = idGenerator.incrementAndGet();
ImmutableMap<String, Object> user = ImmutableMap.of("id", id, "fullName", fullName, "tariffId", tariffId);
users.put(id, user);
return "New user added: " + user;
}
/**
* List users with optional filtering.
*
* @param filter the SpEL expression to which the users should conform
* @return the command output. One user per line.
*/
@ShellMethod("List users with optional filtering.")
String listUsers(@ShellOption(defaultValue = "") String filter) {
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(filter);
StandardEvaluationContext context = new StandardEvaluationContext();
context.addPropertyAccessor(new MapAccessor());
boolean isApplyFilter = !filter.isEmpty();
String result = users.values()
.stream()
.filter(user -> isApplyFilter ? expression.getValue(context, user, Boolean.class) : true)
.map(Object::toString)
.collect(joining("\n"));
return result.isEmpty() ? "No users." : result;
}
/**
* List users by given tariff id.
*
* @param tariff tariff id. Must not be empty
* @return the command output
*/
@ShellMethod("Show users by tariff id.")
String listUsersByTariff(@ShellOption(help = "User's tariff id") long tariff) {
String result = users.values()
.stream()
.filter(user -> user.get("tariffId").equals(tariff))
.map(Object::toString)
.collect(joining("\n"));
return result.isEmpty() ? "No one is found." : result;
}
/**
* Deletes user with given its id if one exists.
*
* @param id user id. Must not be empty
* @return the command output
*/
@ShellMethod("Remove user by specified id.")
String removeUser(@ShellOption(help = "User id") long id) {
return Optional.ofNullable(users.remove(id))
.map(user -> "Removed user: " + user)
.orElse("No user with id: " + id);
}
/**
* Updates details of given user if one exists.
*
* @param id user id. Must not be empty
* @param name new user name. Must no be empty
* @param tariffId new user's tariff. Must not be empty
* @return the command output
*/
@ShellMethod("Make change to user details.")
String updateUser(
@ShellOption(help = "User id") long id,
@ShellOption(help = "User full name") @NotBlank @Length(max = MAX_FULL_NAME_LENGTH) String name,
@ShellOption(help = "User's tariff id") long tariffId) {
Map<String, Object> user = users.get(id);
if (user == null) {
return "No user with id: " + id;
}
HashMap<String, Object> updatedUser = Maps.newHashMap(user);
updatedUser.replace("name", name);
updatedUser.replace("tariffId", tariffId);
users.replace(id, ImmutableMap.copyOf(updatedUser));
return "Updated user: " + updatedUser;
}
}
| true |
5539c51b085705644df2398e2e95b87a70e2f033 | Java | TweetyTheBird/java-homework | /src/sevenclasswork/animalspoly/runAnimals.java | UTF-8 | 541 | 3.3125 | 3 | [] | no_license | package sevenclasswork.animalspoly;
public class runAnimals {
public static void main(String args[]) {
Bird bird1 = new Bird();
bird1.setAnimalType("bird");
Lion lion1 = new Lion();
lion1.setAnimalType("snake");
Snake snake1 = new Snake();
snake1.setAnimalType("snake");
Animal[] animals = {bird1, lion1, snake1};
for (Animal a : animals) {
System.out.println("The " + a.toString() + " said:");
a.eat();
a.move();
}
}
}
| true |
a3fc58e168964d3b67b76b0d394807d88cfe4162 | Java | JasmineLiuLiuLiu/calculation-generator | /src/main/java/calculate/GenerateAndPrint.java | UTF-8 | 3,397 | 2.96875 | 3 | [] | no_license | package calculate;
import static calculate.metadata.Operator.ADD;
import static calculate.metadata.Operator.SUB;
import calculate.expressions.Equation;
import calculate.expressions.FloatEquation;
import calculate.generators.MixCalculationEquationGenerator;
import calculate.generators.MulCalculationExpressionsGenerator;
import calculate.generators.OralCalculationExpressionsGenerator;
import calculate.modifiers.DifferencePositiveModifier;
import java.util.ArrayList;
import java.util.FormatFlagsConversionMismatchException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class GenerateAndPrint {
public static void main(String[] args) {
// FloatEquation f = new DifferencePositiveModifier<FloatEquation>().modify(
// new FloatEquation(39*0.1f, 82*0.1f,ADD));
// System.out.println(f.printAll());
IntStream.range(0, 10).sequential().forEach((i) -> {
OralCalculationExpressionsGenerator og = new OralCalculationExpressionsGenerator(12);
MulCalculationExpressionsGenerator mulg = new MulCalculationExpressionsGenerator(8);
MixCalculationEquationGenerator mixg = new MixCalculationEquationGenerator(9);
i++;
System.out.println("\n\n\n数学计算练习 " + i);
System.out.println("1.\t口算。");
// printInFormat(og.generate(), "%s=\t\t\t%s=\t\t\t%s=\t\t\t%s=");
printAllInFormat(og.generate(), "%s\t\t\t%s\t\t\t%s\t\t\t%s");
System.out.println("2.\t用竖式计算,带*的要验算。");
// printInFormat(mulg.generate(), "%s\t\t\t\t%s\t\t\t\t%s\t\t\t\t* %s\n\n\n\n\n");
printAllInFormat(mulg.generate(), "%s\t\t\t\t%s\t\t\t\t%s\t\t\t\t* %s\n\n\n\n\n");
System.out.println("3.\t计算下列各题。");
// printInFormat(mixg.generate(), "%s\t\t\t\t\t\t\t%s\t\t\t\t\t\t%s\n\n\n\n\n");
printAllInFormat(mixg.generate(), "%s\t\t\t\t\t\t\t%s\t\t\t\t\t\t%s\n\n\n\n\n");
});
}
private static void printInFormat(Set<Equation> equations, String lineFormat) {
int countPerLine = getSubStringCount(lineFormat, "%s");
List<Equation> equationList = new ArrayList<>(equations);
for (int i = 0; i < equationList.toArray().length; i = i + countPerLine) {
List<Equation> ePrintInRow = new ArrayList<>();
for (int j = 0; j < countPerLine; j++) {
ePrintInRow.add(equationList.get(i + j));
}
System.out.println(String.format(lineFormat, ePrintInRow.stream().map(e -> e.print()).collect(
Collectors.toList()).toArray()));
}
}
private static void printAllInFormat(Set<Equation> equations, String lineFormat) {
int countPerLine = getSubStringCount(lineFormat, "%s");
List<Equation> equationList = new ArrayList<>(equations);
for (int i = 0; i < equationList.toArray().length; i = i + countPerLine) {
List<Equation> ePrintInRow = new ArrayList<>();
for (int j = 0; j < countPerLine; j++) {
ePrintInRow.add(equationList.get(i + j));
}
System.out.println(String.format(lineFormat, ePrintInRow.stream().map(e -> e.printAll()).collect(
Collectors.toList()).toArray()));
}
}
private static int getSubStringCount(String s, String sub) {
int count = 0;
int offset = 0;
while ((offset = s.indexOf(sub, offset)) != -1) {
offset += sub.length();
count++;
}
return count;
}
}
| true |
0ed4533e2c850a338b6db5f42f6a5f23c83846d5 | Java | shenzhijiangit/ICMServer | /icm-purchase/icm-purchase-rest-api/src/main/java/org/shenzhijian/controller/purchase/PurchaseReportController.java | UTF-8 | 7,753 | 2.109375 | 2 | [] | no_license | package org.shenzhijian.controller.purchase;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.shenzhijian.persistence.purchase.entity.PurchaseReport;
import org.shenzhijian.service.purchase.PurchaseReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@Api(tags = {"采购申请管理"})
@RestController
@RequestMapping("/api/icm-purchase/reports")
@Validated
public class PurchaseReportController {
private PurchaseReportService purchaseReportService;
@Autowired
public PurchaseReportController(PurchaseReportService purchaseReportService) {
this.purchaseReportService = purchaseReportService;
}
// @ApiOperation(value = "分页查询采购申请信息")
// @GetMapping(value = "")
// public PageDataDTO<PurchaseReport> findOnePage(
// @ApiParam(value = "页号,从0开始", required = true, defaultValue = "0") @RequestParam("page") @Min(0) int page,
// @ApiParam(value = "每页纪录条数", required = true, defaultValue = "20") @RequestParam("size") @Min(1) @Max(100) int size,
// @ApiParam(value = "排序字段, 例如:字段1,asc,字段2,desc") @RequestParam(value = "sort", required = false, defaultValue = "id,desc") String sort,
// @ApiParam(value = "状态类型,查询类型", required = true) @RequestParam(value = "stateType", required = false, defaultValue = "ALL") StateType stateType,
// @ApiParam(value = "申请部门ID") @RequestParam(value = "departmentId", required = false) String departmentId,
// @ApiParam(value = "申请人姓名,支持模糊查询") @RequestParam(value = "declarerName", required = false) String declarerName,
// @ApiParam(value = "业务标题,支持模糊查询") @RequestParam(value = "title", required = false) String title,
// @ApiParam(value = "申请单位ID") @RequestParam(value = "unitId", required = false) String unitId,
// @ApiParam(value = "采购申请起始日期,区间查询", example = "2019-10-15") @RequestParam(value = "beginDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date beginDate,
// @ApiParam(value = "采购申请结束日期,区间查询", example = "2019-10-15") @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date endDate,
// @ApiParam(value = "采购类型:耗材/品目") @RequestParam(value = "purchaseType", required = false, defaultValue = "ALL") PurchaseType purchaseType,
// @ApiParam(value = "支出类型") @RequestParam(value = "budgetApprovalType", required = false, defaultValue = "ALL") BudgetApprovalType budgetApprovalType,
// @ApiParam(value = "采购单号") @RequestParam(value = "code", required = false) String code,
// @ApiParam(value = "最小采购金额") @RequestParam(value = "beginAmount", required = false) Double beginAmount,
// @ApiParam(value = "最大采购金额") @RequestParam(value = "endAmount", required = false) Double endAmount
//
// ) {
// return purchaseReportService.findOnePage(page, size, sort, stateType, departmentId, declarerName, title, purchaseType, budgetApprovalType, unitId, beginDate, endDate, beginAmount, endAmount, code);
// }
@ApiOperation(value = "查询当前操作可获取的采购申请")
@GetMapping(value = "/all/done")
public List<PurchaseReport> findAllDone(
@ApiParam(value = "采购申请id()") @RequestParam(value = "id", required = false) String id,
@ApiParam(value = "部门id()") @RequestParam(value = "departmentId", required = false) String departmentId
) {
return null;
}
@ApiOperation(value = "通过采购状态、采购类型查询采购申请")
@GetMapping(value = "/all")
public List<PurchaseReport> findAll(
) {
return purchaseReportService.findAll();
}
@ApiOperation(value = "查询可用余额大于0的采购申请")
@GetMapping(value = "/available")
public List<PurchaseReport> findAvailable(
@ApiParam(value = "部门id()", required = true) @RequestParam(value = "departmentId") String departmentId,
@ApiParam(value = "采购id") @RequestParam(value = "id", required = false) String id
) {
return purchaseReportService.findAvailable(departmentId, id);
}
@ApiOperation(value = "根据ID查询采购申请")
@GetMapping(value = "/{id}")
public PurchaseReport findById(
@ApiParam(value = "采购申请Id", required = true) @PathVariable(name = "id") String id,
@ApiParam(value = "任务Id") @RequestParam(value = "taskId", required = false) String taskId,
@ApiParam(value = "是否过滤已验收内容") @RequestParam(value = "isFilter", required = false, defaultValue = "false") boolean isFilter
) {
return purchaseReportService.findById(id, taskId, isFilter);
}
@ApiOperation(value = "招标登记时使用:根据ID查询采购申请(过滤掉已经进行招标登记过的采购品目)")
@GetMapping(value = "/id")
public PurchaseReport findCategoriesById(
@ApiParam(value = "采购申请Id", required = true) @RequestParam(value = "id") String id,
@ApiParam(value = "招标Id") @RequestParam(value = "bidId", required = false) String bidId
) {
return purchaseReportService.findCategoriesById(id, bidId, false);
}
@ApiOperation(value = "采购验收时使用:根据ID查询采购申请(过滤掉已经进行验收登记过的采购内容)")
@PutMapping(value = "/id")
public PurchaseReport findPurchaseContentById(
@ApiParam(value = "采购申请Id", required = true) @RequestParam(value = "id") String id,
@ApiParam(value = "验收Id") @RequestParam(value = "acceptanceId", required = false) String acceptanceId
) {
return purchaseReportService.findPurchaseContentById(id, acceptanceId);
}
@ApiOperation(value = "新建采购申请")
@PostMapping(value = "")
public PurchaseReport create(
@ApiParam(value = "采购申请创建信息", required = true) @RequestBody @Validated PurchaseReport createInfo
) throws IOException {
return purchaseReportService.create(createInfo);
}
@ApiOperation(value = "提交采购申请")
@PutMapping(value = "/{id}")
public PurchaseReport complete(
@ApiParam(value = "采购申请Id", required = true) @PathVariable(name = "id") String id,
@ApiParam(value = "采购申请编辑信息", required = true) @RequestBody @Validated PurchaseReport editInfo
) throws IOException {
return purchaseReportService.complete(id, editInfo);
}
@ApiOperation(value = "删除采购申请")
@DeleteMapping(value = "/{id}")
public void delete(
@ApiParam(value = "支出预算Id", required = true) @PathVariable(name = "id") String id
) {
purchaseReportService.delete(id);
}
@ApiOperation(value = "获取采购品目中所用的指标库的可用余额")
@GetMapping(value = "/index")
public Map<String, Double> getIndex(
@ApiParam(value = "当前指标id集合", required = true) @RequestParam(name = "ids") List<String> ids,
@ApiParam(value = "采购申请ID") @RequestParam(name = "id", required = false) String id
) {
return purchaseReportService.getIndex(id, ids);
}
}
| true |
912eed7b7b82eb7bdd2cce8c375d91cc4dd5d638 | Java | robinlabs/RobinClient | /app/src/main/java/com/magnifis/parking/Xml.java | UTF-8 | 18,252 | 2.703125 | 3 | [] | no_license | /*
* Xml.java
*
* Created on April 3, 2007, 11:38 AM
*
* Copyright(C) 2007 Ze'ev (Vladimir) Belkin. All rights reserved.
*
<h1>The Artistic License</h1>
<tt>
<p>Preamble</p>
<p>The intent of this document is to state the conditions under which a
Package may be copied, such that the Copyright Holder maintains some
semblance of artistic control over the development of the package,
while giving the users of the package the right to use and distribute
the Package in a more-or-less customary fashion, plus the right to make
reasonable modifications.</p>
<p>Definitions:</p>
<ul>
<li> "Package" refers to the collection of files distributed by the
Copyright Holder, and derivatives of that collection of files
created through textual modification.</li>
<li> "Standard Version" refers to such a Package if it has not been
modified, or has been modified in accordance with the wishes
of the Copyright Holder.</li>
<li> "Copyright Holder" is whoever is named in the copyright or
copyrights for the package.</li>
<li> "You" is you, if you're thinking about copying or distributing
this Package.</li>
<li> "Reasonable copying fee" is whatever you can justify on the
basis of media cost, duplication charges, time of people involved,
and so on. (You will not be required to justify it to the
Copyright Holder, but only to the computing community at large
as a market that must bear the fee.)</li>
<li> "Freely Available" means that no fee is charged for the item
itself, though there may be fees involved in handling the item.
It also means that recipients of the item may redistribute it
under the same conditions they received it.</li>
</ul>
<p>1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.</p>
<p>2. You may apply bug fixes, portability fixes and other modifications
derived from the Public Domain or from the Copyright Holder. A Package
modified in such a way shall still be considered the Standard Version.</p>
<p>3. You may otherwise modify your copy of this Package in any way, provided
that you insert a prominent notice in each changed file stating how and
when you changed that file, and provided that you do at least ONE of the
following:</p>
<blockquote>
<p>a) place your modifications in the Public Domain or otherwise make them
Freely Available, such as by posting said modifications to Usenet or
an equivalent medium, or placing the modifications on a major archive
site such as ftp.uu.net, or by allowing the Copyright Holder to include
your modifications in the Standard Version of the Package.</p>
<p>b) use the modified Package only within your corporation or organization.</p>
<p>c) rename any non-standard executables so the names do not conflict
with standard executables, which must also be provided, and provide
a separate manual page for each non-standard executable that clearly
documents how it differs from the Standard Version.</p>
<p>d) make other distribution arrangements with the Copyright Holder.</p>
</blockquote>
<p>4. You may distribute the programs of this Package in object code or
executable form, provided that you do at least ONE of the following:</p>
<blockquote>
<p>a) distribute a Standard Version of the executables and library files,
together with instructions (in the manual page or equivalent) on where
to get the Standard Version.</p>
<p>b) accompany the distribution with the machine-readable source of
the Package with your modifications.</p>
<p>c) accompany any non-standard executables with their corresponding
Standard Version executables, giving the non-standard executables
non-standard names, and clearly documenting the differences in manual
pages (or equivalent), together with instructions on where to get
the Standard Version.</p>
<p>d) make other distribution arrangements with the Copyright Holder.</p>
</blockquote>
<p>5. You may charge a reasonable copying fee for any distribution of this
Package. You may charge any fee you choose for support of this Package.
You may not charge a fee for this Package itself. However,
you may distribute this Package in aggregate with other (possibly
commercial) programs as part of a larger (possibly commercial) software
distribution provided that you do not advertise this Package as a
product of your own.</p>
<p>6. The scripts and library files supplied as input to or produced as
output from the programs of this Package do not automatically fall
under the copyright of this Package, but belong to whomever generated
them, and may be sold commercially, and may be aggregated with this
Package.</p>
<p>7. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.</p>
<p>8. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.</p>
<p>The End</p>
*/
/*
* This file is borrowed from Yaacfi open source project
* of Ze'ev Belkin http://zeevbelkin.com/yaacfi/
*
* */
package com.magnifis.parking;
import java.io.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import java.net.*;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashSet;
/**
* A class that provides utilizes to deal with XML-files
* @author Zeev Belkin
* @email koyaanisqatsi@narod.ru
* @www http://zeevbelkin.com
*/
public class Xml {
static private final String TAG="Xml";
/**
* loads an XML-document from an URL
* @return the loaded document, or <b>null</b> if any error
*/
public static org.w3c.dom.Document loadXmlFile(URL url) {
try {
InputStream is=url.openStream();
try {
return loadXmlFile(is);
} finally {
is.close();
}
} catch (Throwable t) {}
return null;
}
/**
* loads an XML-document from a file
* @return the loaded document, or <b>null</b> if any error
*/
public static org.w3c.dom.Document loadXmlFile(File src) {
try {
InputStream is=new FileInputStream(src);
try {
return loadXmlFile(is);
} finally {
is.close();
}
} catch (Throwable t) {}
return null;
}
/**
* loads an XML-document from a file
* @return the loaded document, or <b>null</b> if any error
*/
public static org.w3c.dom.Document loadXmlData(String data) {
return loadXmlFile(new ByteArrayInputStream(data.getBytes()));
}
/**
* loads an XML-document from a file
* @return the loaded document, or <b>null</b> if any error
*/
public static org.w3c.dom.Document loadXmlFile(InputStream is) {
org.w3c.dom.Document doc=null;
try {
DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
if (is!=null) try {
doc=builder.parse(is);
} finally {
is.close();
}
} catch (Throwable t) { t.printStackTrace(); }
return doc;
}
@Retention(value=RetentionPolicy.RUNTIME)
@Target(value=ElementType.FIELD)
public static @interface ML {
public String value() default "";
public String attr() default "";
public String tag() default "";
public String format() default "";
public boolean indirect() default false;
public boolean ifpresents() default true;
};
@Retention(value=RetentionPolicy.RUNTIME)
@Target(value=ElementType.FIELD)
public static @interface ML_alternatives {
public ML[] value();
}
static boolean isEmpty(String s) {
return (s==null)||s.length()==0;
}
private static volatile DateFormat simpleDateFormat=null;
@SuppressWarnings({ "rawtypes", "serial" })
private static HashSet<Class> simpleClass= new HashSet<Class>() {
{Class __simpleClass[]={
String.class,Integer.class,Long.class,java.util.Date.class ,
Double.class, Boolean.class,
boolean.class, int.class, long.class,
double.class
};
for (Class c:__simpleClass) this.add(c);
}
};
@SuppressWarnings("rawtypes")
public static boolean isSimpleClass(Class c) {
return simpleClass.contains(c);
}
public static <T> T setPropertiesFrom(
org.w3c.dom.Element node,
Class<T> cls
) {
T v=null;
try {
v=setPropertiesFrom(node,(T)cls.newInstance());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return v;
}
public static <T> T setPropertiesFrom(
org.w3c.dom.Element node,
T obj
) {
if (node==null) Log.d(TAG,"node==null");
boolean ok=true;
Class cls=obj.getClass();
ArrayList<Class> clss=new ArrayList<Class>(10);
do {
clss.add(cls);
cls=cls.getSuperclass();
} while (cls!=null);
for (Class cl:clss) for (Field fl:cl.getDeclaredFields()) {
fl.setAccessible(true);
ML anns[]=null;
if (fl.isAnnotationPresent(ML.class))
anns=new ML[] { fl.getAnnotation(ML.class) };
else if (fl.isAnnotationPresent(ML_alternatives.class))
anns=fl.getAnnotation(ML_alternatives.class).value();
if (anns!=null) {
Class flType=fl.getType();
for (ML an:anns) try {
String sVal=null;
boolean useAttr=an.attr().length()>0,indirect=an.indirect();
String anv=an.value();
String tag=useAttr?an.tag():(anv.length()==0?an.tag():anv);
if ("".equals(tag)) tag=null;
//Log.d(TAG,"@@ "+fl.getName()+" tag:"+tag+" node:"+node);
if (flType.isArray()) {
NodeList nl=node.getElementsByTagName(tag);
if (nl==null) {
if (useAttr&&an.value().length()>0) {
nl=node.getElementsByTagName(an.value());
}
if (nl==null) continue;
useAttr=false;
}
if (nl!=null){
int nll=nl.getLength();
if (!indirect) {
for (int i=0;i<nl.getLength();i++)
if (node!=nl.item(i).getParentNode()) nll--;
}
if (nll>0) {
Class cc=flType.getComponentType();
Object ar=java.lang.reflect.Array.newInstance(cc, nll);
for (int i=0,j=0;i<nl.getLength();i++) {
Node nli=nl.item(i);
if (indirect||(node==nli.getParentNode())) {
Object ob=null;
if (isSimpleClass(cc)) {
String txt=getInnerText(nli);
if (cc==String.class) {
ob=txt;
} else if (cc==Double.class||cc==double.class) {
ob=Double.parseDouble(txt);
} else if (cc==Integer.class||cc==int.class) {
ob=Integer.parseInt(txt);
}
} else {
ob=cc.newInstance();
setPropertiesFrom((org.w3c.dom.Element)nli,ob);
}
Array.set(ar, j++, ob);
}
}
fl.set(obj,ar);
}
//Log.d(TAG,"!XXX! "+Array.get(ar, 0));
}
//Log.d(TAG,"!! "+fl.getGenericType());
} else {
// Log.d(TAG,"@55@ "+fl.getName()+" tag:"+tag+" node:"+node);
org.w3c.dom.Element
el=(tag==null)?((org.w3c.dom.Element)node):getTag(node,tag,indirect);
if (el==null) {
// Log.d(TAG,"el==null "+domToText(node));
if (useAttr&&an.value().length()>0) {
el=getTag(node,an.value(),indirect);
}
if (el==null) continue;
useAttr=false;
}
if (useAttr) {
// Log.d(TAG,"useAttr ");
if (el.hasAttribute( an.attr()))
sVal=el.getAttribute(an.attr());
else
continue;
} else {
if (!simpleClass.contains(flType)) {
Object fo=flType.newInstance();
//if (fo!=null) {
// Log.d(TAG,"%%%% !simpleClass");
fl.set(obj,setPropertiesFrom(el,fo));
// Log.d(TAG,"%%%% is set "+fl.getName()+" "+fl.get(obj));
//}
continue;
}
CharSequence val=domToText(el,false, true);
if (val!=null) sVal= val.toString();//getInnerText(el);
}
if (sVal==null) {
//Log.d(TAG,an.tag());
if (an.ifpresents()&&(flType==Boolean.class||flType==boolean.class))
fl.set(obj, true);
continue;
}
// Log.i(TAG,"@sv@ "+sVal);
if (flType==String.class)
fl.set(obj,sVal);
else if (flType==Integer.class||flType==int.class) {
if (sVal.length()>0) fl.set(obj, new Integer(sVal));
}
else if (flType==Long.class||flType==long.class) {
if (sVal.length()>0) fl.set(obj, new Long(sVal));
}
else if (flType==Double.class||flType==double.class) {
if (sVal.length()>0) fl.set(obj, new Double(sVal));
} else if (flType==Boolean.class||flType==boolean.class) {
if (sVal.length()>0) fl.set(obj, new Boolean(sVal));
}
else
if (flType==java.util.Date.class) try {
if (simpleDateFormat==null) synchronized(Xml.class) {
if (simpleDateFormat==null) {
simpleDateFormat=new java.text.SimpleDateFormat("yyyy-MM-dd");
}
}
DateFormat df=isEmpty(an.format())?simpleDateFormat:new java.text.SimpleDateFormat(an.format());
fl.set(obj,df.parse(sVal));
} catch(Throwable t) {
t.printStackTrace();
}
}
} catch (Throwable ex) {
ok=false;
Log.e(TAG, ex.getMessage(),ex);
//ex.printStackTrace();
}
//setPropertyFrom(node,an.value(),fl.getName(),obj);
}
}
return ok?obj:null;
}
public static void setPropertyFrom(
org.w3c.dom.Node node,
String name,String propName,
Object obj
) {
String
val=getTagContent(node,name,false),
setterName="set"+Character.toUpperCase(propName.charAt(0))+propName.substring(1);
try {
obj.getClass().getMethod(setterName,String.class).invoke(obj,val);
} catch (Throwable ex) {
//Log.e(TAG, ex.getMessage(),ex);
//ex.printStackTrace();
}
}
public static CharSequence domToText(Element el) {
return domToText(el,true, false);
}
public static CharSequence domToText(Element el, boolean withEnvelope, boolean topLevel) {
StringBuilder sb=new StringBuilder();
if (withEnvelope) {
sb.append("\n<");
sb.append(el.getTagName());
NamedNodeMap attrs=el.getAttributes();
if (attrs!=null) for (int i=0;i<attrs.getLength();i++) {
Attr a=(Attr)attrs.item(i);
sb.append(' ');
sb.append(a.getName());
sb.append("=\"");
sb.append(TextUtils.htmlEncode(a.getValue()));
sb.append('"');
}
}
NodeList cn=el.getChildNodes();
if (cn!=null&&cn.getLength()>0) {
if (withEnvelope) sb.append('>');
///
for (int i=0;i<cn.getLength();i++) {
Node node=cn.item(i);
if (node instanceof Element) sb.append(domToText((Element)node)); else
switch (node.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
String t=node.getNodeValue();
sb.append(withEnvelope?TextUtils.htmlEncode(t):t);
}
}
///
if (withEnvelope) {
sb.append("</");
sb.append(el.getTagName());
sb.append('>');
}
} else {
if (withEnvelope) sb.append("/>"); else if (topLevel) return null;
}
return sb;
}
public static String getInnerText(Node node) {
if (node.getNodeType()==Node.TEXT_NODE) return node.getNodeValue();
NodeList nl=node.getChildNodes();
String s="";
if (nl!=null) for (int i=0;i<nl.getLength();i++) {
String ss=getInnerText(nl.item(i));
if (ss!=null) s+=ss;
}
return s==""?null:s;
}
public static org.w3c.dom.Element getTag(
org.w3c.dom.Node node,String name,
boolean idirect
) {
if (idirect&&(node instanceof org.w3c.dom.Element)) {
org.w3c.dom.Element top=(org.w3c.dom.Element)node;
org.w3c.dom.NodeList nl= top.getElementsByTagName(name);
if (nl!=null&&nl.getLength()>0) {
return (org.w3c.dom.Element)nl.item(0);
}
}
org.w3c.dom.NodeList nl=node.getChildNodes();
if (nl!=null) for (int i=0;i<nl.getLength();i++) {
org.w3c.dom.Node n=nl.item(i);
if (n instanceof org.w3c.dom.Element) {
org.w3c.dom.Element el=(org.w3c.dom.Element)n;
if (el.getTagName().equals(name)) return el;
}
}
return null;
}
public static String getTagContent(org.w3c.dom.Node node,String name, boolean indirect) {
org.w3c.dom.Node n=getTag(node,name,indirect);
if (n!=null) return getInnerText(n);
return null;
}
}
| true |
17a9c0a9389fda12d910704533fe10df9ca8349c | Java | Miklene/FrequencyGenerator | /app/src/main/java/com/miklene/frequencygenerator/sound_effect/SoundEffectDecorator.java | UTF-8 | 147 | 1.898438 | 2 | [] | no_license | package com.miklene.frequencygenerator.sound_effect;
public abstract class SoundEffectDecorator {
public SoundEffectDecorator() {
}
}
| true |
289633d72591026e6dc911fd49905799e14d3347 | Java | Bottle0oo0/juniorPractice | /src/main/java/com/hust/edu/controller/IndexController.java | UTF-8 | 740 | 2.234375 | 2 | [] | no_license | package com.hust.edu.controller;
import com.hust.edu.entity.User;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
@RestController
public class IndexController {
@RequestMapping("/index")
public @ResponseBody
String index(){
return "<h1>welcome hi!<h1>";
}
@RequestMapping("/home")
public ModelAndView getIndex(){
//实例化模型视图和对象
ModelAndView mv = new ModelAndView();
//放入数据 key-value模式
mv.addObject("title","welcom");
//指定显示视图
mv.setViewName("index");
return mv;
}
}
| true |
c80ca268bb176edca53144d80ef48232dd5f666f | Java | Kierian-50/BattleShip | /src/test/TestGame.java | UTF-8 | 5,332 | 3.203125 | 3 | [] | no_license | package test;
import battle.*;
import java.net.StandardSocketOptions;
import java.util.ArrayList;
/**
* This class test the class game.
*/
public class TestGame {
/**
* The entry point of the program.
* @param args The arguments.
*/
public static void main(String[] args){
//testGame();
//testDisplayFromTeacher();
//testDescription();
testAnalyseShot();
}
/**
* Test the constructor of the class Game.
*/
public static void testGame(){
System.out.println("Test the Game's class : \n");
System.out.println("Test a normal case with the creation of a Game's object : \nView no errors :\n");
Ship s1 = new Ship("Porte-avion",5);
Ship s2 = new Ship("Porte-avion",5);
ArrayList<Ship> aGoodFleet = new ArrayList<Ship>();
aGoodFleet.add(s1);
aGoodFleet.add(s2);
Game game1 = new Game(aGoodFleet, "playerName1","playerName2",
5,5, Mode.AA);
System.out.println("We see that there is no error : in a normal case, the creation of the object works\n" +
"Moreover, we see that the attributes have the right value : \n");
System.out.println("auto = "+game1.getAuto().toString());
System.out.println("current = "+game1.getCurrent().toString());
System.out.println("captain = "+game1.getCaptain().toString());
System.out.println("\nNow, we'll see what happen in error case : \n" +
"The test will be with a wrong argument in the declaration of the object\n");
Ship s4 = new Ship("Porte-avion",5);
Ship s3 = new Ship("Porte-avion",5);
ArrayList<Ship> aBadFleet = new ArrayList<Ship>();
aGoodFleet.add(s4);
aGoodFleet.add(s3);
System.out.println("View error : \n");
Game game2 = new Game(aBadFleet,"playerName1",null,-5,-5,Mode.HH);
System.out.println("\nWe see that in a error case, the program blocks the errors.\n");
System.out.println("End of the test.");
}
public static void testDisplayFromTeacher(){
System.out.println("-------------\nThis method allows to test the display of the grid");
Ship s1 = new Ship("fregate",3);
Ship s2 = new Ship("fregate",3);
Ship s3 = new Ship("patrouilleur",3);
Ship s4 = new Ship("porte-avion",3);
Ship s5 = new Ship("sous-marin",3);
ArrayList<Ship> aGoodFleet = new ArrayList<Ship>();
aGoodFleet.add(s1);
aGoodFleet.add(s2);
aGoodFleet.add(s3);
aGoodFleet.add(s5);
aGoodFleet.add(s4);
Game game1 = new Game(aGoodFleet,"Player1","Player2",10,10,Mode.HH);
game1.start();
System.out.println("\nEnd of the test");
}
public static void testDescription(){
Ship s1 = new Ship("fregate",3);
Ship s2 = new Ship("fregate",3);
Ship s3 = new Ship("patrouilleur",3);
Ship s4 = new Ship("porte-avion",3);
Ship s5 = new Ship("sous-marin",3);
ArrayList<Ship> aGoodFleet = new ArrayList<Ship>();
aGoodFleet.add(s1);
aGoodFleet.add(s2);
aGoodFleet.add(s3);
aGoodFleet.add(s5);
aGoodFleet.add(s4);
Game game1 = new Game(aGoodFleet,"Player1","Player2",10,10,Mode.HH);
System.out.println(game1.description());
}
public static void testAnalyseShot(){
Ship s1 = new Ship("fregate",3);
Ship s2 = new Ship("fregate",3);
Ship s3 = new Ship("patrouilleur",3);
Ship s4 = new Ship("porte-avion",3);
Ship s5 = new Ship("sous-marin",3);
ArrayList<Ship> aGoodFleet = new ArrayList<Ship>();
aGoodFleet.add(s1);
aGoodFleet.add(s2);
aGoodFleet.add(s3);
aGoodFleet.add(s5);
aGoodFleet.add(s4);
Game game1 = new Game(aGoodFleet,"Player1","Player2",10,10,Mode.HH);
System.out.println("\nVisualiser : hit :");
int[] tab = {0,0};
System.out.println(game1.analyzeShot(tab));
tab = new int[]{0, 2};
System.out.println(game1.analyzeShot(tab));
System.out.println("\nVisualiser : miss :");
tab = new int[]{1,1};
System.out.println(game1.analyzeShot(tab));
tab = new int[]{0,0};
System.out.println(game1.analyzeShot(tab));
System.out.println("\nVisualiser : sunk :");
tab = new int[]{0,1};
System.out.println(game1.analyzeShot(tab));
System.out.println("\nChange current :");
/*game1.changeCurrent();
System.out.println("\nVisualiser : hit :");
tab = new int[]{0,0};
System.out.println(game1.analyzeShot(tab));
tab = new int[]{0, 2};
System.out.println(game1.analyzeShot(tab));
System.out.println("\nVisualiser : miss :");
tab = new int[]{1,1};
System.out.println(game1.analyzeShot(tab));
tab = new int[]{0,0};
System.out.println(game1.analyzeShot(tab));
System.out.println("\nVisualiser : sunk :");
tab = new int[]{0,1};
System.out.println(game1.analyzeShot(tab));*/
}
}
| true |
2169159156970461de239672b0e241bf38235919 | Java | AquillaSLeite/meeting-room-java | /src/main/java/com/meeting/room/api/meetingroomapi/exception/BusinessException.java | UTF-8 | 361 | 2.046875 | 2 | [] | no_license | package com.meeting.room.api.meetingroomapi.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class BusinessException extends RuntimeException {
private String field;
private String error;
private Integer code;
private String exception;
}
| true |
0ffd808cbbbdfc2822058aa8ab57dbad7cdef443 | Java | github4n/spider-55ht | /spider-55haitao-crawler/src/main/java/com/haitao55/spider/crawler/core/callable/custom/mankind/CrawlerUtils.java | UTF-8 | 8,397 | 2.3125 | 2 | [] | no_license | package com.haitao55.spider.crawler.core.callable.custom.mankind;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import com.haitao55.spider.common.gson.bean.LImageList;
import com.haitao55.spider.common.gson.bean.Picture;
import com.haitao55.spider.common.utils.Currency;
import com.haitao55.spider.crawler.core.model.Image;
import com.haitao55.spider.crawler.exception.ParseException;
import com.haitao55.spider.crawler.exception.CrawlerException.CrawlerExceptionCode;
/**
* @Description:
* @author: zhoushuo
* @date: 2016年11月23日 下午2:23:57
*/
public class CrawlerUtils {
public static final String KEY_UNIT = "unit";
public static final String KEY_PRICE = "price";
public static final String KEY_GENDER = "s_gender";
public static final String MEN = "men";
public static final String WOMEN = "women";
public static final String STYLE_CATE_NAME = "COLOR";
// 设置标题:在页面利用css选择的
public static String setTitle(Document document, String css, String url, Logger logger){
Elements etitle = document.select(css);
if (CollectionUtils.isNotEmpty(etitle)) {
return etitle.get(0).text().trim();
} else {// 过滤掉没有Title的商品
logger.error("Error while fetching url {} because of no title.", url);
throw new ParseException(CrawlerExceptionCode.PARSE_ERROR,
"Error while fetching title with url " + url);
}
}
//设置标题:从源码中截取的
public static String setTitle(String title, String url, Logger logger){
if(StringUtils.isNotBlank(title))
return StringUtils.trim(title);
else {// 过滤掉没有Title的商品
logger.error("Error while fetching url {} because of no title.", url);
throw new ParseException(CrawlerExceptionCode.PARSE_ERROR,
"Error while fetching title with url " + url);
}
}
public static String setProductID(Document document, String css, String url, Logger logger){
Elements eproduct = document.select(css);
String productId = null;
if (CollectionUtils.isNotEmpty(eproduct))
productId = StringUtils.trim(eproduct.get(0).text());
if(StringUtils.isBlank(productId))
productId = UUID.randomUUID().toString();
return productId;
}
public static String getProductId(String currentUrl){
if (currentUrl.endsWith("/")) {
currentUrl = currentUrl.substring(0, currentUrl.length() - 1);
}
return currentUrl.substring(currentUrl.lastIndexOf("/") + 1);
}
/**
* @description 根据属性选择值
* @param document
* @param css
* @param attr
* @return return the match value. If not match,return empty.
*/
public static String getValueByAttr(Document document, String css, String attr){
Elements es = document.select(css);
String value = StringUtils.EMPTY;
if(CollectionUtils.isNotEmpty(es)){
if(StringUtils.isBlank(attr) || "text".equals(attr))
value = StringUtils.trim(es.get(0).text());
else
value = StringUtils.trim(es.get(0).attr(attr));
}
return value;
}
//设置面包屑和类别
public static void setBreadAndCategory(List<String> breads, List<String> categories, Document document, String css, String title){
Elements ebread = document.select(css);
for (Element e : ebread) {
breads.add(e.text());
categories.add(e.text());
}
breads.add(title);
categories.add(title);
}
//设置描述和feature
public static void setDescription(Map<String, Object> featureMap, Map<String, Object> descMap, Document document, String css_desc, String css_detail){
StringBuilder sb = new StringBuilder();
Elements eDescriptions = document.select(css_desc);
int count = 1;
if (CollectionUtils.isNotEmpty(eDescriptions)) {
for (Element e : eDescriptions) {
String decs = StringUtils.trim(e.text());
if(StringUtils.isNotBlank(decs)){
featureMap.put("feature-" + count, decs);
count++;
sb.append(decs).append(".");
}
}
}
Elements eDetails = document.select(css_detail);
if (CollectionUtils.isNotEmpty(eDetails)) {
for (Element e : eDetails) {
if (CollectionUtils.isNotEmpty(e.getElementsByAttributeValue("itemprop", "productID")))
continue;
featureMap.put("feature-" + count, e.text().trim());
count++;
sb.append(e.text().trim()).append(". ");
}
}
descMap.put("en", sb.toString());
}
// 获取价格
public static Map<String, Object> formatPrice(String tempPrice, String url, Logger logger) {
tempPrice = trimStringIgnoreNull(tempPrice);
if (tempPrice.contains("-")) {
tempPrice = trimStringIgnoreNull(StringUtils.substringBefore(tempPrice, "-"));
}
Map<String, Object> map = new HashMap<>();
if (StringUtils.isBlank(tempPrice)) {
logger.error("input price is null and url:{}", url);
throw new ParseException(CrawlerExceptionCode.PARSE_ERROR,
"Error while fetching price with url " + url);
}
String currency = StringUtils.substring(tempPrice, 0, 1);
Currency cuy = Currency.codeOf(currency);
if (cuy == null) {
logger.error("currency is null and url:{}", url);
throw new ParseException(CrawlerExceptionCode.PARSE_ERROR,
"Error while fetching price with url " + url);
}
map.put(KEY_UNIT, cuy.name());
tempPrice = StringUtils.substring(tempPrice, 1).replace(",", "");
try {
float price = Float.parseFloat(tempPrice);
price = formatNum(price);
map.put(KEY_PRICE, price);
} catch (NumberFormatException e) {
logger.error("format price error and url is {},because of {}", url, e.getMessage());
throw new ParseException(CrawlerExceptionCode.PARSE_ERROR,
"Error while fetching price with url " + url);
}
return map;
}
public static float formatNum(float num) {
return ((float) Math.round(num * 100)) / 100; // 四舍五入法保留两位小数
}
// 避免直接使用trim()方法发生空指针异常
public static String trimStringIgnoreNull(String string) {
if (string == null)
return StringUtils.EMPTY; // 这里不返回null的原因是,根据业务场景,不希望返回null
return string.trim();
}
public static List<Image> convertToImageList(List<String> list) {
List<Image> imgs = new ArrayList<Image>();
if (CollectionUtils.isNotEmpty(list)) {
for (String str : list) {
if (StringUtils.isNotBlank(str)) {
Image image = new Image(str);
imgs.add(image);
}
}
}
return imgs;
}
//设置性别
public static void setGender(Map<String, Object> properties, List<String> categories, String[] man_keywords, String[] woman_keywords){
if (CollectionUtils.isNotEmpty(categories)) {
gender: for (String cat : categories) {
for (String male_key : man_keywords) {
if (male_key.equals(cat.trim())) {
properties.put(KEY_GENDER, MEN);
break gender;
}
}
for (String female_key : woman_keywords) {
if (female_key.equals(cat.trim())) {
properties.put(KEY_GENDER, WOMEN);
break gender;
}
}
}
}
if (properties.get(KEY_GENDER) == null)
properties.put(KEY_GENDER, "");
}
//获取价格
public static float getPrice(String priceStr, String url, Logger logger){
return (float)formatPrice(priceStr, url, logger).get(KEY_PRICE);
}
//获取单位
public static String getUnit(String priceStr, String url, Logger logger){
return formatPrice(priceStr, url, logger).get(KEY_UNIT).toString();
}
//Elements转换成Document
public static Document parseToDocument(Elements es){
return Jsoup.parse(es.outerHtml());
}
public static LImageList getImageList(List<String> imgs){
List<Picture> l_image_list = new ArrayList<>();
if(CollectionUtils.isNotEmpty(imgs)){
for(String img : imgs){
Picture pic = new Picture(img, "");
l_image_list.add(pic);
}
}
LImageList image_list = new LImageList(l_image_list);
return image_list;
}
public static String getNumberFromString(String str) {
if (StringUtils.isBlank(str))
return str;
Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher(str);
if (matcher.find())
return matcher.group();
else
return null;
}
}
| true |
f519fc0fa917d0532640f182731b9ef9e250f795 | Java | JimmyInHub/Jimmy-Repo | /logfun/src/main/java/com/jimmy/logfun/utils/ResultInfo.java | UTF-8 | 1,439 | 2.71875 | 3 | [] | no_license | package com.jimmy.logfun.utils;
/**
* @description: 请求返回结果信息
* @fileName: ResultInfo.java
* @date: 2018/7/27 15:34
* @author: Jimmy
* @version: v1.0
*/
public class ResultInfo {
private static final String SUCCESS = "200";
private static final String ERROR = "500"; // 异常时返回错误
private static final String FAIL = "401";
// 返回结果,默认为true
private Boolean success;
// 返回信息
private String msg;
// 状态码,默认成功
private String statusCode;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public ResultInfo() {
this.success = true;
this.statusCode = SUCCESS;
}
/**
* @description 失败返回
* @param msg
* @date: 2018/7/27 15:29
* @author: Jimmy
*/
public void fail(String msg) {
this.success = false;
this.msg = msg;
this.statusCode = FAIL;
}
/**
* @description 错误返回
* @param msg
* @date: 2018/7/27 15:29
* @author: Jimmy
*/
public void error(String msg) {
this.success = false;
this.msg = msg;
this.statusCode = ERROR;
}
}
| true |
aa59ddca198f8460a56e2a51c55488edc347fc3a | Java | roymyboy/cs121 | /lab5/Mood.java | UTF-8 | 811 | 3.421875 | 3 | [] | no_license | public class Mood
{
enum mood { happy, bored, excited, snarky, zombie, grumpy, calm}
public static void main(String[] args) {
mood Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
Sunday = mood.happy;
Monday = mood.bored;
Tuesday = mood.excited;
Wednesday = mood.snarky;
Thursday = mood.zombie;
Friday = mood.grumpy;
Saturday = mood.calm;
System.out.println("On Sunday, I am " + Sunday + "." );
System.out.println("On Monday, I am " + Monday + ".");
System.out.println("On Tuesday, I am " +Tuesday + "." );
System.out.println("On Wednesday, I am " + Wednesday + "." );
System.out.println("On Thursday, I am " + Thursday + "." );
System.out.println("On Friday, I am " + Friday + ".");
System.out.println("On Saturday, I am " + Saturday + "." );
}
} | true |
eeb8c3290295ff93cc9efa3b1a18c462bb63fc02 | Java | ppapzzhCSDN/day17 | /src/com/day8/test/Start.java | UTF-8 | 329 | 2.828125 | 3 | [] | no_license | package com.day8.test;
public class Start {
private Task task; //定义一个Start启动类,内部包含一个任务Task
public void Start(Task task){
this.task=task;
}
public void eat(){
System.out.println("今天又跑步吗??");
//执行task文件
task.task();
}
}
| true |
128c674ecd58e6ed2755e81218f8ead1d300dff5 | Java | tipplerow/jene | /src/test/java/jene/ensembl/EnsemblProteinDbTest.java | UTF-8 | 1,764 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive |
package jene.ensembl;
import jene.hugo.HugoSymbol;
import org.junit.*;
import static org.junit.Assert.*;
public class EnsemblProteinDbTest {
@Test public void testSample2() {
EnsemblProteinDb db = EnsemblProteinDb.load("data/test/ensembl_test2.fa");
HugoSymbol BRAF_Hugo = HugoSymbol.instance("BRAF");
HugoSymbol KRAS_Hugo = HugoSymbol.instance("KRAS");
EnsemblGeneID BRAF_Gene = EnsemblGeneID.instance("ENSG00000157764");
EnsemblGeneID KRAS_Gene = EnsemblGeneID.instance("ENSG00000133703");
EnsemblTranscriptID BRAF_Trans1 = EnsemblTranscriptID.instance("ENST00000496384");
EnsemblTranscriptID BRAF_Trans2 = EnsemblTranscriptID.instance("ENST00000644969");
EnsemblTranscriptID BRAF_Trans3 = EnsemblTranscriptID.instance("ENST00000646891");
EnsemblTranscriptID KRAS_Trans1 = EnsemblTranscriptID.instance("ENST00000311936");
EnsemblTranscriptID KRAS_Trans2 = EnsemblTranscriptID.instance("ENST00000256078");
assertEquals(5, db.size());
assertEquals(2, db.count(KRAS_Hugo));
assertEquals(3, db.count(BRAF_Hugo));
assertEquals(2, db.count(KRAS_Gene));
assertEquals(3, db.count(BRAF_Gene));
assertEquals(BRAF_Hugo, db.getHugo(BRAF_Gene));
assertEquals(KRAS_Hugo, db.getHugo(KRAS_Gene));
assertEquals(BRAF_Hugo, db.getHugo(BRAF_Trans1));
assertEquals(BRAF_Hugo, db.getHugo(BRAF_Trans2));
assertEquals(BRAF_Hugo, db.getHugo(BRAF_Trans3));
assertEquals(KRAS_Hugo, db.getHugo(KRAS_Trans1));
assertEquals(KRAS_Hugo, db.getHugo(KRAS_Trans2));
}
public static void main(String[] args) {
org.junit.runner.JUnitCore.main("jene.ensembl.EnsemblProteinDbTest");
}
}
| true |
b2af07383d27fdafc2140aa67d08cb96c62337b6 | Java | as425017946/UHF_AS | /app/src/main/java/com/speedata/uhf/adapter/MessagesAdapter.java | UTF-8 | 2,877 | 2.375 | 2 | [] | no_license | package com.speedata.uhf.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.speedata.uhf.R;
import com.speedata.uhf.bean.MessagesBean;
import java.util.ArrayList;
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.ViewHolder> {
Context context;
ArrayList<MessagesBean> arrayList;
public MessagesAdapter(Context context,ArrayList<MessagesBean> arrayList){
this.context = context;
this.arrayList = arrayList;
}
/**
* 箱单与getview方法中的创建view和viewholder
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(context,R.layout.messages_items,null);
return new ViewHolder(view);
}
/**
* 相当于getview绑定数据部分
* @param holder
* @param position
*/
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
MessagesBean messagesBean = arrayList.get(position);
holder.tv_type.setText(messagesBean.getData().getPageInfo().getList().get(position).getCONSERVATION_NAME());
holder.tv_startime.setText(messagesBean.getData().getPageInfo().getList().get(position).getSTART_TIME());
holder.tv_endtime.setText(messagesBean.getData().getPageInfo().getList().get(position).getEND_TIME());
holder.tv_beizhu.setText(messagesBean.getData().getPageInfo().getList().get(position).getNOTES());
holder.tv_zhixingzu.setText(messagesBean.getData().getPageInfo().getList().get(position).getGROUP_NAME());
holder.tv_zhixingduixiang.setText(messagesBean.getData().getPageInfo().getList().get(position).getTENDERS());
}
/**
* 得到总条数
* @return
*/
@Override
public int getItemCount() {
return arrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_type;
TextView tv_startime;
TextView tv_endtime;
TextView tv_beizhu;
TextView tv_zhixingzu;
TextView tv_zhixingduixiang;
public ViewHolder(View itemView) {
super(itemView);
tv_type = (TextView) itemView.findViewById(R.id.messages_type);
tv_startime = (TextView) itemView.findViewById(R.id.messages_startime);
tv_endtime = (TextView) itemView.findViewById(R.id.messages_endtime);
tv_beizhu = (TextView) itemView.findViewById(R.id.messages_beizhu);
tv_zhixingzu = (TextView) itemView.findViewById(R.id.messages_zhixingzu);
tv_zhixingduixiang = (TextView) itemView.findViewById(R.id.messages_zhixingduixing);
}
}
}
| true |
60af8370b791343df36d08fc246496f092579c5c | Java | chaosbastler/apps-android-commons | /commons/src/main/java/org/wikimedia/commons/MediaDataExtractor.java | UTF-8 | 11,884 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package org.wikimedia.commons;
import android.util.Log;
import org.mediawiki.api.ApiResult;
import org.mediawiki.api.MWApi;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Fetch additional media data from the network that we don't store locally.
*
* This includes things like category lists and multilingual descriptions,
* which are not intrinsic to the media and may change due to editing.
*/
public class MediaDataExtractor {
private boolean fetched;
private boolean processed;
private String filename;
private ArrayList<String> categories;
private Map<String, String> descriptions;
private String author;
private Date date;
private String license;
private LicenseList licenseList;
/**
* @param filename of the target media object, should include 'File:' prefix
*/
public MediaDataExtractor(String filename, LicenseList licenseList) {
this.filename = filename;
categories = new ArrayList<String>();
descriptions = new HashMap<String, String>();
fetched = false;
processed = false;
this.licenseList = licenseList;
}
/**
* Actually fetch the data over the network.
* todo: use local caching?
*
* Warning: synchronous i/o, call on a background thread
*/
public void fetch() throws IOException {
if (fetched) {
throw new IllegalStateException("Tried to call MediaDataExtractor.fetch() again.");
}
MWApi api = CommonsApplication.createMWApi();
ApiResult result = api.action("query")
.param("prop", "revisions")
.param("titles", filename)
.param("rvprop", "content")
.param("rvlimit", 1)
.param("rvgeneratexml", 1)
.get();
processResult(result);
fetched = true;
}
private void processResult(ApiResult result) throws IOException {
String wikiSource = result.getString("/api/query/pages/page/revisions/rev");
String parseTreeXmlSource = result.getString("/api/query/pages/page/revisions/rev/@parsetree");
// In-page category links are extracted from source, as XML doesn't cover [[links]]
extractCategories(wikiSource);
// Description template info is extracted from preprocessor XML
processWikiParseTree(parseTreeXmlSource);
}
/**
* We could fetch all category links from API, but we actually only want the ones
* directly in the page source so they're editable. In the future this may change.
*
* @param source wikitext source code
*/
private void extractCategories(String source) {
Pattern regex = Pattern.compile("\\[\\[\\s*Category\\s*:([^]]*)\\s*\\]\\]", Pattern.CASE_INSENSITIVE);
Matcher matcher = regex.matcher(source);
while (matcher.find()) {
String cat = matcher.group(1).trim();
categories.add(cat);
}
}
private void processWikiParseTree(String source) throws IOException {
Document doc;
try {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = docBuilder.parse(new ByteArrayInputStream(source.getBytes("UTF-8")));
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (IllegalStateException e) {
throw new IOException(e);
} catch (SAXException e) {
throw new IOException(e);
}
Node templateNode = findTemplate(doc.getDocumentElement(), "information");
if (templateNode != null) {
Node descriptionNode = findTemplateParameter(templateNode, "description");
descriptions = getMultilingualText(descriptionNode);
Node authorNode = findTemplateParameter(templateNode, "author");
author = getFlatText(authorNode);
}
/*
Pull up the license data list...
look for the templates in two ways:
* look for 'self' template and check its first parameter
* if none, look for any of the known templates
*/
Log.d("Commons", "MediaDataExtractor searching for license");
Node selfLicenseNode = findTemplate(doc.getDocumentElement(), "self");
if (selfLicenseNode != null) {
Node firstNode = findTemplateParameter(selfLicenseNode, 1);
String licenseTemplate = getFlatText(firstNode);
License license = licenseList.licenseForTemplate(licenseTemplate);
if (license == null) {
Log.d("Commons", "MediaDataExtractor found no matching license for self parameter: " + licenseTemplate + "; faking it");
this.license = licenseTemplate; // hack hack! For non-selectable licenses that are still in the system.
} else {
// fixme: record the self-ness in here too... sigh
// all this needs better server-side metadata
this.license = license.getKey();
Log.d("Commons", "MediaDataExtractor found self-license " + this.license);
}
} else {
for (License license : licenseList.values()) {
String templateName = license.getTemplate();
Node template = findTemplate(doc.getDocumentElement(), templateName);
if (template != null) {
// Found!
this.license = license.getKey();
Log.d("Commons", "MediaDataExtractor found non-self license " + this.license);
break;
}
}
}
}
private Node findTemplate(Element parentNode, String title) throws IOException {
String ucTitle= Utils.capitalize(title);
NodeList nodes = parentNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeName().equals("template")) {
String foundTitle = getTemplateTitle(node);
if (Utils.capitalize(foundTitle).equals(ucTitle)) {
return node;
}
}
}
return null;
}
private String getTemplateTitle(Node templateNode) throws IOException {
NodeList nodes = templateNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeName().equals("title")) {
return node.getTextContent().trim();
}
}
throw new IOException("Template has no title element.");
}
private static abstract class TemplateChildNodeComparator {
abstract public boolean match(Node node);
}
private Node findTemplateParameter(Node templateNode, String name) throws IOException {
final String theName = name;
return findTemplateParameter(templateNode, new TemplateChildNodeComparator() {
@Override
public boolean match(Node node) {
return (Utils.capitalize(node.getTextContent().trim()).equals(Utils.capitalize(theName)));
}
});
}
private Node findTemplateParameter(Node templateNode, int index) throws IOException {
final String theIndex = "" + index;
return findTemplateParameter(templateNode, new TemplateChildNodeComparator() {
@Override
public boolean match(Node node) {
Element el = (Element)node;
if (el.getTextContent().trim().equals(theIndex)) {
return true;
} else if (el.getAttribute("index") != null && el.getAttribute("index").trim().equals(theIndex)) {
return true;
} else {
return false;
}
}
});
}
private Node findTemplateParameter(Node templateNode, TemplateChildNodeComparator comparator) throws IOException {
NodeList nodes = templateNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeName().equals("part")) {
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node childNode = childNodes.item(j);
if (childNode.getNodeName().equals("name")) {
if (comparator.match(childNode)) {
// yay! Now fetch the value node.
for (int k = j + 1; k < childNodes.getLength(); k++) {
Node siblingNode = childNodes.item(k);
if (siblingNode.getNodeName().equals("value")) {
return siblingNode;
}
}
throw new IOException("No value node found for matched template parameter.");
}
}
}
}
}
throw new IOException("No matching template parameter node found.");
}
private String getFlatText(Node parentNode) throws IOException {
return parentNode.getTextContent();
}
// Extract a dictionary of multilingual texts from a subset of the parse tree.
// Texts are wrapped in things like {{en|foo} or {{en|1=foo bar}}.
// Text outside those wrappers is stuffed into a 'default' faux language key if present.
private Map<String, String> getMultilingualText(Node parentNode) throws IOException {
Map<String, String> texts = new HashMap<String, String>();
StringBuilder localText = new StringBuilder();
NodeList nodes = parentNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeName().equals("template")) {
// process a template node
String title = getTemplateTitle(node);
if (title.length() < 3) {
// Hopefully a language code. Nasty hack!
String lang = title;
Node valueNode = findTemplateParameter(node, 1);
String value = valueNode.getTextContent(); // hope there's no subtemplates or formatting for now
texts.put(lang, value);
}
} else if (node.getNodeType() == Node.TEXT_NODE) {
localText.append(node.getTextContent());
}
}
// Some descriptions don't list multilingual variants
String defaultText = localText.toString().trim();
if (defaultText.length() > 0) {
texts.put("default", localText.toString());
}
return texts;
}
/**
* Take our metadata and inject it into a live Media object.
* Media object might contain stale or cached data, or emptiness.
* @param media
*/
public void fill(Media media) {
if (!fetched) {
throw new IllegalStateException("Tried to call MediaDataExtractor.fill() before fetch().");
}
media.setCategories(categories);
media.setDescriptions(descriptions);
if (license != null) {
media.setLicense(license);
}
// add author, date, etc fields
}
}
| true |
7df035f524c6d4c2949ebba9406fb6ed9a824a10 | Java | VladislavKrets/TestVkApplication | /src/main/java/com/vkfriends/task/Controller.java | UTF-8 | 4,911 | 2.015625 | 2 | [] | no_license | package com.vkfriends.task;
import com.vk.api.sdk.client.TransportClient;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.exceptions.ApiException;
import com.vk.api.sdk.exceptions.ClientException;
import com.vk.api.sdk.httpclient.HttpTransportClient;
import com.vk.api.sdk.objects.UserAuthResponse;
import com.vk.api.sdk.objects.account.UserSettings;
import com.vk.api.sdk.objects.users.UserFull;
import com.vk.api.sdk.objects.users.UserXtrCounters;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;
@org.springframework.stereotype.Controller
public class Controller {
private final static int APP_ID = 5811050;
private final static String CLIENT_SECRET = "knSc6wK92p9T0wYN3Uzs";
private final static String REDIRECT_URI = "http://185.247.117.223:8080";
private final static String BASE_URL = "https://oauth.vk.com/authorize?" +
"client_id=5811050" +
"&display=page" +
"&redirect_uri=" + REDIRECT_URI + "/vkauth" +
"&scope=friends,status,offline" +
"&response_type=code" +
"&v=5.103";
private String token;
private TransportClient transportClient;
private VkApiClient vk;
private int id;
@GetMapping("/")
public String authenticate(@CookieValue(value = "token", defaultValue = "") String token,
@CookieValue(value = "id", defaultValue = "") String id) {
if (!token.isEmpty()) {
this.token = token;
this.id = Integer.parseInt(id);
return "redirect:/friends";
}
return "auth";
}
@PostMapping("/")
public RedirectView postAuthenticate() {
return new RedirectView(BASE_URL);
}
@GetMapping("/friends")
public String friends(Model model) {
if (token == null) return "redirect:/";
if (transportClient == null || vk == null) {
transportClient = HttpTransportClient.getInstance();
vk = new VkApiClient(transportClient);
}
UserActor actor = new UserActor(id, token);
try {
UserXtrCounters userXtrCountersProfile = vk.users().get(actor).userIds(String.valueOf(id)).execute().get(0);
StringBuilder name = new StringBuilder();
name.append(userXtrCountersProfile.getFirstName()).append(" ").append(userXtrCountersProfile.getLastName());
model.addAttribute("profile_name", name.toString());
name = new StringBuilder();
List<String> list = vk.friends().get(actor).count(5).count(5).execute().getItems()
.stream().map(String::valueOf).collect(Collectors.toList());
List<UserXtrCounters> userXtrCountersList = vk.users().get(actor).userIds(list).execute();
for (UserXtrCounters userXtrCounters : userXtrCountersList) {
name.append("<br>").append(userXtrCounters.getFirstName()).append(" ").append(userXtrCounters.getLastName());
}
model.addAttribute("name", name.toString());
} catch (ApiException | ClientException e) {
e.printStackTrace();
}
return "friends";
}
@GetMapping("/vkauth")
public String vkAuth(@RequestParam String code, HttpServletResponse response) {
transportClient = HttpTransportClient.getInstance();
vk = new VkApiClient(transportClient);
try {
UserAuthResponse authResponse = vk.oAuth()
.userAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI + "/vkauth", code)
.execute();
token = authResponse.getAccessToken();
Cookie cookie = new Cookie("token", token);
response.addCookie(cookie);
id = authResponse.getUserId();
cookie = new Cookie("id", String.valueOf(id));
response.addCookie(cookie);
} catch (ApiException | ClientException e) {
e.printStackTrace();
}
return "redirect:/friends";
}
@PostMapping("/friends")
public String exit(HttpServletResponse response){
Cookie cookie = new Cookie("token", "");
response.addCookie(cookie);
cookie = new Cookie("id", "");
response.addCookie(cookie);
token = null;
id = 0;
return "redirect:/";
}
}
| true |
3f056f7270f57932a9bc8bbd72cef011a9878e37 | Java | IOIIIO/DisneyPlusSource | /sources/com/google/android/gms/measurement/internal/C10079i5.java | UTF-8 | 1,124 | 1.65625 | 2 | [] | no_license | package com.google.android.gms.measurement.internal;
/* renamed from: com.google.android.gms.measurement.internal.i5 */
final class C10079i5 implements Runnable {
/* renamed from: U */
private final /* synthetic */ String f23544U;
/* renamed from: V */
private final /* synthetic */ String f23545V;
/* renamed from: W */
private final /* synthetic */ long f23546W;
/* renamed from: X */
private final /* synthetic */ C10156p4 f23547X;
/* renamed from: c */
private final /* synthetic */ String f23548c;
C10079i5(C10156p4 p4Var, String str, String str2, String str3, long j) {
this.f23547X = p4Var;
this.f23548c = str;
this.f23544U = str2;
this.f23545V = str3;
this.f23546W = j;
}
public final void run() {
String str = this.f23548c;
if (str == null) {
this.f23547X.f23848a.mo25945r().mo26017B().mo26170a(this.f23544U, (C10229w6) null);
return;
}
this.f23547X.f23848a.mo25945r().mo26017B().mo26170a(this.f23544U, new C10229w6(this.f23545V, str, this.f23546W));
}
}
| true |
b8c24484d35b8e10a21f191e4c50e52463c0bb11 | Java | weixiding/spring-security | /imooc-security-core/src/main/java/com/imooc/security/core/validate/code/ValidateCodeGenerator.java | UTF-8 | 646 | 1.890625 | 2 | [] | no_license | /**
* Copyright (C), 2015-2019, XXX有限公司
* FileName: ValidateCodeGenerator
* Author: Administrator
* Date: 2019/11/21 11:05
* Description:
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.imooc.security.core.validate.code;
import org.springframework.web.context.request.ServletWebRequest;
/**
* 〈一句话功能简述〉<br>
* 〈〉
*
* @author Administrator
* @create 2019/11/21
* @since 1.0.0
*/
public interface ValidateCodeGenerator<C> {
public C generate(ServletWebRequest request);
}
| true |
e68e888a8c1de8e00fe73b9a9ae344c6eebc89c8 | Java | maitienlong/Lab3_Longmt | /app/src/main/java/com/example/lab3_longmt/MainActivity.java | UTF-8 | 1,556 | 1.976563 | 2 | [] | no_license | package com.example.lab3_longmt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.lab3_longmt.loader.GetLoader;
import com.example.lab3_longmt.model.Item;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private List<Item> myDataset;
private TextView textView;
private RecyclerView rvList;
private EditText edtSearch;
private ImageView btnSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
rvList = findViewById(R.id.rvList);
edtSearch = findViewById(R.id.edtSearch);
btnSearch = findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String search = edtSearch.getText().toString().trim();
if (search.isEmpty()) {
edtSearch.setError("Chưa có từ khóa để tìm kiếm !");
} else {
String link = "http://dotplays.com/wp-json/wp/v2/search?search=" + edtSearch.getText().toString().trim() + "&_embed";
GetLoader getLoader = new GetLoader(rvList, MainActivity.this);
getLoader.execute(link);
}
}
} | true |
7e9a892fe043f93085535b73d90780f74a7b6565 | Java | kakayuw/Java-Metod-Extractor | /src/main/java/fileUtil/FileIO.java | UTF-8 | 1,132 | 3.375 | 3 | [] | no_license | package fileUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileIO {
/**
* Get filename list in one directory
* @param dirPath
* @return
*/
public static List<String> getFilenameList(String dirPath) {
// scan target directory and get file list
File[] allFiles = new File(dirPath).listFiles();
List<String> filenameList = new ArrayList<String>();
for (int i = 0; i < allFiles.length; i++) {
File file = allFiles[i];
if (file.isFile()) filenameList.add(file.getName());
}
return filenameList;
}
/**
* Get ONLY Java filename list in one directory
* @param dirPath
* @return
*/
public static List<String> getJavaFilenameList(String dirPath) {
List<String> allfiles = getFilenameList(dirPath);
List<String> allJava = new ArrayList<String >();
for (String name : allfiles) {
if (name.substring(name.length() - 5).equals(".java")) {
allJava.add(name);
}
}
return allJava;
}
}
| true |
4990e143605e664c83c1181b88ea74837b4a5f50 | Java | 2393937618/springboot | /src/main/java/com/example/demo/dao/paperRepository.java | UTF-8 | 643 | 1.921875 | 2 | [] | no_license | package com.example.demo.dao;
import com.example.demo.entity.paper;
import com.example.demo.entity.result;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface paperRepository extends JpaRepository<paper,Integer> {
@Query(value = "select count(*) from paper where tid=?1",nativeQuery = true)
int paper_count (int tid);
@Query(value = "select * from paper where tid=?1",nativeQuery = true)
List<paper> show_paper (int tid);
@Query(value = "select count(*) from paper",nativeQuery = true)
int paper_count2 ();
}
| true |
b966ee120785efe7473c5429f04af5140b0e9c2c | Java | arkiner/test | /src/postOffice/login/LoginController.java | UTF-8 | 1,188 | 2.296875 | 2 | [] | no_license | package postOffice.login;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/login")
public class LoginController {
@Autowired
private LoginService loginServiceImp;
@RequestMapping("/login")
@ResponseBody
public Map<String, Object> login(@RequestBody String userName,@RequestBody String password,HttpServletRequest request){
Map<String, Object> user = (Map<String, Object>) this.loginServiceImp.login(userName, password);
if(user != null){
user.put("success", "1");
request.getSession().setAttribute("userName", userName);
request.getSession().setAttribute("branchName", user.get("branchName").toString());
request.getSession().setAttribute("branchId", user.get("branchId").toString());
}else{
user = new HashMap<String, Object>();
user.put("success", "0");
}
return user;
}
}
| true |
9363448e80c1fb426f2d1d882251ccde807937a7 | Java | ozygod/leetcode-demo | /src/com/ozygod/elementary/string/Palindrome.java | UTF-8 | 1,452 | 3.859375 | 4 | [] | no_license | package com.ozygod.elementary.string;
import java.util.Locale;
/**
* 验证回文串
*
* 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
*
* 说明:本题中,我们将空字符串定义为有效的回文串。
*
* 示例 1:
* 输入: "A man, a plan, a canal: Panama"
* 输出: true
*
* 示例 2:
* 输入: "race a car"
* 输出: false
*
* 作者:力扣 (LeetCode)
* 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xne8id/
* 来源:力扣(LeetCode)
* 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
public class Palindrome {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
int start = 0, end = s.length()-1;
while (start < end) {
if (!Character.isLetterOrDigit(s.charAt(start))) {
start++;
continue;
}
if (!Character.isLetterOrDigit(s.charAt(end))) {
end--;
continue;
}
if (s.charAt(start++) != s.charAt(end--)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String s = "A man, a plan, a canal: Panama";
Palindrome demo = new Palindrome();
System.out.println(demo.isPalindrome(s));
}
}
| true |
fbb5b79c299f63034f10b014ca7e5d9b7de0122a | Java | jcerbito/BattleOfHogwarts | /gradle/core/src/com/jcerbito/battleofhogwarts/screens/ChooseCharacterDiff.java | UTF-8 | 6,942 | 2.09375 | 2 | [] | no_license | package com.jcerbito.battleofhogwarts.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.jcerbito.battleofhogwarts.BattleOfHogwarts;
import com.jcerbito.battleofhogwarts.forgameproper.GameUpgradeAverage;
import com.jcerbito.battleofhogwarts.forgameproper.GameUpgradeDiff;
import com.jcerbito.battleofhogwarts.forgameproper.GameUpgradeEasy;
/**
* Created by HP on 30/01/2018.
*/
public class ChooseCharacterDiff extends DefaultScreen {
Stage uiStage;
private Texture texture;
private TextureRegion textureRegion;
private TextureRegionDrawable texRegionDrawable;
private ImageButton charButton;
private Texture bgTexture;
private Texture textureTwo;
private TextureRegion textureRegionTwo;
private TextureRegionDrawable texRegionDrawableTwo;
private ImageButton charButtonTwo;
private Texture textureThree;
private TextureRegion textureRegionThree;
private TextureRegionDrawable texRegionDrawableThree;
private ImageButton charButtonThree;
private Texture textureFour;
private TextureRegion textureRegionFour;
private TextureRegionDrawable texRegionDrawableFour;
private ImageButton charButtonFour;
public static int charLockDiff = 0;
void startUI(){
bgTexture = new Texture(Gdx.files.internal("charbg.jpg"));
Image bckgrnd = new Image(bgTexture);
texture = new Texture(Gdx.files.internal("bigharry.png"));
textureRegion = new TextureRegion(texture);
texRegionDrawable = new TextureRegionDrawable(textureRegion);
charButton = new ImageButton(texRegionDrawable);
charButton.addListener(new ClickListener(){
public void touchUp(InputEvent event, float x, float y, int pointer, int button){
charLockDiff = 1;
dispose();
game.setScreen(new GameScreenDiff(game));
}
});
textureTwo = new Texture(Gdx.files.internal("bighermione.png"));
textureRegionTwo = new TextureRegion(textureTwo);
texRegionDrawableTwo = new TextureRegionDrawable(textureRegionTwo);
charButtonTwo = new ImageButton(texRegionDrawableTwo);
if ((GameUpgradeEasy.ulock + GameUpgradeAverage.ulock) >= 30){
charButtonTwo.addListener(new ClickListener(){
public void touchUp(InputEvent event, float x, float y, int pointer, int button){
dispose();
charLockDiff = 2;
game.setScreen(new GameScreenDiff(game));
}
});
}
textureThree = new Texture(Gdx.files.internal("bighagrid.png"));
textureRegionThree = new TextureRegion(textureThree);
texRegionDrawableThree = new TextureRegionDrawable(textureRegionThree);
charButtonThree = new ImageButton(texRegionDrawableThree);
if ((GameUpgradeEasy.ulock + GameUpgradeAverage.ulock) >= 50 ){
charButtonThree.addListener(new ClickListener(){
public void touchUp(InputEvent event, float x, float y, int pointer, int button){
dispose();
charLockDiff = 3;
game.setScreen(new GameScreenDiff(game));
}
});
}
textureFour = new Texture(Gdx.files.internal("bigron.png"));
textureRegionFour = new TextureRegion(textureFour);
texRegionDrawableFour = new TextureRegionDrawable(textureRegionFour);
charButtonFour = new ImageButton(texRegionDrawableFour);
if ((GameUpgradeEasy.ulock + GameUpgradeAverage.ulock + GameUpgradeDiff.ulock) >= 30 ){
charButtonFour.addListener(new ClickListener(){
public void touchUp(InputEvent event, float x, float y, int pointer, int button){
dispose();
charLockDiff = 4;
game.setScreen(new GameScreenDiff(game));
}
});
}
TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle();
buttonStyle.font = game.res.gamefont;
TextButton aBtn = new TextButton("COLLECT MORE POTIONS", buttonStyle);
TextButton qBtn = new TextButton("TO UNLOCK RON!", buttonStyle);
TextButton hBtn = new TextButton("CLICK ON CHOSEN CHARACTER", buttonStyle);
hBtn.setPosition((uiStage.getWidth() - hBtn.getWidth()) / 2, 220) ;
TextButton ex = new TextButton("CLICK HERE TO GO BACK", buttonStyle);
ex.setPosition((uiStage.getWidth() - ex.getWidth()) / 2, 5);
ex.addListener(new ClickListener(){
public void touchUp(InputEvent event, float x, float y, int pointer, int button){
dispose();
game.setScreen(new StartScreen(game));
}
});
charButton.setPosition((uiStage.getWidth() / 3 - 80 ), uiStage.getHeight() / 2);
charButtonTwo.setPosition((uiStage.getWidth() / 3 + 40), uiStage.getHeight() / 2);
charButtonThree.setPosition((uiStage.getWidth() / 3 - 20), uiStage.getHeight() / 4);
charButtonFour.setPosition((uiStage.getWidth() / 2 + 50), uiStage.getHeight() / 4);
uiStage.addActor(bckgrnd);
uiStage.addActor(charButton);
uiStage.addActor(charButtonTwo);
uiStage.addActor(charButtonThree);
uiStage.addActor(charButtonFour);
uiStage.addActor(ex);
uiStage.addActor(hBtn);
if ((GameUpgradeEasy.ulock + GameUpgradeAverage.ulock + GameUpgradeDiff.ulock) <= 29){
aBtn.setPosition((uiStage.getWidth() - aBtn.getWidth()) / 2, 45 );
qBtn.setPosition((uiStage.getWidth() - qBtn.getWidth()) / 2, 33) ;
uiStage.addActor(aBtn);
uiStage.addActor(qBtn);
}
}
public ChooseCharacterDiff(BattleOfHogwarts g){
super(g);
FitViewport viewport = new FitViewport(340,250); //160,120
uiStage = new Stage(viewport);
Gdx.input.setInputProcessor(uiStage);
startUI();
}
@Override
public void render(float delta){
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
uiStage.act(delta);
uiStage.draw();
}
@Override
public void dispose(){
Gdx.input.setInputProcessor(null);
uiStage.dispose();
super.dispose();
}
}
| true |
cf480b213e9c175fa717d9468d9a36032495789e | Java | berty/ble-prototype-v2 | /app/src/main/java/com/example/ble/PeerDevice.java | UTF-8 | 12,551 | 1.867188 | 2 | [] | no_license | package com.example.ble;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import java.util.List;
public class PeerDevice {
private static final String TAG = "PeerDevice";
// Max MTU requested
// See https://chromium.googlesource.com/aosp/platform/system/bt/+/29e794418452c8b35c2d42fe0cda81acd86bbf43/stack/include/gatt_api.h#123
private static final int REQUEST_MTU = 517;
public enum CONNECTION_STATE {
DISCONNECTED,
CONNECTED,
CONNECTING,
DISCONNECTING
}
private CONNECTION_STATE mState = CONNECTION_STATE.DISCONNECTED;
private Context mContext;
private BluetoothDevice mBluetoothDevice;
private BluetoothGatt mBluetoothGatt;
private Thread mThread;
private final Object mLockState = new Object();
private final Object mLockReadPeerID = new Object();
private final Object mLockMtu = new Object();
private BluetoothGattService mBertyService;
private BluetoothGattCharacteristic mPeerIDCharacteristic;
private BluetoothGattCharacteristic mWriterCharacteristic;
private String mPeerID;
private boolean mHasReadServerPeerID;
private boolean mHasReadClientPeerID;
//private int mMtu = 0;
// default MTU is 23
private int mMtu = 23;
public PeerDevice(@NonNull Context context, @NonNull BluetoothDevice bluetoothDevice) {
mContext = context;
mBluetoothDevice = bluetoothDevice;
}
public String getMACAddress() {
return mBluetoothDevice.getAddress();
}
@NonNull
@Override
public java.lang.String toString() {
return getMACAddress();
}
// Use TRANSPORT_LE for connections to remote dual-mode devices. This is a solution to prevent the error
// status 133 in GATT connections:
// https://android.jlelse.eu/lessons-for-first-time-android-bluetooth-le-developers-i-learned-the-hard-way-fee07646624
// API level 23
public boolean asyncConnectionToDevice() {
Log.d(TAG, "asyncConnectionToDevice() called");
if (!isConnected()) {
mThread = new Thread(new Runnable() {
@Override
public void run() {
setBluetoothGatt(mBluetoothDevice.connectGatt(mContext, false,
mGattCallback, BluetoothDevice.TRANSPORT_LE));
}
});
mThread.start();
}
return false;
}
public boolean isConnected() {
return getState() == CONNECTION_STATE.CONNECTED;
}
public boolean isDisconnected() {
return getState() == CONNECTION_STATE.DISCONNECTED;
}
// setters and getters are accessed by the DeviceManager thread et this thread so we need to
// synchronize them.
public void setState(CONNECTION_STATE state) {
synchronized (mLockState) {
mState = state;
}
}
public CONNECTION_STATE getState() {
synchronized (mLockState) {
return mState;
}
}
public void setBluetoothGatt(BluetoothGatt gatt) {
synchronized (mLockState) {
mBluetoothGatt = gatt;
}
}
public BluetoothGatt getBluetoothGatt() {
synchronized (mLockState) {
return mBluetoothGatt;
}
}
public void setPeerIDCharacteristic(BluetoothGattCharacteristic peerID) {
mPeerIDCharacteristic = peerID;
}
public BluetoothGattCharacteristic getPeerIDCharacteristic() {
return mPeerIDCharacteristic;
}
public void setWriterCharacteristic(BluetoothGattCharacteristic write) {
mWriterCharacteristic = write;
}
public BluetoothGattCharacteristic getWriterCharacteristic() {
return mWriterCharacteristic;
}
public boolean updateWriterValue(String value) {
return getWriterCharacteristic().setValue(value);
}
public BluetoothGattService getBertyService() {
return mBertyService;
}
public void setBertyService(BluetoothGattService service) {
mBertyService = service;
}
public void setPeerID(String peerID) {
mPeerID = peerID;
}
public String getPeerID() {
return mPeerID;
}
public void setReadClientPeerID(boolean value) {
Log.d(TAG, "setReadClientPeerID called: " + value);
synchronized (mLockReadPeerID) {
mHasReadClientPeerID = value;
if (mHasReadServerPeerID) {
PeerManager.set(getPeerID(), true, this);
} else {
PeerManager.set(getPeerID(), false, this);
}
}
}
public boolean hasReadClientPeerID() {
synchronized (mLockReadPeerID) {
return mHasReadClientPeerID;
}
}
public void setReadServerPeerID(boolean value) {
Log.d(TAG, "setReadServerPeerID called: " + value);
synchronized (mLockReadPeerID) {
mHasReadServerPeerID = value;
if (mHasReadClientPeerID) {
PeerManager.set(getPeerID(), true, this);
}
}
}
public boolean hasReadServerPeerID() {
synchronized (mLockReadPeerID) {
return mHasReadServerPeerID;
}
}
public void close() {
if (isConnected()) {
getBluetoothGatt().close();
setState(CONNECTION_STATE.DISCONNECTING);
}
}
private boolean takeBertyService(List<BluetoothGattService> services) {
Log.d(TAG, "takeBertyService() called");
for (BluetoothGattService service : services) {
if (service.getUuid().equals(GattServer.SERVICE_UUID)) {
Log.d(TAG, "takeBertyService(): found");
setBertyService(service);
return true;
}
}
return false;
}
private boolean checkCharacteristicProperties(BluetoothGattCharacteristic characteristic,
int properties) {
if (characteristic.getProperties() == properties) {
Log.d(TAG, "checkCharacteristicProperties() match");
return true;
}
Log.e(TAG, "checkCharacteristicProperties() doesn't match: " + characteristic.getProperties() + " / " + properties);
return false;
}
private boolean takeBertyCharacteristics() {
int nbOfFoundCharacteristics = 0;
List<BluetoothGattCharacteristic> characteristics = mBertyService.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
if (characteristic.getUuid().equals(GattServer.PEER_ID_UUID)) {
Log.d(TAG, "takeBertyCharacteristic(): peerID characteristic found");
if (checkCharacteristicProperties(characteristic,
BluetoothGattCharacteristic.PROPERTY_READ)) {
setPeerIDCharacteristic(characteristic);
nbOfFoundCharacteristics++;
}
} else if (characteristic.getUuid().equals(GattServer.WRITER_UUID)) {
Log.d(TAG, "takeBertyCharacteristic(): writer characteristic found");
if (checkCharacteristicProperties(characteristic,
BluetoothGattCharacteristic.PROPERTY_WRITE)) {
setWriterCharacteristic(characteristic);
nbOfFoundCharacteristics++;
}
}
if (nbOfFoundCharacteristics == 2) {
return true;
}
}
return false;
}
// Asynchronous operation that will be reported to the BluetoothGattCallback#onCharacteristicRead
// callback.
public boolean requestPeerIDValue() {
Log.v(TAG, "requestPeerIDValue() called");
if (!mBluetoothGatt.readCharacteristic(getPeerIDCharacteristic())) {
Log.e(TAG, "requestPeerIDValue() error");
return false;
}
return true;
}
public void setMtu(int mtu) {
synchronized (mLockMtu) {
mMtu = mtu;
}
}
public int getMtu() {
synchronized (mLockMtu) {
return mMtu;
}
}
private BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
Log.d(TAG, "onConnectionStateChange() called by device " + gatt.getDevice().getAddress());
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.d(TAG, "onConnectionStateChange(): connected");
setState(CONNECTION_STATE.CONNECTED);
gatt.requestMtu(REQUEST_MTU);
//gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.d(TAG, "onConnectionStateChange(): disconnected");
setState(CONNECTION_STATE.DISCONNECTED);
setBluetoothGatt(null);
} else {
Log.e(TAG, "onConnectionStateChange(): unknown state");
setState(CONNECTION_STATE.DISCONNECTED);
close();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
Log.d(TAG, "onServicesDiscovered(): called");
if (takeBertyService(gatt.getServices())) {
if (takeBertyCharacteristics()) {
requestPeerIDValue();
}
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
super.onCharacteristicRead(gatt, characteristic, status);
Log.d(TAG, "onCharacteristicRead() called");
if (status != BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "onCharacteristicRead(): read error");
gatt.close();
}
if (characteristic.getUuid().equals(GattServer.PEER_ID_UUID)) {
String peerID;
if ((peerID = characteristic.getStringValue(0)) == null
|| peerID.length() == 0) {
Log.e(TAG, "takePeerID() error: peerID is null");
} else {
setPeerID(peerID);
Log.i(TAG, "takePeerID(): peerID is " + peerID);
setReadClientPeerID(true);
}
}
}
@Override
public void onCharacteristicWrite (BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
Log.d(TAG, "onMtuChanged() called: " + mtu);
PeerDevice peerDevice;
if (status != BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "onMtuChanged() error: transmission error");
return ;
}
if ((peerDevice = DeviceManager.get(gatt.getDevice().getAddress())) == null) {
Log.e(TAG, "onMtuChanged() error: device not found");
return ;
}
peerDevice.setMtu(mtu);
gatt.discoverServices();
}
};
}
| true |
78d3a5ff00bff8683c626b87aa5ca73ac6c91fe6 | Java | matrixxun/FMTech | /GooglePlay6.0.5/app/src/main/java/com/google/android/finsky/download/inlineappinstaller/steps/InlineConsumptionAppInstallerReadyToReadStep.java | UTF-8 | 2,377 | 1.632813 | 2 | [
"Apache-2.0"
] | permissive | package com.google.android.finsky.download.inlineappinstaller.steps;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.finsky.analytics.FinskyEventLog;
import com.google.android.finsky.analytics.PlayStore.PlayStoreUiElement;
import com.google.android.finsky.api.model.Document;
import com.google.android.finsky.billing.lightpurchase.multistep.StepFragment;
import com.google.android.finsky.download.inlineappinstaller.InlineConsumptionAppInstallerFragment;
import com.google.android.finsky.navigationmanager.ConsumptionUtils;
import com.google.android.finsky.utils.UiUtils;
public final class InlineConsumptionAppInstallerReadyToReadStep
extends StepFragment<InlineConsumptionAppInstallerFragment>
{
private View mMainView;
private final PlayStore.PlayStoreUiElement mUiElement = FinskyEventLog.obtainPlayStoreUiElement(5107);
public final String getContinueButtonLabel(Resources paramResources)
{
return paramResources.getString(2131362633);
}
public final PlayStore.PlayStoreUiElement getPlayStoreUiElement()
{
return this.mUiElement;
}
public final void onContinueButtonClicked()
{
((InlineConsumptionAppInstallerFragment)this.mParentFragment).logClick(5108, this);
((InlineConsumptionAppInstallerFragment)this.mParentFragment).finish(true);
}
public final View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
{
Document localDocument = (Document)this.mArguments.getParcelable("InlineConsumptionAppInstallerReadyToReadStep.appDoc");
this.mMainView = paramLayoutInflater.inflate(2130968795, paramViewGroup, false);
ConsumptionUtils.maybeBindAppIcon(localDocument, this.mMainView);
return this.mMainView;
}
public final void onResume()
{
super.onResume();
UiUtils.sendAccessibilityEventWithText(getContext(), getString(2131361846), this.mMainView);
}
}
/* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar
* Qualified Name: com.google.android.finsky.download.inlineappinstaller.steps.InlineConsumptionAppInstallerReadyToReadStep
* JD-Core Version: 0.7.0.1
*/ | true |
98e8cf03d8c33bc58ef987ce950b7e4beb14292a | Java | BrianKGit/Java-WSU | /Rectangle.java | UTF-8 | 1,314 | 4.15625 | 4 | [] | no_license | /*
* Author: Brian Klein
* Date: 4-1-17
* Program: Rectangle.java
* Purpose: user-defined class to create a rectangle object
*/
import java.util.Scanner; //use a Scanner object to represent the keyboard
public class Rectangle
{
//data members - instance variables
private double length, width;
//setters and getters
public void setLength(double len) {
length = len;
}
public void setWidth(double w) {
width = w;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return (2 * length) + (2 * width);
}
//two overloaded constructors
public Rectangle() {
length = 0;
width = 0;
}
public Rectangle(double len, double w) {
length = len;
width = w;
}
//toString method
public String toString() {
String str = "\nLength: " + length +
"\nWidth: " + width +
"\nArea: " + (length * width) +
"\nPerimeter: " + ((2 * length) + (2 * width));
return str;
}
}//end class | true |
ebb04a886afaa732e9e2b20f2b9f97b95c22d026 | Java | idiraitsadoune/OntoEventB | /fr.cs.ontoeventb.pivotmodel.metamodel/src/pivotmodel/NamedUnit.java | UTF-8 | 1,220 | 2.171875 | 2 | [] | no_license | /**
*/
package pivotmodel;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Named Unit</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link pivotmodel.NamedUnit#getExponent <em>Exponent</em>}</li>
* </ul>
*
* @see pivotmodel.PivotmodelPackage#getNamedUnit()
* @model
* @generated
*/
public interface NamedUnit extends UnitType {
/**
* Returns the value of the '<em><b>Exponent</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Exponent</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Exponent</em>' attribute.
* @see #setExponent(int)
* @see pivotmodel.PivotmodelPackage#getNamedUnit_Exponent()
* @model
* @generated
*/
int getExponent();
/**
* Sets the value of the '{@link pivotmodel.NamedUnit#getExponent <em>Exponent</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Exponent</em>' attribute.
* @see #getExponent()
* @generated
*/
void setExponent(int value);
} // NamedUnit
| true |
7c0f06ea846aca167b01f22315a75c435cfb27a9 | Java | anand1996wani/CompetitiveCoding-Hard | /MergeSort.java | UTF-8 | 2,936 | 3.5625 | 4 | [] | no_license | /*
Given an array, find inversion count of array.
Inversion Count for an array indicates – how far (or close) the array is from being sorted.
If array is already sorted then inversion count is 0.
If array is sorted in reverse order that inversion count is the maximum.
Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].
Output:
Print the inversion count of array.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
1 ≤ C ≤ 500
Example:
Input:
1
5
2 4 1 3 5
Output:
3
*/
import java.util.*;
import java.lang.*;
import java.io.*;
class MergeSort
{
//public static int inversion;
public static int merge(int array[],int temp[],int low,int mid,int high){
//int left[] = new int[mid - low + 1];
//int right[] = new int[high - mid];
int inversion = 0;
int n1 = mid - low + 1;
int n2 = high - mid;
int l = low;
int r = mid + 1;
int k = low;
while((l <= mid)&&(r <= high)){
if(array[l] <= array[r]){
temp[k++] = array[l++];
}
else{
temp[k++] = array[r++];
inversion = inversion + mid + 1 - l;
}
}
while(l <= mid){
temp[k++] = array[l++];
}
while(r <= high){
temp[k++] = array[r++];
}
for(int i = low;i<=high;i++){
array[i] = temp[i];
}
return inversion;
}
public static int mergeSort(int array[],int temp[],int low,int high){
int inversion = 0;
if(low < high){
int mid = (low + high)/2;
inversion = inversion + mergeSort(array,temp,low,mid);
inversion = inversion + mergeSort(array,temp,mid + 1,high);
inversion = inversion + merge(array,temp,low,mid,high);
}
return inversion;
}
public static void main (String[] args)
{
//code
Scanner scanner = new Scanner(System.in);
int test = scanner.nextInt();
for(int i = 0;i<test;i++){
int n = scanner.nextInt();
int array[] = new int[n];
for(int j = 0;j<n;j++){
array[j] = scanner.nextInt();
}
/*for(int k = 0;k<n;k++){
System.out.print(array[k]);
System.out.print(" ");
}
System.out.println();*/
int temp[] = new int[n];
int inversion = mergeSort(array,temp,0,n-1);
/*for(int k = 0;k<n;k++){
System.out.print(array[k]);
System.out.print(" ");
}*/
System.out.println(inversion);
}
}
}
| true |
24e01c39ef53a72568e76ddb0f2730c0ecbed121 | Java | googleapis/google-cloud-java | /java-document-ai/proto-google-cloud-document-ai-v1/src/main/java/com/google/cloud/documentai/v1/BatchProcessRequestOrBuilder.java | UTF-8 | 5,686 | 1.84375 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/documentai/v1/document_processor_service.proto
package com.google.cloud.documentai.v1;
public interface BatchProcessRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.documentai.v1.BatchProcessRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The resource name of
* [Processor][google.cloud.documentai.v1.Processor] or
* [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion].
* Format: `projects/{project}/locations/{location}/processors/{processor}`,
* or
* `projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
java.lang.String getName();
/**
*
*
* <pre>
* Required. The resource name of
* [Processor][google.cloud.documentai.v1.Processor] or
* [ProcessorVersion][google.cloud.documentai.v1.ProcessorVersion].
* Format: `projects/{project}/locations/{location}/processors/{processor}`,
* or
* `projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
com.google.protobuf.ByteString getNameBytes();
/**
*
*
* <pre>
* The input documents for the
* [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]
* method.
* </pre>
*
* <code>.google.cloud.documentai.v1.BatchDocumentsInputConfig input_documents = 5;</code>
*
* @return Whether the inputDocuments field is set.
*/
boolean hasInputDocuments();
/**
*
*
* <pre>
* The input documents for the
* [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]
* method.
* </pre>
*
* <code>.google.cloud.documentai.v1.BatchDocumentsInputConfig input_documents = 5;</code>
*
* @return The inputDocuments.
*/
com.google.cloud.documentai.v1.BatchDocumentsInputConfig getInputDocuments();
/**
*
*
* <pre>
* The input documents for the
* [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]
* method.
* </pre>
*
* <code>.google.cloud.documentai.v1.BatchDocumentsInputConfig input_documents = 5;</code>
*/
com.google.cloud.documentai.v1.BatchDocumentsInputConfigOrBuilder getInputDocumentsOrBuilder();
/**
*
*
* <pre>
* The output configuration for the
* [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]
* method.
* </pre>
*
* <code>.google.cloud.documentai.v1.DocumentOutputConfig document_output_config = 6;</code>
*
* @return Whether the documentOutputConfig field is set.
*/
boolean hasDocumentOutputConfig();
/**
*
*
* <pre>
* The output configuration for the
* [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]
* method.
* </pre>
*
* <code>.google.cloud.documentai.v1.DocumentOutputConfig document_output_config = 6;</code>
*
* @return The documentOutputConfig.
*/
com.google.cloud.documentai.v1.DocumentOutputConfig getDocumentOutputConfig();
/**
*
*
* <pre>
* The output configuration for the
* [BatchProcessDocuments][google.cloud.documentai.v1.DocumentProcessorService.BatchProcessDocuments]
* method.
* </pre>
*
* <code>.google.cloud.documentai.v1.DocumentOutputConfig document_output_config = 6;</code>
*/
com.google.cloud.documentai.v1.DocumentOutputConfigOrBuilder getDocumentOutputConfigOrBuilder();
/**
*
*
* <pre>
* Whether human review should be skipped for this request. Default to
* `false`.
* </pre>
*
* <code>bool skip_human_review = 4;</code>
*
* @return The skipHumanReview.
*/
boolean getSkipHumanReview();
/**
*
*
* <pre>
* Inference-time options for the process API
* </pre>
*
* <code>.google.cloud.documentai.v1.ProcessOptions process_options = 7;</code>
*
* @return Whether the processOptions field is set.
*/
boolean hasProcessOptions();
/**
*
*
* <pre>
* Inference-time options for the process API
* </pre>
*
* <code>.google.cloud.documentai.v1.ProcessOptions process_options = 7;</code>
*
* @return The processOptions.
*/
com.google.cloud.documentai.v1.ProcessOptions getProcessOptions();
/**
*
*
* <pre>
* Inference-time options for the process API
* </pre>
*
* <code>.google.cloud.documentai.v1.ProcessOptions process_options = 7;</code>
*/
com.google.cloud.documentai.v1.ProcessOptionsOrBuilder getProcessOptionsOrBuilder();
}
| true |
a1d47a427cd0bbbda80caad7b89130eb1e2ecdc3 | Java | lovexiaodong/Data-Structure | /DataStructure/src/com/zyd/map/PrimDemo.java | GB18030 | 2,285 | 3 | 3 | [] | no_license | package com.zyd.map;
/**
* prim㷨ͼС
* @author
*
*/
public class PrimDemo {
private static int MAXVEX = 9;
public static void main(String[] args) {
int[][] src = {
{0, 10, 65535, 65535, 65535, 11, 65535, 65535, 65535},
{10, 0, 18, 65535, 65535, 65535, 16, 65535, 12},
{65535, 65535, 0, 22, 65535, 65535, 65535, 65535, 8},
{65535, 65535, 22, 0, 20, 65535, 65535, 16, 21},
{65535, 65535, 65535, 20, 0, 26, 65535, 7, 65535 },
{11, 65535, 65535, 65535, 26, 0, 17, 65535, 65535},
{65535, 16, 65535, 65535, 65535, 17, 0, 19, 65535},
{65535, 65535, 65535, 16, 17, 65535, 19, 0, 65535},
{65535, 12, 8, 21, 65535, 65535, 65535, 65535, 0}};
MiniPanTree_Prim(src);
}
public static void MiniPanTree_Prim(int[][] src) {
int min, i, j, k;
int adjvex[] = new int[MAXVEX];
int lowcast[] = new int[MAXVEX];
lowcast[0] = 0;
adjvex[0] = 0;
for(i = 1; i < src.length; i ++) {
lowcast[i] = src[0][i];
adjvex[i] = 0;
}
for(i = 1; i < src.length; i++) {
min = 65535;
j = 1; k =0;
while(j < src.length) {
if(lowcast[j] != 0 && lowcast[j] < min) {
min = lowcast[j];
k = j;
}
j++;
}
System.out.println("(" + adjvex[k] + "," + k + ")");
lowcast[k] = 0;
for(j = 1; j < src.length; j++) {
if(lowcast[j] != 0 && src[k][j] < lowcast[j]) {
lowcast[j] = src[k][j];
adjvex[j] = k;
}
}
}
}
public static void MinTree_Src(int[][] src) {
int[] adjvex = new int[src.length];
int[] lowcost = new int[src.length];
int max = 65535;
adjvex[0] = 0;
lowcost[0] = 0;
int j = 0, k = 0, i = 0;
for(i = 1; i < src.length; i++) {
lowcost[i] = src[0][i];
adjvex[i] = 0;
}
for(i = 1; i < src.length; i++) {
max = 65535;
j = 1;
while(j < src.length) {
if(lowcost[j] != 0 && lowcost[j] < max) {
max = lowcost[j];
k = j;
}
j++;
}
System.out.println("(" + adjvex[k] + ", " + k + ")");
lowcost[k] = 0;
for(j = 1; j < src.length; j++) {
if(lowcost[j] != 0 && src[k][j] < lowcost[j]) {
lowcost[j] = src[k][j];
adjvex[j] = k;
}
}
}
}
}
| true |
b2988da26dac15a09d8e497446ddea5054e781e8 | Java | Newegg/newegg-marketplace-sdk-java | /Seller/src/test/java/com/newegg/marketplace/sdk/seller/inner/SubcategoryCallerTest.java | UTF-8 | 17,698 | 1.765625 | 2 | [] | no_license | package com.newegg.marketplace.sdk.seller.inner;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.newegg.marketplace.sdk.common.APIConfig;
import com.newegg.marketplace.sdk.common.Content;
import com.newegg.marketplace.sdk.common.Content.MEDIA_TYPE;
import com.newegg.marketplace.sdk.common.Content.PLATFORM;
import com.newegg.marketplace.sdk.seller.SellerConfig;
import com.newegg.marketplace.sdk.seller.Variables;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryPropertiesRequest;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryPropertiesResponse;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryPropertyValuesRequest;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryPropertyValuesResponse;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusForInternationalCountryRequest;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusForInternationalCountryResponse;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusRequest;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusRequest.RequestBody.GetItemSubcategory;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusRequest.RequestBody.GetItemSubcategory.IndustryCodeList;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusRequest.RequestBody.GetItemSubcategory.SubcategoryIDList;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusResponse;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusV1Request;
import com.newegg.marketplace.sdk.seller.model.GetSubcategoryStatusV1Response;
public class SubcategoryCallerTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
APIConfig.load(SellerConfig.class);
}
@Before
public void before() {
Variables.SimulationEnabled = true;
}
@After
public void After() {
Variables.SimulationEnabled = false;
}
@Test
public void testGetSubcategoryPropertyValues_XML() {
SubcategoryCaller call=SubcategoryCaller.buildXML();
GetSubcategoryPropertyValuesRequest request=new GetSubcategoryPropertyValuesRequest();
GetSubcategoryPropertyValuesRequest.RequestBody body=new GetSubcategoryPropertyValuesRequest.RequestBody();
body.setPropertyName("Costume_Gender");
body.setSubcategoryID(1045);
request.setRequestBody(body);
GetSubcategoryPropertyValuesResponse r=call.getSubcategoryPropertyValues(request);
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getPropertyInfoList().getPropertyInfo().size()>0);
}
@Test
public void testGetSubcategoryPropertyValues_JSON() {
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryPropertyValuesRequest request=new GetSubcategoryPropertyValuesRequest();
GetSubcategoryPropertyValuesRequest.RequestBody body=new GetSubcategoryPropertyValuesRequest.RequestBody();
body.setPropertyName("Costume_Gender");
body.setSubcategoryID(1045);
request.setRequestBody(body);
GetSubcategoryPropertyValuesResponse r=call.getSubcategoryPropertyValues(request);
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getPropertyInfoList().getPropertyInfo().size()>0);
}
@Test
public void testGetSubcategoryProperties_XML() {
SubcategoryCaller call=SubcategoryCaller.buildXML();
GetSubcategoryPropertiesRequest request=new GetSubcategoryPropertiesRequest();
GetSubcategoryPropertiesRequest.RequestBody body=new GetSubcategoryPropertiesRequest.RequestBody();
body.setSubcategoryID(1045);
request.setRequestBody(body);
GetSubcategoryPropertiesResponse r=call.getSubcategoryProperties(request);
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getSubcategoryPropertyList().getSubcategoryProperty().size()>0);
}
@Test
public void testGetSubcategoryProperties_JSON() {
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryPropertiesRequest request=new GetSubcategoryPropertiesRequest();
GetSubcategoryPropertiesRequest.RequestBody body=new GetSubcategoryPropertiesRequest.RequestBody();
body.setSubcategoryID(1045);
request.setRequestBody(body);
GetSubcategoryPropertiesResponse r=call.getSubcategoryProperties(request);
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getSubcategoryPropertyList().getSubcategoryProperty().size()>0);
}
@Test
public void testGetSubcategory4InternationalCountry_XML() {
PLATFORM tmp=Content.Platform;
Content.Platform=PLATFORM.USA;
SubcategoryCaller call=SubcategoryCaller.buildXML();
GetSubcategoryStatusForInternationalCountryRequest request=new GetSubcategoryStatusForInternationalCountryRequest();
GetSubcategoryStatusForInternationalCountryRequest.RequestBody body=new GetSubcategoryStatusForInternationalCountryRequest.RequestBody();
body.setCountryCode("USA");
GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory s=new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory();
s.setEnabled(1);
s.setSubcategoryIDList(new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory.SubcategoryIDList());
s.getSubcategoryIDList().getSubcategoryID().add(397);
s.setIndustryCodeList(new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory.IndustryCodeList());
s.getIndustryCodeList().getIndustryCode().add("CH");
body.setGetItemSubcategory(s);
request.setRequestBody(body);
GetSubcategoryStatusForInternationalCountryResponse r=call.getSubcategory4InternationalCountry(request);
Content.Platform=tmp;
assertTrue(r.getIsSuccess());
assertTrue("USA".equals(r.getResponseBody().getCountryCode()));
assertTrue(r.getResponseBody().getSubcategoryList().getSubcategory().size()>0);
}
@Test
public void testGetSubcategoryStatusV1_JSON() {
Variables.MediaType = MEDIA_TYPE.JSON;
// Variables.SimulationEnabled = true;
PLATFORM tmp=Content.Platform;
Content.Platform=PLATFORM.USA;
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryStatusV1Request body=new GetSubcategoryStatusV1Request();
GetSubcategoryStatusV1Request.RequestBody requestBody=new GetSubcategoryStatusV1Request.RequestBody();
body.setRequestBody(requestBody);
GetSubcategoryStatusV1Request.RequestBody.GetItemSubcategory getItemSubcategory=new GetSubcategoryStatusV1Request.RequestBody.GetItemSubcategory();
requestBody.setGetItemSubcategory(getItemSubcategory);
GetSubcategoryStatusV1Request.RequestBody.GetItemSubcategory.SubcategoryIDList subcategoryIDList=new GetSubcategoryStatusV1Request.RequestBody.GetItemSubcategory.SubcategoryIDList();
List<Integer> webSiteCategoryIDList=new ArrayList<>();
webSiteCategoryIDList.add(402);
subcategoryIDList.setWebSiteCategoryID(webSiteCategoryIDList);
subcategoryIDList.setWebSiteCatalogName("CH");
getItemSubcategory.setSubcategoryIDList(subcategoryIDList);
GetSubcategoryStatusV1Response res = call.getSubcategoryStatusV1(body);
System.out.println(res);
}
@Test
public void testGetSubcategory4InternationalCountry_JSON() {
PLATFORM tmp=Content.Platform;
Content.Platform=PLATFORM.USA;
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryStatusForInternationalCountryRequest request=new GetSubcategoryStatusForInternationalCountryRequest();
GetSubcategoryStatusForInternationalCountryRequest.RequestBody body=new GetSubcategoryStatusForInternationalCountryRequest.RequestBody();
body.setCountryCode("USA");
GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory s=new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory();
s.setEnabled(1);
s.setSubcategoryIDList(new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory.SubcategoryIDList());
s.getSubcategoryIDList().getSubcategoryID().add(397);
s.setIndustryCodeList(new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory.IndustryCodeList());
s.getIndustryCodeList().getIndustryCode().add("CH");
body.setGetItemSubcategory(s);
request.setRequestBody(body);
GetSubcategoryStatusForInternationalCountryResponse r=call.getSubcategory4InternationalCountry(request);
Content.Platform=tmp;
assertTrue(r.getIsSuccess());
assertTrue("USA".equals(r.getResponseBody().getCountryCode()));
assertTrue(r.getResponseBody().getSubcategoryList().getSubcategory().size()>0);
}
@Test
public void testGetSubcategoryStatus_XML() {
SubcategoryCaller call=SubcategoryCaller.buildXML();
GetSubcategoryStatusRequest request=new GetSubcategoryStatusRequest();
GetSubcategoryStatusRequest.RequestBody body=new GetSubcategoryStatusRequest.RequestBody();
GetItemSubcategory s=new GetItemSubcategory();
s.setEnabled(1);
s.setSubcategoryIDList(new SubcategoryIDList());
s.getSubcategoryIDList().getSubcategoryID().add(397);
s.setIndustryCodeList(new IndustryCodeList());
s.getIndustryCodeList().getIndustryCode().add("CH");
body.setGetItemSubcategory(s);
request.setRequestBody(body);
GetSubcategoryStatusResponse r=call.getSubcategoryStatus(request);
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getSubcategoryList().getSubcategory().size()>0);
}
@Test
public void testGetSubcategoryStatus_JSON() {
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryStatusRequest request=new GetSubcategoryStatusRequest();
GetSubcategoryStatusRequest.RequestBody body=new GetSubcategoryStatusRequest.RequestBody();
GetItemSubcategory s=new GetItemSubcategory();
s.setEnabled(1);
s.setSubcategoryIDList(new SubcategoryIDList());
s.getSubcategoryIDList().getSubcategoryID().add(397);
s.setIndustryCodeList(new IndustryCodeList());
s.getIndustryCodeList().getIndustryCode().add("CH");
body.setGetItemSubcategory(s);
request.setRequestBody(body);
GetSubcategoryStatusResponse r=call.getSubcategoryStatus(request);
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getSubcategoryList().getSubcategory().size()>0);
}
@Test
public void testMockGetSubcategoryStatus_XML() {
Variables.SimulationEnabled=true;
SubcategoryCaller call=SubcategoryCaller.buildXML();
GetSubcategoryStatusRequest request=new GetSubcategoryStatusRequest();
GetSubcategoryStatusRequest.RequestBody body=new GetSubcategoryStatusRequest.RequestBody();
GetItemSubcategory s=new GetItemSubcategory();
s.setEnabled(1);
s.setSubcategoryIDList(new SubcategoryIDList());
s.getSubcategoryIDList().getSubcategoryID().add(379);
s.setIndustryCodeList(new IndustryCodeList());
s.getIndustryCodeList().getIndustryCode().add("CH");
body.setGetItemSubcategory(s);
request.setRequestBody(body);
GetSubcategoryStatusResponse r=call.getSubcategoryStatus(request);
Variables.SimulationEnabled=false;
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getSubcategoryList().getSubcategory().size()>0);
}
@Test
public void testMockGetSubcategoryStatus_JSON() {
Variables.SimulationEnabled=true;
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryStatusRequest request=new GetSubcategoryStatusRequest();
GetSubcategoryStatusRequest.RequestBody body=new GetSubcategoryStatusRequest.RequestBody();
GetItemSubcategory s=new GetItemSubcategory();
s.setEnabled(1);
s.setSubcategoryIDList(new SubcategoryIDList());
s.getSubcategoryIDList().getSubcategoryID().add(379);
s.setIndustryCodeList(new IndustryCodeList());
s.getIndustryCodeList().getIndustryCode().add("CH");
body.setGetItemSubcategory(s);
request.setRequestBody(body);
GetSubcategoryStatusResponse r=call.getSubcategoryStatus(request);
Variables.SimulationEnabled=false;
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getSubcategoryList().getSubcategory().size()>0);
}
@Test
public void testMockGetSubcategory4InternationalCountry_XML() {
Variables.SimulationEnabled=true;
PLATFORM tmp=Content.Platform;
Content.Platform=PLATFORM.USA;
SubcategoryCaller call=SubcategoryCaller.buildXML();
GetSubcategoryStatusForInternationalCountryRequest request=new GetSubcategoryStatusForInternationalCountryRequest();
GetSubcategoryStatusForInternationalCountryRequest.RequestBody body=new GetSubcategoryStatusForInternationalCountryRequest.RequestBody();
body.setCountryCode("USA");
GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory s=new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory();
s.setEnabled(1);
s.setSubcategoryIDList(new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory.SubcategoryIDList());
s.getSubcategoryIDList().getSubcategoryID().add(397);
s.setIndustryCodeList(new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory.IndustryCodeList());
s.getIndustryCodeList().getIndustryCode().add("CH");
body.setGetItemSubcategory(s);
request.setRequestBody(body);
GetSubcategoryStatusForInternationalCountryResponse r=call.getSubcategory4InternationalCountry(request);
Variables.SimulationEnabled=false;
Content.Platform=tmp;
assertTrue(r.getIsSuccess());
assertTrue("USA".equals(r.getResponseBody().getCountryCode()));
assertTrue(r.getResponseBody().getSubcategoryList().getSubcategory().size()>0);
}
@Test
public void testMockGetSubcategory4InternationalCountry_JSON() {
Variables.SimulationEnabled=true;
PLATFORM tmp=Content.Platform;
Content.Platform=PLATFORM.USA;
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryStatusForInternationalCountryRequest request=new GetSubcategoryStatusForInternationalCountryRequest();
GetSubcategoryStatusForInternationalCountryRequest.RequestBody body=new GetSubcategoryStatusForInternationalCountryRequest.RequestBody();
body.setCountryCode("USA");
GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory s=new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory();
s.setEnabled(1);
s.setSubcategoryIDList(new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory.SubcategoryIDList());
s.getSubcategoryIDList().getSubcategoryID().add(397);
s.setIndustryCodeList(new GetSubcategoryStatusForInternationalCountryRequest.RequestBody.GetItemSubcategory.IndustryCodeList());
s.getIndustryCodeList().getIndustryCode().add("CH");
body.setGetItemSubcategory(s);
request.setRequestBody(body);
GetSubcategoryStatusForInternationalCountryResponse r=call.getSubcategory4InternationalCountry(request);
Variables.SimulationEnabled=false;
Content.Platform=tmp;
assertTrue(r.getIsSuccess());
assertTrue("USA".equals(r.getResponseBody().getCountryCode()));
assertTrue(r.getResponseBody().getSubcategoryList().getSubcategory().size()>0);
}
@Test
public void testMockGetSubcategoryProperties_XML() {
Variables.SimulationEnabled=true;
SubcategoryCaller call=SubcategoryCaller.buildXML();
GetSubcategoryPropertiesRequest request=new GetSubcategoryPropertiesRequest();
GetSubcategoryPropertiesRequest.RequestBody body=new GetSubcategoryPropertiesRequest.RequestBody();
body.setSubcategoryID(1045);
request.setRequestBody(body);
GetSubcategoryPropertiesResponse r=call.getSubcategoryProperties(request);
Variables.SimulationEnabled=false;
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getSubcategoryPropertyList().getSubcategoryProperty().size()>0);
}
@Test
public void testMockGetSubcategoryProperties_JSON() {
Variables.SimulationEnabled=true;
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryPropertiesRequest request=new GetSubcategoryPropertiesRequest();
GetSubcategoryPropertiesRequest.RequestBody body=new GetSubcategoryPropertiesRequest.RequestBody();
body.setSubcategoryID(1045);
request.setRequestBody(body);
GetSubcategoryPropertiesResponse r=call.getSubcategoryProperties(request);
Variables.SimulationEnabled=false;
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getSubcategoryPropertyList().getSubcategoryProperty().size()>0);
}
@Test
public void testMockGetSubcategoryPropertyValues_XML() {
Variables.SimulationEnabled=true;
SubcategoryCaller call=SubcategoryCaller.buildXML();
GetSubcategoryPropertyValuesRequest request=new GetSubcategoryPropertyValuesRequest();
GetSubcategoryPropertyValuesRequest.RequestBody body=new GetSubcategoryPropertyValuesRequest.RequestBody();
body.setPropertyName("Costume_Gender");
body.setSubcategoryID(1045);
request.setRequestBody(body);
GetSubcategoryPropertyValuesResponse r=call.getSubcategoryPropertyValues(request);
Variables.SimulationEnabled=false;
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getPropertyInfoList().getPropertyInfo().size()>0);
}
@Test
public void testMockGetSubcategoryPropertyValues_JSON() {
Variables.SimulationEnabled=true;
SubcategoryCaller call=SubcategoryCaller.buildJSON();
GetSubcategoryPropertyValuesRequest request=new GetSubcategoryPropertyValuesRequest();
GetSubcategoryPropertyValuesRequest.RequestBody body=new GetSubcategoryPropertyValuesRequest.RequestBody();
body.setPropertyName("Costume_Gender");
body.setSubcategoryID(1045);
request.setRequestBody(body);
GetSubcategoryPropertyValuesResponse r=call.getSubcategoryPropertyValues(request);
Variables.SimulationEnabled=false;
assertTrue(r.getIsSuccess());
assertTrue(r.getResponseBody().getPropertyInfoList().getPropertyInfo().size()>0);
}
}
| true |
4ced795a27a089849554597e3e27fd26bd57a61d | Java | yapengsong/business | /src-biz/eayun-virtualization/src/main/java/com/eayun/virtualization/ecmccontroller/EcmcCloudVolumeTypeController.java | UTF-8 | 4,894 | 1.875 | 2 | [] | no_license | package com.eayun.virtualization.ecmccontroller;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.eayun.common.ConstantClazz;
import com.eayun.common.dao.ParamsMap;
import com.eayun.common.dao.QueryMap;
import com.eayun.common.dao.support.Page;
import com.eayun.common.exception.AppException;
import com.eayun.common.model.EayunResponseJson;
import com.eayun.log.ecmcsevice.EcmcLogService;
import com.eayun.virtualization.ecmcservice.EcmcCloudVolumeTypeService;
import com.eayun.virtualization.model.CloudImage;
import com.eayun.virtualization.model.CloudVolumeType;
/**
* @author
*
*/
@Controller
@RequestMapping("/ecmc/cloud/volumetype")
@Scope("prototype")
public class EcmcCloudVolumeTypeController {
private static final Logger log = LoggerFactory.getLogger(EcmcCloudVolumeTypeController.class);
@Autowired
private EcmcCloudVolumeTypeService ecmcCloudVolumeTypeService;
@Autowired
private EcmcLogService ecmcLogService;
/**
* 查询云硬盘类型列表
*
* @author Chengxiaodong
* @param request
* @param datacenterId
* @param page
* @return
* @throws Exception
*/
@RequestMapping(value = "/getvolumetypelist", method = RequestMethod.POST)
@ResponseBody
public String getVolumeList(HttpServletRequest request, Page page,
@RequestBody ParamsMap map) throws Exception{
try {
log.info("查询云硬盘列表开始");
String dcId = map.getParams().get("dcId")!=null?map.getParams().get("dcId").toString():null;
int pageSize = map.getPageSize();
int pageNumber = map.getPageNumber();
QueryMap queryMap = new QueryMap();
queryMap.setPageNum(pageNumber);
queryMap.setCURRENT_ROWS_SIZE(pageSize);
page = ecmcCloudVolumeTypeService.getVolumeTypeList(page,dcId,queryMap);
} catch (Exception e) {
log.error(e.toString(),e);
throw e;
}
return JSONObject.toJSONString(page);
}
@RequestMapping(value = "/updatetype", method = RequestMethod.POST)
@ResponseBody
public String updateVolumeType(HttpServletRequest request, @RequestBody CloudVolumeType cloudVolumeType) throws Exception{
log.info("编辑云硬盘类型开始");
EayunResponseJson json = new EayunResponseJson();
try {
ecmcCloudVolumeTypeService.updateVolumeType(cloudVolumeType);
json.setRespCode(ConstantClazz.SUCCESS_CODE);
ecmcLogService.addLog("编辑", ConstantClazz.LOG_TYPE_VOLUME_TYPE, cloudVolumeType.getVolumeTypeAs(), null, 1, cloudVolumeType.getId(), null);
}catch (AppException e) {
json.setRespCode(ConstantClazz.ERROR_CODE);
log.error(e.toString(),e);
ecmcLogService.addLog("编辑", ConstantClazz.LOG_TYPE_VOLUME_TYPE, cloudVolumeType.getVolumeTypeAs(), null, 0, cloudVolumeType.getId(), e);
throw e;
} catch (Exception e) {
json.setRespCode(ConstantClazz.ERROR_CODE);
log.error(e.toString(),e);
ecmcLogService.addLog("编辑", ConstantClazz.LOG_TYPE_VOLUME_TYPE, cloudVolumeType.getVolumeTypeAs(), null, 0, cloudVolumeType.getId(), e);
throw e;
}
return JSONObject.toJSONString(json);
}
/**
* 启用或停用云硬盘类型
* @param request
* @param cloudVolumeType
* @return
* @throws Exception
*/
@RequestMapping(value = "/changeuse", method = RequestMethod.POST)
@ResponseBody
public String changeUse(HttpServletRequest request, @RequestBody CloudVolumeType cloudVolumeType) throws Exception{
log.info("启用/停用云硬盘类型");
EayunResponseJson json = new EayunResponseJson();
String volTypeName=cloudVolumeType.getVolumeTypeAs();
String isUse=cloudVolumeType.getIsUse();
String operat="启用";
if(null!=isUse&&!"".equals(isUse)){
if("2".equals(isUse)){
operat="停用";
}
}
try {
ecmcCloudVolumeTypeService.changeUse(cloudVolumeType);
json.setRespCode(ConstantClazz.SUCCESS_CODE);
ecmcLogService.addLog(operat, ConstantClazz.LOG_TYPE_VOLUME_TYPE, volTypeName, null, 1, cloudVolumeType.getId(), null);
} catch (Exception e) {
json.setRespCode(ConstantClazz.ERROR_CODE);
log.error(e.toString(),e);
ecmcLogService.addLog(operat, ConstantClazz.LOG_TYPE_VOLUME_TYPE, volTypeName, null, 0, cloudVolumeType.getId(), e);
throw e;
}
return JSONObject.toJSONString(json);
}
}
| true |
bc4a764808e2b681db361e2be044e6e9404e8d21 | Java | ticod/simplog | /src/main/java/com/ticodev/model/dto/BlogType.java | UTF-8 | 600 | 2.234375 | 2 | [
"MIT"
] | permissive | package com.ticodev.model.dto;
/*
블로그 분야 테이블
*/
public class BlogType {
private int btType;
private String btName;
@Override
public String toString() {
return "BlogType{" +
"btType=" + btType +
", btName=" + btName +
'}';
}
public int getBtType() {
return btType;
}
public void setBtType(int btType) {
this.btType = btType;
}
public String getBtName() {
return btName;
}
public void setBtName(String btName) {
this.btName = btName;
}
}
| true |
d8fe91bac22b1de8fda591cc03bddff1251ebac0 | Java | Maryville-SP2018-ISYS-320-1M/computation-with-functions-Salfurhud | /src/PayProgram.java | UTF-8 | 434 | 3.265625 | 3 | [] | no_license | /*
ISYS 320
Name(s):AlfurhudSolomon
Date: Apr1, 2018
*/
public class PayProgram {
public static void main(String[] args) {
double salary = computePay(4, 11);
System.out.println(salary);
}
public static double computePay( double salary, double numOfHours ) {
if(numOfHours > 8) {
return (8 * salary) + ( (1.5 * salary) * ( numOfHours - 8 ) );
} else {
return salary * numOfHours;
}
}
} | true |
1b627ef077e48c7025c0405c445e1da88e56b612 | Java | MauricioPortilla/SistemaGimnasio | /SistemaGimnasio/src/sistemagimnasio/controlador/FXMLSistemaGimnasioController.java | UTF-8 | 3,465 | 2.65625 | 3 | [] | no_license | /**
* Sistema de Gimnasio
* Elaborado por (en orden alfabetico):
* Cruz Portilla Mauricio
* Gonzalez Hernandez Maria Saarayim
* Hernandez Molinos Maria Jose
*
* Mayo, 2019
*/
package sistemagimnasio.controlador;
import java.net.URL;
import java.util.ResourceBundle;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import sistemagimnasio.Empleado;
import sistemagimnasio.EmpleadoDAO;
import sistemagimnasio.Engine;
import sistemagimnasio.IEmpleadoDAO;
/**
* FXMLSistemaGimnasioController es la clase que lleva el control de la interfaz
* FXMLSistemaGimnasio y se encarga del inicio de sesion de los empleados.
*
* @author Mauricio Cruz Portilla
* @version 1.0
* @since 2019/05/18
*/
public class FXMLSistemaGimnasioController {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Button iniciarSesionButton;
@FXML
private PasswordField passwordTextField;
@FXML
private TextField usernameTextField;
private IEmpleadoDAO empleadoDAO = new EmpleadoDAO();
@FXML
void initialize() {
iniciarSesionButton.setOnAction(iniciarSesionButtonHandler());
}
/**
* Lleva a cabo la accion del boton de inicio de sesion, verificando con la base de datos
* si existe el usuario y realizando el inicio de sesion.
*
* @return el evento del boton
*/
private EventHandler<ActionEvent> iniciarSesionButtonHandler() {
return new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (usernameTextField.getText().isEmpty() || passwordTextField.getText().isEmpty()) {
new Alert(AlertType.WARNING, "Debes completar todos los campos.").show();
return;
}
Empleado empleado = empleadoDAO.getEmpleado(
usernameTextField.getText(), passwordTextField.getText()
);
if (empleado.isLoaded()) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource(
"/sistemagimnasio/interfaz/FXMLMenuPrincipal.fxml"
));
Stage stage = new Stage();
stage.setScene(new Scene((AnchorPane) loader.load()));
stage.setTitle("Menú principal - Gimnasio");
stage.show();
Engine.iniciarSesionWindow = iniciarSesionButton.getScene().getWindow();
Engine.empleadoSesion = empleado;
iniciarSesionButton.getScene().getWindow().hide();
} catch (IOException e) {
new Alert(
AlertType.ERROR, "Ocurrió un error al abrir el menú principal."
).show();
System.out.println(e.getMessage());
}
} else {
new Alert(AlertType.ERROR, "Este empleado no existe.").show();
}
}
};
}
}
| true |
5e386662a0c86595aff6d579d64e3f6097db8168 | Java | jesusPA/ProyectoJavaHC_GCraft | /ProyectoJava/src/java/Model/Candidate.java | UTF-8 | 8,243 | 2.578125 | 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 Model;
import Database.Database;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Jepa
*/
public class Candidate {
private int id = -1;
private String firstName;
private String lastName;
private String address;
private String phone;
private String email;
private String title;
private String university;
private String certificates;
private int expectatives;
private String previous;
private int interview;
public Candidate(int id, String firstName, String lastName, String address, String phone,
String email, String title, String university, String certificates,
int expectatives, String previous, int interview) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phone = phone;
this.email = email;
this.title = title;
this.university = university;
this.certificates = certificates;
this.expectatives = expectatives;
this.previous = previous;
this.interview = interview;
}
public static Candidate getCandidate(int id){
Candidate candidate = null;
ResultSet rs = null;
try {
String query = "SELECT * FROM Candidate WHERE id" + Integer.toString(id);
rs = Database.query(query, id);
if (rs.next()){
candidate = new Candidate(
rs.getInt("id"),
rs.getString("firstName"),
rs.getString("lastName"),
rs.getString("address"),
rs.getString("phone"),
rs.getString("email"),
rs.getString("title"),
rs.getString("university"),
rs.getString("certificates"),
rs.getInt("expectatives"),
rs.getString("previous"),
rs.getInt("interview")
);
}
} catch (SQLException ex) {
Logger.getLogger(Candidate.class.getName()).log(Level.SEVERE, null, ex);
}
return candidate;
}
public boolean exists() throws SQLException{
ResultSet rs = null;
try {
String query = "SELECT * FROM Candidate WHERE id" + Integer.toString(this.id);
rs = Database.query(query, this.id);
} catch (SQLException ex) {
Logger.getLogger(Candidate.class.getName()).log(Level.SEVERE, null, ex);
}
return rs.first();
}
public static List<Candidate> all(){
List<Candidate> candidates = new ArrayList<>();
try {
String query = "SELECT * FROM Candidate";
ResultSet rs = Database.query(query);
while(rs.next()) {
Candidate candidate = new Candidate(
rs.getInt("id"),
rs.getString("firstName"),
rs.getString("lastName"),
rs.getString("address"),
rs.getString("phone"),
rs.getString("email"),
rs.getString("title"),
rs.getString("university"),
rs.getString("certificates"),
rs.getInt("expectatives"),
rs.getString("previous"),
rs.getInt("interview")
);
candidates.add(candidate);
}
} catch (SQLException ex) {
Logger.getLogger(Candidate.class.getName()).log(Level.SEVERE, null, ex);
}
return candidates;
}
public boolean save() throws SQLException{
String query;
query = "INSERT INTO Candidate (id, firstName, lastName, address, phone,"
+ " email, title, university, certificates, expectatives, previous, interview)" +
"VALUES ('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d')";
try {
Database.update(query, this.id, this.firstName, this.lastName, this.address,
this.phone, this.email, this.title, this.university, this.certificates, this.expectatives,
this.previous, this.interview);
} catch (SQLException ex) {
Logger.getLogger(Candidate.class.getName()).log(Level.SEVERE, null, ex);
}
return true;
}
public boolean delete(){
try {
String query = "DELETE FROM Candidate WHERE id =" + Integer.toString(this.id);
Database.update(query, id);
return true;
} catch (SQLException ex) {
Logger.getLogger(Candidate.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the university
*/
public String getUniversity() {
return university;
}
/**
* @param university the university to set
*/
public void setUniversity(String university) {
this.university = university;
}
/**
* @return the certificates
*/
public String getCertificates() {
return certificates;
}
/**
* @param certificates the certificates to set
*/
public void setCertificates(String certificates) {
this.certificates = certificates;
}
/**
* @return the expectatives
*/
public int getExpectatives() {
return expectatives;
}
/**
* @param expectatives the expectatives to set
*/
public void setExpectatives(int expectatives) {
this.expectatives = expectatives;
}
/**
* @return the previous
*/
public String getPrevious() {
return previous;
}
/**
* @param previous the previous to set
*/
public void setPrevious(String previous) {
this.previous = previous;
}
/**
* @return the interview
*/
public int getInterview() {
return interview;
}
/**
* @param interview the interview to set
*/
public void setInterview(int interview) {
this.interview = interview;
}
}
| true |
e8c83d4852fe0f43ada874816e4d67678cdbadb5 | Java | prvsh03/springBoot-Project | /StudentTable/src/main/java/com/basic/StudentTable/StudentDetailsController.java | UTF-8 | 827 | 2.375 | 2 | [] | no_license | package com.basic.StudentTable;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentDetailsController {
private final StudentDetailsRepository repository;
StudentDetailsController(StudentDetailsRepository repository){
this.repository = repository;
}
@GetMapping("/getAllStudents")
List<StudentDetails> all(){
return repository.findAll();
}
@PostMapping("/saveStudents")
StudentDetails newStudentDetails(@RequestBody StudentDetails newStudentDetails) {
return repository.save(newStudentDetails);
}
}
| true |
ba6ff04daf345e9830feaf3aa0f1095f3ac0b047 | Java | foryou2030/carbondata | /Molap/Molap-Spark-Interface/src/main/java/com/huawei/datasight/molap/query/MolapQueryPlan.java | UTF-8 | 9,867 | 1.960938 | 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 com.huawei.datasight.molap.query;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.huawei.datasight.molap.query.metadata.MolapDimension;
import com.huawei.datasight.molap.query.metadata.MolapDimensionFilter;
import com.huawei.datasight.molap.query.metadata.MolapLikeFilter;
import com.huawei.datasight.molap.query.metadata.MolapMeasure;
import com.huawei.datasight.molap.query.metadata.MolapMeasureFilter;
import com.huawei.datasight.molap.query.metadata.MolapQueryExpression;
import com.huawei.datasight.molap.query.metadata.TopOrBottomFilter;
import com.huawei.unibi.molap.constants.MolapCommonConstants;
import com.huawei.unibi.molap.engine.aggregator.dimension.DimensionAggregatorInfo;
import com.huawei.unibi.molap.engine.expression.Expression;
/**
* This class contains all the logical information about the query like dimensions,measures,sort order, topN etc..
*/
public class MolapQueryPlan implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -9036044826928017164L;
/**
* Schema name , if user asks select * from datasight.employee. then datasight is the schame name.
* Remains null if the user does not select schema name.
*/
private String schemaName;
/**
* Cube name .
* if user asks select * from datasight.employee. then employee is the cube name.
* It is mandatory.
*/
private String cubeName;
/**
* List of dimensions.
* Ex : select employee_name,department_name,sum(salary) from employee, then employee_name and department_name are dimensions
* If there is no dimensions asked in query then it would be remained as empty.
*/
private List<MolapDimension> dimensions = new ArrayList<MolapDimension>(MolapCommonConstants.CONSTANT_SIZE_TEN);
/**
* List of measures.
* Ex : select employee_name,department_name,sum(salary) from employee, then sum(salary) would be measure.
* If there is no dimensions asked in query then it would be remained as empty.
*/
private List<MolapMeasure> measures = new ArrayList<MolapMeasure>(MolapCommonConstants.CONSTANT_SIZE_TEN);
/**
* List of expressions. Sum(m1+10), Sum(m1)
*/
private List<MolapQueryExpression> expressions = new ArrayList<MolapQueryExpression>(MolapCommonConstants.CONSTANT_SIZE_TEN);
/**
* Map of dimension and corresponding dimension filter.
*/
private Map<MolapDimension, MolapDimensionFilter> dimensionFilters = new HashMap<MolapDimension, MolapDimensionFilter>(MolapCommonConstants.DEFAULT_COLLECTION_SIZE);
private Map<MolapDimension, List<MolapLikeFilter>> dimensionLikeFilters = new HashMap<MolapDimension, List<MolapLikeFilter>>(MolapCommonConstants.DEFAULT_COLLECTION_SIZE);
/**
* Map of measures and corresponding measure filter.
*/
private Map<MolapMeasure, List<MolapMeasureFilter>> measureFilters = new HashMap<MolapMeasure, List<MolapMeasureFilter>>(MolapCommonConstants.DEFAULT_COLLECTION_SIZE);
/**
* Top or bottom filter.
*/
private TopOrBottomFilter topOrBottomFilter;
/**
* Limit
*/
private int limit = -1;
/**
* If it is detail query, no need to aggregate in backend
*/
private boolean detailQuery;
/**
* expression
*/
private Expression expression;
/**
* queryId
*/
private String queryId;
/**
* outLocationPath
*/
private String outLocationPath;
/**
* dimAggregatorInfoList
*/
private Map<String,DimensionAggregatorInfo> dimAggregatorInfos = new LinkedHashMap<String,DimensionAggregatorInfo>();
/**
* isCountStartQuery
*/
private boolean isCountStartQuery;
private List<MolapDimension> sortedDimensions;
/**
* Constructor created with cube name.
* @param cubeName
*/
public MolapQueryPlan(String cubeName)
{
this.cubeName = cubeName;
}
/**
* Constructor created with schema name and cube name.
* @param schemaName
* @param cubeName
*/
public MolapQueryPlan(String schemaName,String cubeName)
{
this.cubeName = cubeName;
this.schemaName = schemaName;
}
/**
* @return the dimensions
*/
public List<MolapDimension> getDimensions()
{
return dimensions;
}
/**
* @param dimensions the dimension to add
*/
public void addDimension(MolapDimension dimension)
{
this.dimensions.add(dimension);
}
/**
* @return the measures
*/
public List<MolapMeasure> getMeasures()
{
return measures;
}
/**
* @param measures the measure to add
*/
public void addMeasure(MolapMeasure measure)
{
this.measures.add(measure);
}
/**
* @return the dimensionFilters
*/
public Map<MolapDimension, MolapDimensionFilter> getDimensionFilters()
{
return dimensionFilters;
}
/**
* @param dimensionFilters the dimensionFilters to set
*/
public void setDimensionFilter(MolapDimension dimension, MolapDimensionFilter dimFilter)
{
this.dimensionFilters.put(dimension, dimFilter);
}
/**
* @param dimensionFilters the dimensionFilters to set
*/
public void setFilterExpression(Expression expression)
{
this.expression=expression;
}
/**
* @param dimensionFilters the dimensionFilters to set
*/
public Expression getFilterExpression()
{
return expression;
}
/**
* @return the measureFilters
*/
public Map<MolapMeasure, List<MolapMeasureFilter>> getMeasureFilters()
{
return measureFilters;
}
/**
* @param measureFilters the measureFilter to set
*/
public void setMeasureFilter(MolapMeasure measure, MolapMeasureFilter measureFilter)
{
List<MolapMeasureFilter> list = measureFilters.get(measure);
if(list == null)
{
list = new ArrayList<MolapMeasureFilter>(MolapCommonConstants.CONSTANT_SIZE_TEN);
this.measureFilters.put(measure, list);
}
list.add(measureFilter);
}
/**
* @return the topOrBottomFilter
*/
public TopOrBottomFilter getTopOrBottomFilter()
{
return topOrBottomFilter;
}
/**
* @param topOrBottomFilter the topOrBottomFilter to set
*/
public void setTopOrBottomFilter(TopOrBottomFilter topOrBottomFilter)
{
this.topOrBottomFilter = topOrBottomFilter;
}
/**
* @return the schemaName
*/
public String getSchemaName()
{
return schemaName;
}
/**
* @return the cubeName
*/
public String getCubeName()
{
return cubeName;
}
/**
* @return the limit
*/
public int getLimit()
{
return limit;
}
/**
* @param limit the limit to set
*/
public void setLimit(int limit)
{
this.limit = limit;
}
/**
* @return the detailQuery
*/
public boolean isDetailQuery()
{
return detailQuery;
}
/**
* @param detailQuery the detailQuery to set
*/
public void setDetailQuery(boolean detailQuery)
{
this.detailQuery = detailQuery;
}
public String getQueryId()
{
return queryId;
}
public void setQueryId(String queryId)
{
this.queryId = queryId;
}
public String getOutLocationPath()
{
return outLocationPath;
}
public void setOutLocationPath(String outLocationPath)
{
this.outLocationPath = outLocationPath;
}
public Map<MolapDimension, List<MolapLikeFilter>> getDimensionLikeFilters()
{
return dimensionLikeFilters;
}
public void setDimensionLikeFilters(MolapDimension dimension, List<MolapLikeFilter> dimFilter)
{
dimensionLikeFilters.put(dimension, dimFilter);
}
public void addAggDimAggInfo(String columnName, String aggType, int queryOrder)
{
DimensionAggregatorInfo dimensionAggregatorInfo = dimAggregatorInfos.get(columnName);
if(null==dimensionAggregatorInfo)
{
dimensionAggregatorInfo = new DimensionAggregatorInfo();
dimensionAggregatorInfo.setColumnName(columnName);
dimensionAggregatorInfo.setOrder(queryOrder);
dimensionAggregatorInfo.addAgg(aggType);
dimAggregatorInfos.put(columnName,dimensionAggregatorInfo);
}
else
{
dimensionAggregatorInfo.setOrder(queryOrder);
dimensionAggregatorInfo.addAgg(aggType);
}
}
public boolean isCountStartQuery()
{
return isCountStartQuery;
}
public void setCountStartQuery(boolean isCountStartQuery)
{
this.isCountStartQuery = isCountStartQuery;
}
public Map<String, DimensionAggregatorInfo> getDimAggregatorInfos()
{
return dimAggregatorInfos;
}
public void removeDimensionFromDimList(MolapDimension dim)
{
dimensions.remove(dim);
}
public void addExpression(MolapQueryExpression expression)
{
expressions.add(expression);
}
public List<MolapQueryExpression> getExpressions()
{
return expressions;
}
public List<MolapDimension> getSortedDimemsions()
{
return sortedDimensions;
}
public void setSortedDimemsions(List<MolapDimension> dims)
{
this.sortedDimensions = dims;
}
}
| true |
8227b8520c27ca00ec434d96586409fdf6dfbce4 | Java | nekolr/saber | /src/main/java/com/nekolr/saber/entity/IdSeq.java | UTF-8 | 475 | 2.0625 | 2 | [] | no_license | package com.nekolr.saber.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import jakarta.persistence.*;
import java.io.Serializable;
@Getter
@Setter
@ToString
@Entity
@Table(name = "id_seq")
public class IdSeq implements Serializable {
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_seq_sequence")
@SequenceGenerator(name = "id_seq_sequence", initialValue = 589, allocationSize = 1)
@Id
private Long id;
}
| true |
8d1aaeb6ba63012db7a035e650baa896a8d9bb84 | Java | pinocchio123/pinocchio-security | /src/main/java/com/pinocchio/security/controller/SysLoginController.java | UTF-8 | 3,836 | 2.140625 | 2 | [] | no_license | /**
* Copyright 2018 人人开源 http://www.renren.io
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.pinocchio.security.controller;
import com.pinocchio.security.model.MenuVo;
import com.pinocchio.security.model.SysUser;
import com.pinocchio.security.service.SysMenuService;
import com.pinocchio.security.util.R;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pinocchio.security.shiro.ShiroUtils;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 登录相关
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年11月10日 下午1:15:31
*/
@Controller
public class SysLoginController {
@Autowired
private SysMenuService sysMenuService;
/**
* 登录
*/
@ResponseBody
@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
public R login(String username, String password) {
try {
Subject subject = ShiroUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
subject.login(token);
} catch (UnknownAccountException e) {
return R.error(e.getMessage());
} catch (IncorrectCredentialsException e) {
return R.error("账号或密码不正确");
} catch (LockedAccountException e) {
return R.error("账号已被锁定,请联系管理员");
} catch (AuthenticationException e) {
return R.error("账户验证失败");
}
return R.ok();
}
/**
* 登录页面
*
* @return
*/
@RequestMapping(value = "/login")
public String login() {
return "login";
}
/**
* 首页跳转
*
* @return
*/
@RequestMapping(value = "/main")
public String main() {
return "main";
}
/**
* 退出
*/
@RequestMapping(value = "logout", method = RequestMethod.GET)
public String logout() {
ShiroUtils.logout();
return "login";
}
/**
* 首页
*
* @return
*/
@RequestMapping(value = "index", method = RequestMethod.GET)
public ModelAndView index(Model model, HttpServletRequest request) {
ModelAndView mv = new ModelAndView("index");
SysUser user = (SysUser) request.getSession().getAttribute("sessionUser");
model.addAttribute("user", user);
mv.addObject(model);
return mv;
}
@RequestMapping("/menu/MenuList")
@ResponseBody
public R MenuList(HttpServletRequest request) {
// SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
SysUser user = (SysUser) request.getSession().getAttribute("sessionUser");
System.out.println("user:" + user.getUserId());
List<MenuVo> menuList = sysMenuService.getUserMenuList(user.getUserId());
return R.ok().put("menuList", menuList);
}
}
| true |
b39fdebc3a223eb1275eee1ea6b7aff25f16403f | Java | eduardo-bm10/Proyecto-1-Datos | /GameScreen/src/shooting/Colision.java | UTF-8 | 1,224 | 3.703125 | 4 | [] | no_license | package shooting;
import display.Display;
import javax.swing.*;
import java.awt.*;
/**
* Clase Colision provee los métodos que verifican el choque entre dos objetos en pantalla.
* Provee un método estático para que sea fácilmente accesible en cualquier otra clase.
*
* @author Alessandro Hidalgo, Javier Tenorio
* @version 1.5
*
* @see java.awt.Rectangle
*/
public class Colision
{
/**
* Verifica si hubo colisión entre dos objetos de tipo JLabel.
* Registra el tamaño de cada objeto en forma de rectángulo por medio de la clase Rectangle.
* Si hubo colisión, además, elimina el objeto 1 de la pantalla.
*
* @author Alessandro Hidalgo, Javier Tenorio
* @param obj1 es el objeto que recibe el impacto del segundo objeto.
* @param obj2 es el objeto que impacta al primer objeto.
* @return boolean
*
* @see javax.swing.JLabel
* @see java.awt.Rectangle
*/
public static boolean checkCollision(JLabel obj1, JLabel obj2)
{
Rectangle r1 = obj1.getBounds();
Rectangle r2 = obj2.getBounds();
if (r1.intersects(r2))
{
Display.panel.remove(obj1);
return true;
}
else{
return false;
}
}
}
| true |
01d99f7bbb7e4adb7ebfedfcb45e04b2f77884f0 | Java | jmtimko5/Voogasalad | /src/engine/Updateable.java | UTF-8 | 523 | 2.875 | 3 | [
"MIT"
] | permissive | package engine;
import util.TimeDuration;
/**
* This interface imposes the behavior of being updateable, specifically in a game loop with a
* defined frame time
*
* @author Joe Timko
* @author Dhrumil Patel
* @author David Maydew
* @author Ryan St.Pierre
* @author Jonathan Im
*
*/
public interface Updateable {
/**
* tells this object to update, informing it also of how much game time has passed since the
* last call.
*
* @param duration since the last frame
*/
void update (TimeDuration duration);
}
| true |
80ed91bd738db8318818e174bd8d6f251a600416 | Java | KoisX/JavaExternalFinalProject | /src/main/java/com/javacourse/test/topic/Topic.java | UTF-8 | 1,276 | 2.75 | 3 | [] | no_license | package com.javacourse.test.topic;
import com.javacourse.shared.dataAccess.Entity;
import javax.validation.constraints.PositiveOrZero;
import javax.validation.constraints.Size;
import java.util.Objects;
/**
* A model class for topic database table
*/
public class Topic implements Entity {
@PositiveOrZero
private long id;
@Size(min = 3, max = 250, message = "{msg.emptyFields}")
private String name;
public Topic(long id, String name) {
this.id = id;
this.name = name;
}
public Topic() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Topic{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Topic)) return false;
Topic topic = (Topic) o;
return id == topic.id &&
name.equals(topic.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
| true |
4742f006ed56c3ac4ad1cd720e59ff58d5e7953e | Java | koreach/Random_Things | /reddit_dailyprogrammer/Intermediate_295.java | UTF-8 | 151 | 1.742188 | 2 | [] | no_license | import java.lang.String;
public class Intermediate_295 {
public static void main(String [] arg) {
}
public int permutations(int n, ) {
}
}
| true |
acec07c293c7d9064adec3d0620e7f590ba51102 | Java | niwatly/SingleDateAndTimePicker | /singledateandtimepicker/src/main/java/com/github/florent37/singledateandtimepicker/widget/LinkableWheelPicker.java | UTF-8 | 226 | 1.890625 | 2 | [
"Apache-2.0"
] | permissive | package com.github.florent37.singledateandtimepicker.widget;
import android.support.annotation.Nullable;
public interface LinkableWheelPicker<T> {
@Nullable public T getGlobalValue();
public void setGlobalValue(T value);
} | true |
40d07d8144b3c192e80ac6a7cc29a11239de440a | Java | code10ftn/building-management | /src/main/java/com/code10/kts/model/dto/SurveyCreateDto.java | UTF-8 | 1,998 | 2.75 | 3 | [
"MIT"
] | permissive | package com.code10.kts.model.dto;
import com.code10.kts.model.domain.Building;
import com.code10.kts.model.domain.Survey;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* Represents a new survey.
*/
public class SurveyCreateDto {
/**
* List of survey questions.
*/
@NotEmpty
private List<QuestionCreateDto> questions;
/**
* Survey's name.
*/
@NotNull
private String name;
/**
* Survey's expiration date.
*/
@NotNull
private Date expirationDate;
public SurveyCreateDto() {
this.questions = new ArrayList<>();
}
public SurveyCreateDto(String name, List<QuestionCreateDto> questions, Date expirationDate) {
this.name = name;
this.questions = questions;
this.expirationDate = expirationDate;
}
/**
* Creates Survey from this DTO
*
* @param building building in which this survey is created
* @return Survey model
*/
public Survey createSurvey(Building building) {
final Survey survey = new Survey();
survey.setName(name);
survey.setQuestions(questions.stream().map(t -> t.createQuestion(survey)).collect(Collectors.toList()));
survey.setExpirationDate(expirationDate);
survey.setBuilding(building);
return survey;
}
public List<QuestionCreateDto> getQuestions() {
return questions;
}
public void setQuestions(List<QuestionCreateDto> questions) {
this.questions = questions;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | true |
036c6f82eabe0ba77ede491cf0fca2a66c2ffd55 | Java | hundoy/ursoavg | /core/src/com/urso/avg/graphics/TxtLayer.java | UTF-8 | 3,609 | 2.34375 | 2 | [] | no_license | package com.urso.avg.graphics;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Align;
import com.urso.avg.UrsoAvgGame;
/**
* Created by hundoy on 2016/7/18.
*/
public class TxtLayer extends PicLayer {
public final static int PRIORITY_RATE = 1000;
private Rectangle txtRect;
private float lineSpace = 2;
private boolean nowait = false;
private float interTime = 0.05f;
private float scaleX = 1f;
private float scaleY = 1f;
// ctrl variables
private String curText = "";
private int blockStartIndex = 0;
private int textIndex = 0;
private String command = "";
public TxtLayer(UrsoAvgGame g, int priority, String uname) {
super(g, priority, uname);
}
/**
* draw text
*/
public void draw() {
game.font.color(Color.RED);
game.font.draw(txtRect.getX(), txtRect.getY());
}
public Rectangle getTxtRect() {
return txtRect;
}
public void setTxtRect(Rectangle txtRect) {
this.txtRect = txtRect;
}
public float getLineSpace() {
return lineSpace;
}
public void setLineSpace(float lineSpace) {
this.lineSpace = lineSpace;
}
public boolean isNowait() {
return nowait;
}
public void setNowait(boolean nowait) {
this.nowait = nowait;
}
public float getInterTime() {
return interTime;
}
public void setInterTime(float interTime) {
this.interTime = interTime;
}
public String getCurText() {
return curText;
}
public void setCurText(String curText) {
this.curText = curText;
textIndex = 0;
blockStartIndex = 0;
}
public void addCurText(String addText){
curText += addText;
}
public int getTextIndex() {
return textIndex;
}
public void setTextIndex(int textIndex) {
this.textIndex = textIndex;
}
public void nextTextIndex(){
this.textIndex++;
if (textIndex>=curText.length()){
// reach text end
// game.logic.stopSay();
} else{
// check whether get out of region or meet stop command
String curWord = "";
boolean isCommand = false;
char curChar = curText.charAt(textIndex);
if (curChar=='\\' && textIndex!=curText.length()-1){
textIndex++;
curWord = String.valueOf(curChar) + String.valueOf(curText.charAt(textIndex));
isCommand = true;
command = curWord;
} else{
curWord = String.valueOf(curChar);
command = "";
}
if (isCommand){
if (command.equalsIgnoreCase("\\l")){
// game.logic.waitAction(LogicCtrl.WAIT_CLICK);
} else if (curWord.equalsIgnoreCase("\\p")){
// next block
blockStartIndex = textIndex+1;
}
} else{
String msg = curText.substring(blockStartIndex, textIndex+1);
float preHeight = game.font.preDrawText(msg, txtRect.width, Align.left);
Gdx.app.debug("text", msg+" ("+preHeight+")");
if (preHeight>txtRect.height){
textIndex--;
// game.logic.waitAction(LogicCtrl.WAIT_CLICK);
}
}
}
}
public void afterWait() {
if (command.length()>0){
}
nextTextIndex();
}
}
| true |
35a946fc6da22a4c0bb67e48791130983976f78e | Java | Bot-Benedict/CZ2002-OODP | /SS4-grp4/src/moblima/view/BaseMenu.java | UTF-8 | 956 | 2.9375 | 3 | [] | no_license | package moblima.view;
import moblima.controller.*;
/**
* Represents the home page.
*/
public class BaseMenu extends View {
/**
* Instantiates a new Base menu.
*
* @param userType the user type
* @param nextView the next view
*/
public BaseMenu(int userType, View nextView) {
super("baseMenu", userType, nextView);
}
/**
* Display the view.
*/
public void display() {
outputPageName("Welcome to MOBLIMA!");
System.out.println(
"(1) Admin\n"
+ "(2) Movie-goer\n"
+ "(3) Quit");
while (true) {
int input = getChoice("Please select an option: ");
if (input == 1) {
View nextView = new LoginVerification(0, null);
Navigation.goTo(new ChooseCineplex(0, nextView));
break;
} else if (input == 2) {
Navigation.goTo(new MoviegoerMenu(1, null));
break;
} else if (input == 3) {
Navigation.exit();
} else {
System.out.println("\nPlease enter a valid input!\n");
}
}
}
}
| true |
7e025c677edc2c2f325c07d852fe43bf920cf5a6 | Java | Ana-Vi/Homework | /Computador/Computador.java | UTF-8 | 1,564 | 3.078125 | 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 pkg202001;
/**
*
* @author avbvi
*/
public class Computador {
String nomeComputador;
String processador;
String placaMae;
String placaDeVideo;
double preco;
Computador(String nC, String pro, String pM, String pV, double p){
this.nomeComputador=nC;
this.placaDeVideo=pV;
this.placaMae=pM;
if(p<0){
this.preco=0;
}else{
this.preco=p;
}
this.processador=pro;
}
@Override
public String toString(){
return "Nome: "+this.nomeComputador+
".\nPlaca Vídeo: "+this.placaDeVideo+
".\nPlaca Mãe: "+this.placaMae+
".\nProcessador: "+this.processador+
".\nPreço: "+String.format("%.2f",this.preco)+
".\n\n";
}
//método que não retorna nada
public void aplicaDesconto(int porcentagem){
double aux=this.preco*(100-porcentagem)/100;
this.preco=aux;
}
/*
//metodo que retorna o desconto
public double calculaDesconto(int porcentagem){
double aux=this.preco*(porcentagem)/100;
return aux;
}*/
/*
//método que retorna um double
public double aplicaValorizacao(int porcentagem){
double aux=this.preco*(100+porcentagem)/100;
this.preco=aux;
return this.preco;
}*/
}
| true |
ca8927929ae6238db2651c43397d59bdcf95959a | Java | SocialHui/Java17 | /回文串/Solution.java | UTF-8 | 726 | 3.484375 | 3 | [] | no_license | public class Solution {
public boolean isPalindrome(String s) {
String str = s.toLowerCase();
int left = 0;
int right = s.length()-1;
while (left < right) {
char ch1 = str.charAt(left);
char ch2 = str.charAt(right);
if (Character.isLetterOrDigit(ch1) && Character.isLetterOrDigit(ch2)) {
if (ch1 != ch2) {
return false;
}
left++;
right--;
}
if (!Character.isLetterOrDigit(ch1)){
left++;
}
if (Character.isLetterOrDigit(ch2)){
right--;
}
}
return true;
}
}
| true |
91f8aec27694c4f12491ef2c3fd9016731915834 | Java | apache/cassandra | /src/java/org/apache/cassandra/hints/package-info.java | UTF-8 | 2,294 | 1.9375 | 2 | [
"Apache-2.0",
"MIT",
"CC0-1.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | 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.
*/
/**
* Hints subsystem consists of several components.
*
* {@link org.apache.cassandra.hints.Hint} encodes all the required metadata and the mutation being hinted.
*
* {@link org.apache.cassandra.hints.HintsBuffer} provides a temporary buffer for writing the hints to in a concurrent manner,
* before we flush them to disk.
*
* {@link org.apache.cassandra.hints.HintsBufferPool} is responsible for submitting {@link org.apache.cassandra.hints.HintsBuffer}
* instances for flushing when they exceed their capacity, and for maitaining a reserve {@link org.apache.cassandra.hints.HintsBuffer}
* instance, and creating extra ones if flushing cannot keep up with arrival rate.
*
* {@link org.apache.cassandra.hints.HintsWriteExecutor} is a single-threaded executor that performs all the writing to disk.
*
* {@link org.apache.cassandra.hints.HintsDispatchExecutor} is a multi-threaded executor responsible for dispatch of
* the hints to their destinations.
*
* {@link org.apache.cassandra.hints.HintsStore} tracks the state of all hints files (written and being written to)
* for a given host id destination.
*
* {@link org.apache.cassandra.hints.HintsCatalog} maintains the mapping of host ids to {@link org.apache.cassandra.hints.HintsStore}
* instances, and provides some aggregate APIs.
*
* {@link org.apache.cassandra.hints.HintsService} wraps the catalog, the pool, and the two executors, acting as a front-end
* for hints.
*/
package org.apache.cassandra.hints;
| true |
3cceab6857b7822811e5216099af3d7a468b8f0a | Java | cash2one/fmps | /trunk/fmps-web/src/main/java/cn/com/fubon/fo/repairplatform/entity/response/GiftSetInstructionsResponse.java | UTF-8 | 337 | 1.703125 | 2 | [] | no_license | package cn.com.fubon.fo.repairplatform.entity.response;
import cn.com.fubon.fo.repairplatform.entity.BaseResult;
public class GiftSetInstructionsResponse extends BaseResult {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| true |
c50cf6d312855c1254e5636f84b973f3a681da4f | Java | rjit987/lambdatest_amazon | /src/main/java/pages/SearchResultPage.java | UTF-8 | 2,438 | 2.5 | 2 | [] | no_license | package pages;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import utilities.CreateTextFile;
import utilities.MapSortingDec;
public class SearchResultPage {
WebDriver driver;
public SearchResultPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(css = "#brandsRefinements")
WebElement brandsBox;
public SearchResultPage selectBrand(String brand) throws IOException {
List<WebElement> brandNames = brandsBox.findElements(By.cssSelector(".a-size-base.a-color-base"));
for (WebElement name : brandNames) {
if (name.getText().contains(brand)) {
name.click();
break;
}
}return new SearchResultPage(driver);
}
@FindBy(css = ".a-pagination")
WebElement pagination;
public void pagination() {
}
@FindBy(css = ".s-main-slot.s-result-list.s-search-results.sg-row")
WebElement allSearchItems;
@FindBy(css = ".a-size-medium.a-color-base.a-text-normal")
WebElement brandsName;
public void getProductDetails() {
HashMap<String, Integer> map = new HashMap<String, Integer>();
List<WebElement> allPrice = allSearchItems.findElements(By.cssSelector(".a-price-whole"));
List<WebElement> allName = allSearchItems
.findElements(By.cssSelector(".a-size-medium.a-color-base.a-text-normal"));
for (int i = 0; i < allPrice.size(); i++) {
// System.out.println(allName.get(i).getText()+" "+allPrice.get(i).getText());
String[] a = allPrice.get(i).getText().split(",");
String c = "";
for (String b : a) {
c = c + b;
}
map.put(allName.get(i).getText(), Integer.parseInt(c));
}
MapSortingDec sortMap = new MapSortingDec();
Map<String, Integer> hm1 = MapSortingDec.sortByValue(map);
// print the sorted hashmap
for (Map.Entry<String, Integer> en : hm1.entrySet()) {
//print in console
System.out.println("Key = " + en.getKey() + ", Value = " + en.getValue());
// Printing to text file
CreateTextFile c = new CreateTextFile();
c.createTextFile(("Key = " + en.getKey() + ", Value = " + en.getValue()));
}
}
}
| true |
c95877b0b5ecd8c4a977c0f04ff1839805b826bf | Java | puklu/UniformSeleniumProject | /Selenium-Automation-Elearning-Framework-TestNG/tests/com/training/sanity/tests/UFM_006_ChangePwd.java | UTF-8 | 2,122 | 2.390625 | 2 | [] | no_license | package com.training.sanity.tests;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.training.generics.ScreenShot;
import com.training.pom.ChangePwd_POM;
import com.training.pom.LoginForUser_POM;
import com.training.utility.DriverFactory;
import com.training.utility.DriverNames;
//Test to change the password for a user
public class UFM_006_ChangePwd {
//variables
private WebDriver driver;
private String baseUrl;
private LoginForUser_POM loginToApp;
private ChangePwd_POM UFM_006_changePwdPOM;
private static Properties properties;
private ScreenShot screenShot;
@BeforeClass
public static void setUpBeforeClass() throws IOException {
properties = new Properties();
FileInputStream inStream = new FileInputStream("./resources/others.properties");
properties.load(inStream);
}
@BeforeMethod
public void setUp() throws Exception {
driver = DriverFactory.getDriver(DriverNames.CHROME);
UFM_006_changePwdPOM = new ChangePwd_POM(driver);
loginToApp = new LoginForUser_POM(driver);
baseUrl = properties.getProperty("baseURL");
screenShot = new ScreenShot(driver);
// open the browser
driver.get(baseUrl);
}
@AfterTest
public void tearDown() throws Exception {
Thread.sleep(1000);
driver.quit();
}
@Test
public void changePassword() {
//logging to the app first using LoginForUser_POM
loginToApp.loginUser("batsy@cave.com", "ghi@123");
//calling methods from ChangePwd_POM to change the password
UFM_006_changePwdPOM.findOptionToChange();
UFM_006_changePwdPOM.newPassword("jkl@123");
UFM_006_changePwdPOM.confirmPassword("jkl@123");
UFM_006_changePwdPOM.clickContinueBtn();
UFM_006_changePwdPOM.assertTheChange();
UFM_006_changePwdPOM.printNewPassword();
}
}
| true |
ce570b325652d604678d00bc687366150c2dc148 | Java | BaibaKondratjeva/demoOnlineStore | /src/main/java/com/example/demo/onlineshop/orders/OrdersProductsTable.java | UTF-8 | 1,164 | 2.34375 | 2 | [] | no_license | package com.example.demo.onlineshop.orders;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class OrdersProductsTable {
private long id;
private String imageUri;
private String name;
private Integer quantity;
private BigDecimal price;
private Integer totalSum;
public Integer getTotalSum() {
return totalSum;
}
public void setTotalSum(Integer totalSum) {
this.totalSum = totalSum;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getImageUri() {
return imageUri;
}
public void setImageUri(String imageUri) {
this.imageUri = imageUri;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
| true |
61189e7b424cef828a0e472753da28466f9555f1 | Java | easonlong/Kepler-All | /src/main/java/com/kepler/queue/QueueRunnable.java | UTF-8 | 117 | 1.78125 | 2 | [] | no_license | package com.kepler.queue;
/**
* @author KimShen
*
*/
public interface QueueRunnable {
public void running();
}
| true |
ac736f10e5e7a317a5a71d521b49f78aced1d0d5 | Java | LearnLib/learnlib | /algorithms/active/discrimination-tree/src/test/java/de/learnlib/algorithms/discriminationtree/DTLearnerDFAIT.java | UTF-8 | 2,225 | 1.976563 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | /* Copyright (C) 2013-2023 TU Dortmund
* This file is part of LearnLib, http://www.learnlib.de/.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.learnlib.algorithms.discriminationtree;
import de.learnlib.algorithms.discriminationtree.dfa.DTLearnerDFABuilder;
import de.learnlib.api.oracle.MembershipOracle.DFAMembershipOracle;
import de.learnlib.counterexamples.LocalSuffixFinder;
import de.learnlib.counterexamples.LocalSuffixFinders;
import de.learnlib.testsupport.it.learner.AbstractDFALearnerIT;
import de.learnlib.testsupport.it.learner.LearnerVariantList.DFALearnerVariantList;
import net.automatalib.words.Alphabet;
import org.testng.annotations.Test;
@Test
public class DTLearnerDFAIT extends AbstractDFALearnerIT {
private static final boolean[] BOOLEAN_VALUES = {false, true};
@Override
protected <I> void addLearnerVariants(Alphabet<I> alphabet,
int targetSize,
DFAMembershipOracle<I> mqOracle,
DFALearnerVariantList<I> variants) {
DTLearnerDFABuilder<I> builder = new DTLearnerDFABuilder<>();
builder.setAlphabet(alphabet);
builder.setOracle(mqOracle);
for (boolean epsilonRoot : BOOLEAN_VALUES) {
builder.setEpsilonRoot(epsilonRoot);
for (LocalSuffixFinder<? super I, ? super Boolean> suffixFinder : LocalSuffixFinders.values()) {
builder.setSuffixFinder(suffixFinder);
String name = "epsilonRoot=" + epsilonRoot + ",suffixFinder=" + suffixFinder.toString();
variants.addLearnerVariant(name, builder.create());
}
}
}
}
| true |
34e1a5af811c947fc6d4c0e0d4d52703f37fda9a | Java | wenhao543/sell | /src/test/java/com/wenhao/SBRedisTest.java | UTF-8 | 1,048 | 1.835938 | 2 | [] | no_license | package com.wenhao;
import java.math.BigDecimal;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.wenhao.form.OrderMaster;
import com.wenhao.mapper.OrderMasterMapper;
import com.wenhao.service.RedisService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SBRedisTest {
Logger logger = LoggerFactory.getLogger(SBRedisTest.class);
@Autowired
private RedisService redisService;
@Before
public void init(){
/*OrderMaster orderMaster = (OrderMaster) orderMasterMapper.selectByPrimaryKey("201710041933232345");*/
}
@Test
public void get(){
//logger.info(string);
}
@Test
public void add(){
redisService.set("springboot", "springboot4redis");
}
@Test
public void del(){
redisService.del("springboot");
}
}
| true |
3e72527480eaf5f626bf7d6b55db6269aa8cef7a | Java | ravinduu/Service-Throttle-Web | /Service-Throttle-Backend/service-throttle-backend/src/main/java/com/servicethrottle/servicethrottlebackend/controllers/UserController.java | UTF-8 | 4,861 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package com.servicethrottle.servicethrottlebackend.controllers;
import com.servicethrottle.servicethrottlebackend.models.Customer;
import com.servicethrottle.servicethrottlebackend.models.MobileMechanic;
import com.servicethrottle.servicethrottlebackend.models.Supervisor;
import com.servicethrottle.servicethrottlebackend.models.UserCredentials;
import com.servicethrottle.servicethrottlebackend.models.dto.AdminDetailsDto;
import com.servicethrottle.servicethrottlebackend.models.dto.UserDetailsDto;
import com.servicethrottle.servicethrottlebackend.services.*;
import lombok.AllArgsConstructor;
import org.dom4j.util.UserDataElement;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/st")
@AllArgsConstructor
@CrossOrigin("*")
public class UserController {
/**
* TO-DO
* implement remove user by himself (delete account)
* */
private final UserService userService;
private final AuthorityService authorityService;
private final AdminService adminService;
private final SupervisorService supervisorService;
private final CustomerService customerService;
private final MobileMechanicService mobileMechanicService;
@GetMapping("/users")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public ResponseEntity<List<UserCredentials>> getAllUsers(){
return ResponseEntity.ok().body(userService.getAllUsers());
}
@GetMapping("/authorities")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public ResponseEntity<List<String>> getAllAuthorities(){
return ResponseEntity.ok().body(authorityService.getAllAuthorities());
}
@GetMapping("/users/admin")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public ResponseEntity<List<UserDetailsDto>> getAllAdmins(){
return ResponseEntity.ok().body(adminService.getAllAdmins());
}
@GetMapping("/users/supervisor")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_SUPERVISOR')")
public ResponseEntity<List<UserDetailsDto>> getAllSupervisors(){
return ResponseEntity.ok().body(supervisorService.getAllSupervisors());
}
@GetMapping("/users/mobile-mechanic")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_SUPERVISOR')")
public ResponseEntity<List<UserDetailsDto>> getAllMobileMechanics(){
return ResponseEntity.ok().body(mobileMechanicService.getAllMobileMechanics());
}
@GetMapping("/users/customer")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_SUPERVISOR')")
public ResponseEntity<List<UserDetailsDto>> getAllCustomers(){
return ResponseEntity.ok().body(customerService.getAllCustomers());
}
/**
* get details of a admin
*
* parameter username use to fetch info from db
* ROLE_ADMIN requires
* return {userDetailsDto} details of admin
* */
@GetMapping("/user/admin/{username}")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public ResponseEntity<UserDetailsDto> getAdmin(@PathVariable String username){
return ResponseEntity.ok().body(adminService.getAdmin(username));
}
/**
* get details of a supervisor
*
* parameter username use to fetch info from db
* ROLE_ADMIN requires
* return {userDetailsDto} details of supervisor
* */
@GetMapping("/user/supervisor/{username}")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public ResponseEntity<UserDetailsDto> getSupervisor(@PathVariable String username){
return ResponseEntity.ok().body(supervisorService.getSupervisor(username));
}
/**
* get details of a mobile-mechanic
*
* parameter username use to fetch info from db
* ROLE_ADMIN, ROLE_SUPERVISOR, ROLE_MM or ROLE_CUSTOMER requires
* return {userDetailsDto} details of MM
* */
@GetMapping("/user/mobile-mechanic/{username}")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_SUPERVISOR','ROLE_MOBILEMECHANIC','ROLE_CUSTOMER')")
public ResponseEntity<MobileMechanic> getMobileMechanic(@PathVariable String username){
return ResponseEntity.ok().body(mobileMechanicService.getMobileMechanic(username));
}
/**
* get details of a customer
*
* parameter username use to fetch info from db
* ROLE_ADMIN, ROLE_SUPERVISOR or ROLE_MM requires
* return {userDetailsDto} details of customer
* */
@GetMapping("/user/customer/{username}")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_SUPERVISOR','ROLE_MOBILEMECHANIC')")
public ResponseEntity<Customer> getCustomer(@PathVariable String username){
return ResponseEntity.ok().body(customerService.getCustomer(username));
}
}
| true |
549ab7b61f3cef1c4a233e841b28a77fc972e22d | Java | raeffu/prog2-i18n | /src/internationalizedFrameAppl/Person.java | UTF-8 | 1,265 | 3.046875 | 3 | [
"MIT"
] | permissive | package internationalizedFrameAppl;
@SuppressWarnings("rawtypes")
public final class Person implements Comparable{
private String firstName, lastName, city, country;
public Person(String firstName, String lastName, String city, String country) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.city = city;
this.country = country;
}
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public String getCity() {return city;}
public void setCity(String city) {this.city = city;}
public String getCountry() {return country;}
public void setCountry(String country) {this.country = country;}
public int compareTo(Object o) {
Person p = (Person)o;
if(lastName.compareTo(p.lastName)==0) return firstName.compareTo(p.firstName);
return lastName.compareTo(p.lastName);
}
public String toString(){return lastName+" "+firstName+" "+city+" "+country;}
public boolean equals(Object o){
Person p= (Person)o;
if(lastName.equals(p.lastName)) return firstName.equals(p.firstName);
else return lastName.equals(p.lastName);
}
}
| true |
64eb1be4c505b441dba7a525eed45ac7790eaa34 | Java | halarotu/WorkingHours | /src/main/java/ha/controller/EmployeeController.java | UTF-8 | 1,589 | 2.296875 | 2 | [] | no_license | package ha.controller;
import ha.domain.Employee;
import ha.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private EmployeeRepository emplRepo;
@Autowired
private PasswordEncoder passwordEncoder;
@RequestMapping(method = RequestMethod.GET)
public String getEmployees(Model model) {
model.addAttribute("employees", this.emplRepo.findAll());
return "employees";
}
@RequestMapping(method = RequestMethod.POST)
public String addNewEmployee(@RequestParam String name, @RequestParam String level) {
Employee e = new Employee();
e.setName(name);
e.setAuthorityLevel(level);
e.setPassword(passwordEncoder.encode(name));
this.emplRepo.save(e);
return "redirect:/employees";
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String getEmployee(Model model, @PathVariable Long id) {
model.addAttribute("employee", emplRepo.findOne(id));
return "employee";
}
} | true |
5415a9bc1a1eef8e8f77d7d417d0e14e8ca750cf | Java | P79N6A/icse_20_user_study | /methods/Method_2047.java | UTF-8 | 939 | 2.40625 | 2 | [] | no_license | /**
* Utility method which adds optional configuration to ImageRequest
* @param imageRequestBuilder The Builder for ImageRequest
* @param config The Config
*/
public static void addOptionalFeatures(ImageRequestBuilder imageRequestBuilder,Config config){
if (config.usePostprocessor) {
final Postprocessor postprocessor;
switch (config.postprocessorType) {
case "use_slow_postprocessor":
postprocessor=DelayPostprocessor.getMediumPostprocessor();
break;
case "use_fast_postprocessor":
postprocessor=DelayPostprocessor.getFastPostprocessor();
break;
default :
postprocessor=DelayPostprocessor.getMediumPostprocessor();
}
imageRequestBuilder.setPostprocessor(postprocessor);
}
if (config.rotateUsingMetaData) {
imageRequestBuilder.setRotationOptions(RotationOptions.autoRotateAtRenderTime());
}
else {
imageRequestBuilder.setRotationOptions(RotationOptions.forceRotation(config.forcedRotationAngle));
}
}
| true |
2eec4a9921a70d31b952ca1659ab76079eadd3fe | Java | liuyun073/wzd | /src/main/java/com/liuyun/site/service/impl/UserLogServiceImpl.java | UTF-8 | 1,486 | 2.0625 | 2 | [] | no_license | package com.liuyun.site.service.impl;
import com.liuyun.site.dao.UserLogDao;
import com.liuyun.site.domain.UserLog;
import com.liuyun.site.model.PageDataList;
import com.liuyun.site.model.SearchParam;
import com.liuyun.site.service.UserLogService;
import com.liuyun.site.tool.Page;
import java.util.List;
public class UserLogServiceImpl implements UserLogService {
private UserLogDao userLogDao;
public UserLogDao getUserLogDao() {
return this.userLogDao;
}
public void setUserLogDao(UserLogDao userLogDao) {
this.userLogDao = userLogDao;
}
public void addLog(UserLog userLog) {
this.userLogDao.addUserLog(userLog);
}
public int getLogCountByUserId(long userId, SearchParam param) {
return this.userLogDao.getLogCountByUserId(userId, param);
}
public List getLogListByUserId(long userId, int start, int end,
SearchParam param) {
return this.userLogDao.getLogListByUserId(userId, start, end, param);
}
public int getLogCountByParam(SearchParam param) {
return this.userLogDao.getLogCountByParam(param);
}
public List getLogListByParams(int start, int end, SearchParam param) {
return this.userLogDao.getLogListByParams(start, end, param);
}
public PageDataList getUserLogList(int currentPage, SearchParam param) {
int total = this.userLogDao.getLogCountByParam(param);
Page p = new Page(total, currentPage);
List list = this.userLogDao.getLogListByParams(p.getStart(), p
.getPernum(), param);
return new PageDataList(p, list);
}
} | true |
7fe52b236f7f3f75642dba28dee7748731e7c1f0 | Java | 452693688/NetWork | /app/src/main/java/com/network/common/net/source/SourceTask.java | UTF-8 | 4,756 | 2.21875 | 2 | [] | no_license | package com.network.common.net.source;
import android.text.TextUtils;
import com.network.common.net.connect.URLConnectionBase;
import com.ui.utiles.other.DLog;
import com.ui.utiles.other.JSONUtile;
import org.apache.http.util.ByteArrayBuffer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.zip.GZIPInputStream;
/**
* Created by Administrator on 2016/1/14.
*/
public class SourceTask<T extends AbstractRequestData<?>> implements Runnable {
private int responseCode;
private String responseMsg;
private OnRequestBack onRequestBack;
private T requestData;
private byte[] request;
private final String TAG = "SourceTask";
public SourceTask(OnRequestBack onRequestBack, T requestData) {
this.onRequestBack = onRequestBack;
this.requestData = requestData;
}
private byte[] postMethod() {
try {
HttpURLConnection urlConn = (HttpURLConnection) URLConnectionBase.getURLConnection(requestData.getUrl());
// 设置为Post请求
urlConn.setRequestMethod("POST");
//设置重定向
urlConn.setInstanceFollowRedirects(true);
// 开始连接
urlConn.connect();
// 发送请求参数
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
String str = "";
str = requestData.getDataStr();
if (TextUtils.isEmpty(str)) {
Object data = requestData.getData();
str = JSONUtile.obj2String(data);
}
str="{\"channel\":\"21\",\"oper\":\"127.0.0.1\",\"random\":\"6806\",\"sign\":\"dcec6e810c683bc0a165a302fe629d34\",\"spid\":\"1001\",\"token\":\"TOKEN_f6e46ef5594a41b59642643fcd9acc20\",\"limit\":\"30\",\"page\":0,\"deptId\":null,\"docFamousConsultStatus\":null,\"docPicConsultStatus\":null,\"docVideoConsultStatus\":null,\"hosId\":null,\"service\":\"nethos.doc.list\"}";
DLog.e("请求:", str);
dos.write(str.getBytes());
dos.flush();
dos.close();
// 判断请求是否成功
responseCode = urlConn.getResponseCode();
responseMsg = urlConn.getResponseMessage();
if (responseCode != 200) {
return null;
}
// 读取数据
/** 判断是否是GZIP **/
boolean isGzipEncoding = false;
String contentEncoding = urlConn.getContentEncoding();
if (!TextUtils.isEmpty(contentEncoding)) {
if (contentEncoding.contains("gzip")) {
isGzipEncoding = true;
}
}
DLog.e("请求gzip:" , isGzipEncoding);
byte[] readBuffer = new byte[1024];
ByteArrayBuffer buffer = null;
InputStream input = urlConn.getInputStream();
// 如果是GZIP压缩
if (isGzipEncoding) {
GZIPInputStream inPutStream = new GZIPInputStream(input);
int size = (inPutStream.available());
buffer = new ByteArrayBuffer(size);
int len = 0;
while ((len = inPutStream.read(readBuffer)) != -1) {
buffer.append(readBuffer, 0, len);
}
inPutStream.close();
} else {
//非GZIP压缩
int size = (input.available());
buffer = new ByteArrayBuffer(size);
int len = 0;
while ((len = input.read(readBuffer)) != -1) {
buffer.append(readBuffer, 0, len);
}
input.close();
}
request = str.getBytes();
return buffer.toByteArray();
} catch (IOException ioe) {
responseMsg = ioe.getMessage();
responseCode = 400;
return null;
}
}
@Override
public void run() {
byte[] result = postMethod();
if (result == null) {
DLog.e("请求失败:" + responseCode, responseMsg);
onRequestBack.onFailed(responseCode, responseMsg);
return;
}
DLog.e("请求成功:" + responseCode, new String(result));
onRequestBack.onSucess(responseCode, responseMsg, result, request);
}
public interface OnRequestBack {
/**
* 成功
*
* @param bytes 成功返回值
*/
void onSucess(int responseCode, String responseMsg, byte[] bytes, byte[] request);
/**
* 失败
*/
void onFailed(int responseCode, String responseMsg);
}
}
| true |
fdf480f81e33550b283a6dff36e9f460d6f5440d | Java | Karavanych/GrainKingdom | /src/draziw/karavan/grainkingdom/baseclass/Corn.java | WINDOWS-1251 | 3,918 | 2.234375 | 2 | [] | no_license | package draziw.karavan.grainkingdom.baseclass;
import android.app.Activity;
import android.text.style.ForegroundColorSpan;
import draziw.karavan.grainkingdom.GameState;
import draziw.karavan.grainkingdom.R;
import draziw.karavan.grainkingdom.supportclass.mySpannableString;
public class Corn {
/* --
p ('^^ : ', Corn.total, ' .');
p ('^ : ', Corn.seed, ' .');
p ('^: ', Corn.harvest, ' .');
if (Corn.land >= 0) then
p ('^ : ', Corn.land, ' .');
else
p ('^ : ', Corn.land, ' .');
end
p ('^ : ', Corn.ships, ' .');
p ('^ : ', Corn.food, ' .');
p ('^ : ', Corn.war, ' .');
p ('^ : ', Corn.thiefs, ' .');
p ('^ : ', Corn.rats, ' .');
p ('^ : ', Corn.fee, ' .');
p ('^ : ', Corn.science, ' .');
p ('^: ', Corn.spoiled, ' .');
p ('^: ', Corn.bonus, ' .');
p ('^/ : ', Corn.deal, ' .');
p ('^ : ', Corn.yield, ' /.');
p ('^ : ', Corn.now, ' .');*/
public long total=0;
public long seed=0;
public long harvest=0;
public long land=0;
public long ships=0;
public long food=0;
public long war=0;
public long thiefs=0;
public long rats=0;
public long fee=0;
public long science=0;
public long spoiled=0;
public long bonus=0;
public long deal=0;
public long yield=0;
public long now=0;
public Corn() {
}
/* public mySpannableString reports(Activity cc) {
String recstr = cc.getResources().getString(R.string.cornreports);
recstr=String.format(recstr,total,seed,harvest,land>0?land:0,land<0?-land:0,ships,food,war,thiefs,rats,fee,science,spoiled,bonus,deal,yield,now);
mySpannableString msps=new mySpannableString(recstr);
//msps.setSpanToLine(new ForegroundColorSpan(cc.getResources().getColor(R.color.titleTextColor)),2, 0, 0, 0);
return msps;
}*/
public String fillReportVars(String ss) {
return String.format(ss,total,seed,harvest,land>0?land:0,land<0?-land:0,ships,food,war,thiefs,rats,fee,science,spoiled,bonus,deal,yield,now);
}
public void newYear() {
/* -- Corn
if (Epidemy.bugs == 0) then
tmp = math.random (3);
Corn.yield = tmp + 2 + math.floor (Science.land/3);
else
Corn.yield = 0;
end
if not isSow then
Corn.yield = 0;
end
Corn.now = Corn.now + Corn.harvest;
Corn.now = Corn.now + Corn.bonus;
Corn.now = Corn.now - Corn.rats;
Corn.now = Corn.now - Corn.spoiled;
Corn.now = Corn.now - Corn.thiefs;*/
if (0==GameState.epidemy.bugs) {
yield=(int) (GameState.getRandom(3)+2+Math.floor(GameState.science.land/3f));
} else yield=0;
if (!GameState.isSow) yield=0;
//
now = now + harvest;
now = now + bonus;
now = now - rats;
now = now - spoiled;
now = now - thiefs;
}
public void svernut() {
seed=0;
harvest=0;
land=0;
ships=0;
food=0;
war=0;
thiefs=0;
rats=0;
fee=0;
science=0;
spoiled=0;
bonus=0;
deal=0;
total=now;
}
}
| true |
77f4585e093c761888cf490d8e5bd86935b4e044 | Java | cmokbel/temporary | /GWTOpenLayers/gwtopenlayers-gwt-openlayers-1d8f2a30c137/gwt-openlayers-client/src/main/java/org/gwtopenmaps/openlayers/client/control/NavigationHistoryImpl.java | UTF-8 | 1,411 | 1.898438 | 2 | [
"Apache-2.0"
] | permissive | package org.gwtopenmaps.openlayers.client.control;
import org.gwtopenmaps.openlayers.client.util.JSObject;
/**
*
* @author giuseppe
*
*/
public class NavigationHistoryImpl
{
public static native JSObject create() /*-{
return new $wnd.OpenLayers.Control.NavigationHistory();
}-*/;
public static native JSObject create(JSObject options) /*-{
return new $wnd.OpenLayers.Control.NavigationHistory(options);
}-*/;
public static native void previous(JSObject self) /*-{
self.previous.trigger();
}-*/;
public static native void next(JSObject self) /*-{
self.next.trigger();
}-*/;
public static native void limit(JSObject self, int limit) /*-{
self.limit = limit;
}-*/;
public static native void autoActivate(JSObject self, boolean autoActivate) /*-{
self.autoActivate = autoActivate;
}-*/;
public static native JSObject nextTrigger(JSObject self) /*-{
return self.nextTrigger();
}-*/;
public static native JSObject getPrevious(JSObject self) /*-{
return self.previous;
}-*/;
public static native JSObject getNext(JSObject self) /*-{
return self.next;
}-*/;
public static native void previousTrigger(JSObject self) /*-{
self.previousTrigger();
}-*/;
public static native void clear(JSObject self) /*-{
self.clear();
}-*/;
}
| true |
2c30987329a66d90fd1064f822fe6767780a355d | Java | hemoura12/youblog | /youblog/src/main/java/org/kh/youblog/comment/model/vo/Comment.java | UTF-8 | 1,697 | 2.1875 | 2 | [] | no_license | package org.kh.youblog.comment.model.vo;
public class Comment implements java.io.Serializable {
private final static long serialVersionUID = 12L;
private String cmtno;
private String blogno;
private String memberid;
private String cmtparentno;
private String cmtcontents;
private String state;
public Comment() {}
public Comment(String cmtno, String blogno, String memberid, String cmtparentno, String cmtcontents, String state) {
super();
this.cmtno = cmtno;
this.blogno = blogno;
this.memberid = memberid;
this.cmtparentno = cmtparentno;
this.cmtcontents = cmtcontents;
this.state = state;
}
public String getCmtno() {
return cmtno;
}
public void setCmtno(String cmtno) {
this.cmtno = cmtno;
}
public String getBlogno() {
return blogno;
}
public void setBlogno(String blogno) {
this.blogno = blogno;
}
public String getMemberid() {
return memberid;
}
public void setMemberid(String memberid) {
this.memberid = memberid;
}
public String getCmtparentno() {
return cmtparentno;
}
public void setCmtparentno(String cmtparentno) {
this.cmtparentno = cmtparentno;
}
public String getCmtcontents() {
return cmtcontents;
}
public void setCmtcontents(String cmtcontents) {
this.cmtcontents = cmtcontents;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "Comment [cmtno=" + cmtno + ", blogno=" + blogno + ", memberid=" + memberid + ", cmtparentno="
+ cmtparentno + ", cmtcontents=" + cmtcontents + ", state=" + state + "]";
}
}
| true |
fe93b124e21d53e53d518ff5ef1632cc3a6c1876 | Java | dangfugui/note | /note-other/src/main/java/dang/jdk/thread/MaxThroead.java | UTF-8 | 1,867 | 3.3125 | 3 | [] | no_license | package dang.jdk.thread;
import java.util.Random;
/**
* Created by dangqihe on 2017/2/18.
*/
public class MaxThroead {
public long count = 0;
public Boolean alive = true;
public static void main(String[] args) throws InterruptedException {
MaxThroead maxThroead = new MaxThroead();
int throeadCount = 100;
while (true) {
for (int i = 0; i < 100; i++) {
Producer producer = new Producer(maxThroead);
Thread thread = new Thread(producer);
thread.start();
}
long start = System.currentTimeMillis();
Random rand = new Random();
Thread.sleep(1000);
long end = System.currentTimeMillis();
long avg = ((maxThroead.count) / (end - start));
System.out.print("throeadCount:" + throeadCount + ":" + avg);
for (int i = 0; i < (maxThroead.count / (throeadCount * 5)); i++) {
System.out.print("*");
}
System.out.println(avg * throeadCount);
if (throeadCount < 10000) {
throeadCount += 100;
} else {
maxThroead.alive = false;
return;
}
maxThroead.count = 0;
}
}
}
class Producer implements Runnable {
MaxThroead maxThroead;
public Producer(MaxThroead maxThroead) {
this.maxThroead = maxThroead;
}
public void run() {
while (maxThroead.alive) {
work();
maxThroead.count++;
}
}
private void work() {
double i = Math.pow(1.245, 456.2545);
i = Math.pow(i, i);
Random rand = new Random();
try {
Thread.sleep(rand.nextInt(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true |
382a0b82e7556766d1831ef5baed7f20d754e30f | Java | thirosan/walmartTest_project | /tests/src/test/java/tests/walmart/step/IntegrationStep2.java | UTF-8 | 702 | 2.21875 | 2 | [] | no_license | package tests.walmart.step;
import cucumber.api.java.pt.Então;
import cucumber.api.java.pt.Quando;
import tests.walmart.page.CartPage;
import tests.walmart.page.LoginPage;
import static org.junit.Assert.assertTrue;
public class IntegrationStep2 {
private CartPage cartPage = new CartPage();
private LoginPage loginPage = new LoginPage();
@Quando("^o usuário finaliza a compra do produto$")
public void o_usuário_finaliza_a_compra_do_produto() throws Throwable {
cartPage.finishBuy();
}
@Então("^a página de login é apresentada$")
public void a_página_de_login_é_apresentada() throws Throwable {
assertTrue(loginPage.isWindowLoginExists());
}
} | true |
77c847d277c221de0149b32a826bc69500357700 | Java | TarunRahuja/Java-Programs | /practice/SplitArray.java | UTF-8 | 746 | 3.3125 | 3 | [] | no_license | package practice;
import java.util.*;
public class SplitArray {
static int count;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int []arr = new int[n];
for(int i = 0; i<n; i++)
{
arr[i] = sc.nextInt();
}
split(arr,0, "", "",0, 0);
System.out.println(count);
}
public static void split(int []arr,int vidx,String one, String two,int sum1,int sum2)
{
if(vidx==arr.length)
{
if(sum1==sum2)
{
System.out.print(one+"and ");
System.out.println(two);
count++;
return;
}
else
return;
}
split(arr,vidx+1,one+arr[vidx]+" ",two,sum1+arr[vidx],sum2);
split(arr, vidx+1, one, two+arr[vidx]+" ", sum1, sum2+arr[vidx]);
}
}
| true |
5b2097856d766c071756b423ca6bf2a133f5ffab | Java | ymsyms/InventorySystem | /InventorySystem-Team5/src/main/java/sg/edu/iss/inventory/service/TransactionHistoryServiceImpl.java | UTF-8 | 682 | 2.21875 | 2 | [] | no_license | package sg.edu.iss.inventory.service;
import java.util.*;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sg.edu.iss.inventory.model.TransactionDetail;
import sg.edu.iss.inventory.repository.TransactionDetailRepository;
@Service
public class TransactionHistoryServiceImpl implements TransactionHistoryService{
@Resource
TransactionDetailRepository transRepo;
@Override
@Transactional
public ArrayList<TransactionDetail> findTransactionDetails(String partNo,Date startDate,Date endDate)
{
return transRepo.findTransactionsByPartNo(partNo,startDate,endDate);
}
}
| true |
9f7a3e832a7d80598766640304798bcd1f23731b | Java | dsachdeva1/testAssignment | /app/src/main/java/com/example/deepak/uberassignment/viewmodel/GetImageViewModel.java | UTF-8 | 856 | 2.171875 | 2 | [] | no_license | package com.example.deepak.uberassignment.viewmodel;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import com.example.deepak.uberassignment.model.ImageItem;
import com.example.deepak.uberassignment.repository.ImageRepository;
import java.util.List;
public class GetImageViewModel extends ViewModel {
// Here communication between Repository, View MOdel & asyncTask can be happened through listers..
private ImageRepository imgRepository;
public GetImageViewModel() {
imgRepository = new ImageRepository();
}
public MutableLiveData<List<ImageItem>> getImgLiveList(String text) {
return imgRepository.getImgLiveList(text);
}
public void loadMoreData(String text, boolean loadNewData, int page) {
imgRepository.loadMoreData(text,loadNewData, page+1);
}
}
| true |
47204e4386a2fa7eb84e2bc82eeacbc9b79a7816 | Java | armaandev/sheconomyapp | /app/src/main/java/com/sheconomy/sheeconomy/Network/services/AddToCartApiInterface.java | UTF-8 | 549 | 2.046875 | 2 | [] | no_license | package com.sheconomy.sheeconomy.Network.services;
import com.sheconomy.sheeconomy.Network.response.AddToCartResponse;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;
public interface AddToCartApiInterface {
@Headers("Content-Type: application/json")
@POST("carts/add")
Call<AddToCartResponse> sendAddToCartRequest(@Header("Authorization") String authHeader, @Body JsonObject jsonObject);
}
| true |
68cd820bb660af2db1fd60efa7b5461ff14851c6 | Java | Xiezimiao/designer | /src/cn/edu/zjut/action/DesignerAction.java | UTF-8 | 1,672 | 2.4375 | 2 | [] | no_license | package cn.edu.zjut.action;
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
import cn.edu.zjut.po.Designer;
import cn.edu.zjut.po.Example;
import cn.edu.zjut.service.DesignerService;
import cn.edu.zjut.service.ExampleService;
public class DesignerAction extends ActionSupport {
private Example example;
private Designer designer;
// 封装上传文件属性
private File[] upload;
private File[] upload2;
public File[] getUpload() {return upload;}
public void setUpload(File[] upload) {this.upload = upload;}
public File[] getUpload2() {return upload2;}
public void setUpload2(File[] upload2) {this.upload2 = upload2;}
public Example getExample() {return example;}
public void setExample(Example example) {this.example = example;}
public Designer getDesigner() {return designer;}
public void setDesigner(Designer designer) {this.designer = designer;}
public String upload() throws Exception {
DesignerService designerServ = new DesignerService();
if (designerServ.upload(designer,example,upload,upload2))
return "uploadSucccess";
else
return "uploadFail";
}
public String viewExampleDetails()
{
DesignerService designerServ = new DesignerService();
if(designerServ.viewExampleDetails(designer, example))
return "viewSuccess";
else
return "viewFail";
}
public String execute()
{
DesignerService designerServ=new DesignerService();
if(designerServ.putDesigner(designer))
return "myself";
else
return"others";
}
public String judgeIdentity()
{
DesignerService designerServ=new DesignerService();
if(designerServ.judgeIdentity())
return "designer";
else
return "employer";
}
}
| true |
7b009cbc8fc08b71fd66c6e75790ac2dca2be6ae | Java | gonzalouli/dss2020-2021-GonJeDav | /Core/src/main/java/com/jedago/practica_dss/persistance/OrdersRepositoryOnMemory.java | UTF-8 | 1,336 | 2.796875 | 3 | [
"MIT"
] | permissive | package com.jedago.practica_dss.persistance;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import com.jedago.practica_dss.core.Order;
public class OrdersRepositoryOnMemory implements OrdersRepository {
List<Order> orders;
@Override
public List<Order> findAll() throws Exception {
return orders;
}
@Override
public Optional<Order> findById(String id) {
boolean found = false;
Order seekOrder = null, order;
Iterator<Order> i = orders.iterator();
while(i.hasNext() && !found)
{
order = i.next();
if(order.getId_order().equals(id))
{
seekOrder = order;
found = true;
}
}
if(found)
return Optional.of(seekOrder);
else
return Optional.empty();
}
@Override
public void save(List<Order> orderList) throws Exception {
this.orders = orderList;
}
@Override
public void add(Order o) throws Exception {
this.orders.add(o);
}
@Override
public void delete(List<Order> orderList) throws Exception {
this.orders.removeAll(orderList);
}
@Override
public void delete(Order o) throws Exception {
this.orders.remove(o);
}
@Override
public void update(String id, Order o) throws Exception {
Optional<Order> toUpdate = this.findById(id);
if(!toUpdate.isPresent())
{
this.delete(toUpdate.get());
this.add(o);
}
}
}
| true |
6687213e897213ab3aea6b4b5f98691bd3614b77 | Java | sangjiexun/20191031test | /chintai-migration-cms/src/net/chintai/backend/sysadmin/shop_bukken/service/bean/ShopListingDeleteConfirmInServiceBean.java | UTF-8 | 2,018 | 2.21875 | 2 | [] | no_license | package net.chintai.backend.sysadmin.shop_bukken.service.bean;
/**
* 店舗リスティング設定削除確認
*
* @author
* @version $Revision: $ Copyright: (C) CHINTAI Corporation All Right Reserved.
*/
public class ShopListingDeleteConfirmInServiceBean {
/** 店舗コード */
private String shopCd;
/** 契約コード */
private String keiyakuCd;
/** 契約サブコード */
private String keiyakuSubCd;
/** 削除する適用月リスト */
private String[] delFlgList;
/**
* shopCdを返します。
*
* @return shopCd
*/
public String getShopCd() {
return shopCd;
}
/**
* を設定します。
*
* @param shopCd
* shopCd
*/
public void setShopCd(String shopCd) {
this.shopCd = shopCd;
}
/**
* keiyakuCdを返します。
*
* @return keiyakuCd
*/
public String getKeiyakuCd() {
return keiyakuCd;
}
/**
* を設定します。
*
* @param keiyakuCd
* keiyakuCd
*/
public void setKeiyakuCd(String keiyakuCd) {
this.keiyakuCd = keiyakuCd;
}
/**
* keiyakuSubCdを返します。
*
* @return keiyakuSubCd
*/
public String getKeiyakuSubCd() {
return keiyakuSubCd;
}
/**
* を設定します。
*
* @param keiyakuSubCd
* keiyakuSubCd
*/
public void setKeiyakuSubCd(String keiyakuSubCd) {
this.keiyakuSubCd = keiyakuSubCd;
}
/**
* 削除する適用月リストを取得します。
*
* @return 削除する適用月リスト
*/
public String[] getDelFlgList() {
return delFlgList;
}
/**
* 削除する適用月リストを設定します。
*
* @param delFlgList
* 削除する適用月リスト
*/
public void setDelFlgList(String[] delFlgList) {
this.delFlgList = delFlgList;
}
}
| true |
12e2880ef5218ab03fd3245e3bc04e797a41f840 | Java | zoozooll/MyExercise | /meep/MeepLib/src/com/oregonscientific/meep/message/common/MsmReportAppVersion.java | UTF-8 | 1,117 | 2.234375 | 2 | [
"Apache-2.0"
] | permissive | package com.oregonscientific.meep.message.common;
public class MsmReportAppVersion extends MeepServerMessage {
private String appName = null;
private int versionCode = 0;
private String versionName = null;
private long firstInstallTime = 0;
private long lastUpdateTime = 0;
public MsmReportAppVersion(String proc, String opcode) {
super(proc, opcode);
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getVersionCode() {
return versionCode;
}
public void setVersionCode(int versionCode) {
this.versionCode = versionCode;
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public long getFirstInstallTime() {
return firstInstallTime;
}
public void setFirstInstallTime(long firstInstallTime) {
this.firstInstallTime = firstInstallTime;
}
public long getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(long lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
}
| true |
00c535ef445e52328b9786c029bebaf8c5e14feb | Java | jakesig/dsa2019-2020 | /Circular Queue/CircularQueue.java | UTF-8 | 1,423 | 3.484375 | 3 | [] | no_license | import java.util.ArrayList;
public class CircularQueue {
public Node thisNode;
private Node lastNode;
private int size;
public CircularQueue(int size) {
thisNode = new Node(1);
Node current = thisNode;
for (int i = 1; i < size; i++) {
current.next = new Node(i+1);
current = current.next;
}
this.size = size;
current.next = thisNode;
}
@Override public String toString() {
String toReturn = "";
Node current = thisNode;
while (current.next!=null) {
toReturn += current.nodeID + "\n";
current = current.next;
}
return toReturn;
}
public int execute() {
Node current = thisNode;
while (size!=1) {
current.next = current.next.next;
current = current.next;
size--;
}
return current.nodeID;
}
}
class Node {
public int nodeID;
public Node next;
public boolean hasSword;
public Node(int obj) {
this.nodeID = obj;
}
@Override public String toString() {
return ""+nodeID;
}
public static void main(String[] args) {
//Tester Code
CircularQueue list = new CircularQueue(0);
for (int i = 1; i < 100; i++) {
list = new CircularQueue(i);
System.out.println(i+": "+list.execute());
}
}
}
| true |
70f77bfc1ab121fe8477e9ff8a2d25a1d32e9842 | Java | da-ferreira/poo-java | /POO-CC3A/test/aula_15_interface/BankTestFile.java | UTF-8 | 2,506 | 2.921875 | 3 | [
"MIT"
] | permissive |
package aula_15_interface;
import org.junit.Test;
import static org.junit.Assert.*;
import Aula_15_Interface.Bank;
import Aula_15_Interface.SavingsAccount;
/**
* @author daferreira
*/
public class BankTestFile {
@Test
public void testeConstrutor() {
Bank banco = new Bank("entrada4.txt");
assertEquals(10, banco.size());
assertNotNull(banco);
}
@Test
public void testeSavingsAccount() {
Bank banco = new Bank("entrada4.txt");
assertEquals(2045, banco.getAccounts().get(2).getAccountNumber());
assertEquals(1890.0, banco.getAccounts().get(2).getBalance(),0.01); // Poupança
assertTrue(banco.getAccounts().get(2) instanceof SavingsAccount);
}
@Test
public void sortTest(){
Bank banco = new Bank("entrada4.txt");
banco.sortBalanceDecreasing();
assertEquals(531, banco.getAccounts().get(9).getAccountNumber());
assertEquals(388.0, banco.getAccounts().get(9).getBalance(),0.01); // Taxa = 3.0
assertEquals(2062, banco.getAccounts().get(8).getAccountNumber()); // 400,00
assertEquals("Guilherme Freitas", banco.getAccounts().get(0).getOwner());
}
@Test
public void regularAccountsTest(){
Bank banco = new Bank("entrada4.txt");
banco.sortBalanceDecreasing();
assertEquals(2, banco.regularAccounts().size());
assertEquals(2062, banco.regularAccounts().get(1).getAccountNumber());
assertEquals("Regina Celia", banco.regularAccounts().get(0).getOwner());
}
@Test
public void savingsAccountsTest(){
Bank banco = new Bank("entrada4.txt");
banco.sortBalanceDecreasing();
assertEquals(2, banco.savingsAccounts().size());
assertEquals(2045, banco.savingsAccounts().get(0).getAccountNumber());
assertEquals("Vinicius Lopes", banco.savingsAccounts().get(1).getOwner());
}
@Test
public void lawAccountsTest(){
Bank banco = new Bank("entrada4.txt");
banco.sortBalance();
assertEquals(6, banco.lawAccounts().size());
assertEquals(531, banco.lawAccounts().get(0).getAccountNumber());
}
@Test
public void getAccountTypeTest(){
Bank banco = new Bank("entrada4.txt");
assertEquals(10, banco.getAccounts().size());
assertEquals("CLA", banco.getAccountType(banco.getAccounts().get(0)));
}
}
| true |
9a5adf202ce170ba4706c9e840148ad7dc299a45 | Java | InhoAndrewJung/SpringLevel1 | /spring07_aop/src/api1/MessageAdvice.java | UHC | 1,027 | 3.453125 | 3 | [] | no_license | package api1;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/*
* Cross Cutting Concern ִ ̽ Ŭ
* ::
* TARGET CLASS Ͻ ȣǸ
* ̰ ͼ MessageAdvice ̺Ʈ ؼ
* invoke() ȣ
* ᱹ Ͻ DZ invoke() ȴ.
*/
public class MessageAdvice implements MethodInterceptor{
public Object invoke(MethodInvocation invocation) throws Throwable {
//Ͻ Ǵ ...
System.out.println("1.Ͻ Ǵ ...");
Object obj = invocation.proceed(); // -> Ͻ ȣȴ.
if(obj!=null) {
System.out.println("target ϰ :: "+obj);
}
//Ͻ Ŀ Ǵ
System.out.println("2. Ͻ Ŀ Ǵ ");
return obj;
}
}
| true |
b11873cf56e0fa7eab8aafcbdab084edc3b9d765 | Java | TWSSYesterday/WoodMachine | /src/de/chillupx/commands/Command_WoodMachine.java | UTF-8 | 2,220 | 2.84375 | 3 | [] | no_license | package de.chillupx.commands;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import de.chillupx.WoodMachine;
import de.chillupx.machine.Machine;
public class Command_WoodMachine implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(sender instanceof ConsoleCommandSender) {
sender.sendMessage("This command is only for players!");
return true;
}
Player player = (Player) sender;
if(args.length == 0) {
player.sendMessage(" ");
player.sendMessage(ChatColor.GOLD + "--------------- Your WoodMachines ---------------");
List<Machine> machines = WoodMachine.getDatabaseHandler().getWoodMachines(player);
if(machines == null || machines.size() == 0) {
player.sendMessage(ChatColor.YELLOW + "You dont have any WoodMachines.");
return true;
}
int i = 1;
for(Machine m : machines) {
player.sendMessage(ChatColor.GOLD + "#"+ i + ChatColor.YELLOW + " @(world="+ m.getDispenser().getWorld().getName() +" / x=" + m.getDispenser().getLocation().getBlockX() + " / y=" + m.getDispenser().getLocation().getBlockY() + " / z=" + m.getDispenser().getLocation().getBlockZ() + ")");
i++;
}
player.sendMessage(" ");
return true;
}
else if(args.length == 1 && args[0].equalsIgnoreCase("create")) {
if(!player.hasPermission("woodmachine.create")) {
player.sendMessage(ChatColor.RED + "You do not have permissios!");
return true;
}
WoodMachine.getMachineCreator().placeMode(player);
player.sendMessage(" ");
player.sendMessage(ChatColor.GOLD + "--------------- WoodMachine Creator ---------------");
player.sendMessage(ChatColor.YELLOW + "You are now in the WoodMachine creation mode.");
player.sendMessage(" ");
player.sendMessage(ChatColor.GOLD + "Next step:");
player.sendMessage(ChatColor.YELLOW + " Place a dispenser to create the WoodMachine");
player.sendMessage(" ");
return true;
}
return false;
}
}
| true |
887da190f2d6ef6a14fb33a84935a3d3a2ee6d1e | Java | pooi/HappyCake | /app/src/main/java/tk/twpooi/happycake/BaseActivity.java | UTF-8 | 902 | 1.976563 | 2 | [
"Apache-2.0"
] | permissive | package tk.twpooi.happycake;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import com.tsengvn.typekit.Typekit;
import com.tsengvn.typekit.TypekitContextWrapper;
/**
* Created by tw on 2017. 2. 3..
*/
public class BaseActivity extends AppCompatActivity {
public static String Bareun1 = "font/BareunDotumOTFPro1.otf";
public static String Bareun2 = "font/BareunDotumOTFPro2.otf";
public static String Bareun3 = "font/BareunDotumOTFPro3.otf";
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(TypekitContextWrapper.wrap(newBase));
}
public void setFont(TextView view, String fontName){
view.setTypeface(Typeface.createFromAsset(getAssets(), Bareun1));
}
}
| true |