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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3b2a7704e3ecc321ac76be888f938e36a92b9605 | Java | siorekoskar/OpenChat | /src/chat/model/Database.java | UTF-8 | 4,322 | 2.828125 | 3 | [] | no_license | package chat.model;
import javax.xml.transform.Result;
import java.sql.*;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Created by Oskar on 08/01/2017.
*/
public class Database{
//////////////////FIELDS//////////////////////////////////////
private List<User> users;
private Connection conn;
//////////////////CONSTRUCTORS////////////////////////////////
public Database(){
users = new LinkedList<>();
}
//////////////////METHODS/////////////////////////////////////
public List<User> getUsers(){
return Collections.unmodifiableList(users);
}
public void removeUser(int index){
users.remove(index);
}
public void addUser(User user){
users.add(user);
}
///////////DO
public void connect() throws Exception{
if(conn!=null){
return;
}
try{
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException e){
throw new Exception("Driver not found");
}
String url = "jdbc:mysql://localhost:3306/user";
conn = DriverManager.getConnection(url, "root", "shihtzu1");
System.out.println("Connected: " + conn);
}
public void disconnect(){
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
System.out.println("Cant close connection");
}
}
}
public boolean checkIfUserExists(User user) throws SQLException{
String login = user.getLogin();
String checkIfExistsSql = "select count(*) as count from user where login = '"
+ login+"'";
PreparedStatement checkStmt = conn.prepareStatement(checkIfExistsSql);
/* int id = user.getId();
checkStmt.setInt(1, id);*/
ResultSet checkResult = checkStmt.executeQuery();
checkResult.next();
int count = checkResult.getInt(1);
System.out.println("znaleziono:" +count);
return (count != 0);
}
public void save() throws SQLException{
String checkSql = "Select count(*) as count from user where id=?";
PreparedStatement checkStmt = conn.prepareStatement(checkSql);
String insertSql = "insert into user (login, password) values (?,?)";
PreparedStatement insertStmt = conn.prepareStatement(insertSql);
String updateSql = "update user set login=?, password=? where id = ?";
PreparedStatement updateStmt = conn.prepareStatement(updateSql);
for(User user: users){
int id = user.getId();
String login = user.getLogin();
String password = user.getPass();
checkStmt.setInt(1, id);
ResultSet checkResult = checkStmt.executeQuery();
checkResult.next();
int count = checkResult.getInt(1);
if(count == 0){
System.out.println("Inserting person with ID " + id);
int col = 1;
insertStmt.setInt(col, id);
insertStmt.setString(col++, login);
insertStmt.setString(col++, password);
insertStmt.executeUpdate();
}
else {/*
System.out.println("Updating person with ID" + id);
int col = 1;
updateStmt.setString(col++, login);
updateStmt.setString(col++, password);
updateStmt.setInt(col++, id);
updateStmt.executeUpdate();*/
}
}
}
public void load() throws SQLException{
users.clear();
String sql = "select id, login, password from user order by id";
Statement selectStmt = conn.createStatement();
ResultSet results = selectStmt.executeQuery(sql);
while(results.next()){
int id = results.getInt("id");
String login = results.getString("login");
String password = results.getString("password");
User user = new User(id, login, password);
users.add(user);
System.out.println(user);
}
results.close();
selectStmt.close();
}
/////////DO
}
| true |
1d9a4ac14195632b0456688b18df2d345bd18379 | Java | shuiliuxing/MyJava | /src/main/java/org/bing/learn/book/设计/设计模式/代理/Proxy.java | UTF-8 | 512 | 3.078125 | 3 | [] | no_license | package org.bing.learn.book.设计.设计模式.代理;
public class Proxy implements Subject{
private RealSubject realSubject;
@Override
public void request(){
if(realSubject==null){
realSubject=new RealSubject();
}
preRequest();
realSubject.request();
postRequest();
}
public void preRequest(){
System.out.println("预处理......");
}
public void postRequest(){
System.out.println("处理后......");
}
}
| true |
6f218ae3d83410c10d0a1808dd07fe1acae19b23 | Java | skysaver00/Java | /Hello_World/src/Hello.java | UTF-8 | 161 | 1.992188 | 2 | [] | no_license | public class Hello {
public static void main(String[] args) {
System.out.println("Hello World");
System.out.println("Hello Young Woo Kim");
}
}
| true |
569976298c81afa24b1f1d9e4f9e04142267c510 | Java | code-aspirant/spark-template-engines | /spark-template-handlebars/src/test/java/spark/template/handlebars/HandlebarsTemplateEngineTest.java | UTF-8 | 2,041 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | package spark.template.handlebars;
import com.github.jknack.handlebars.Helper;
import org.junit.Before;
import org.junit.Test;
import spark.ModelAndView;
import java.io.File;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HandlebarsTemplateEngineTest {
private HandlebarsTemplateEngine hte;
@Before
public void setup() throws Exception {
hte = new HandlebarsTemplateEngine();
}
@Test
public void render() throws Exception {
String templateVariable = "Hello Handlebars!";
Map<String, Object> model = new HashMap<>();
model.put("message", templateVariable);
String expected = String.format("<h1>%s</h1>", templateVariable);
String actual = hte.render(new ModelAndView(model, "hello.hbs"));
assertEquals(expected, actual);
}
@Test
public void helperShouldBeRegistered() throws Exception {
String name = "stringHelper";
Helper<String> helper = (s, options) -> options.equals(s);
hte.registerHelper(name, helper);
assertTrue(hte.handlebars.helper(name).equals(helper));
}
@Test
public void helpersShouldBeRegistered() throws Exception {
File file = Paths.get(ClassLoader.getSystemResource("helpers/test.js").toURI()).toFile();
int initialHelperCount = hte.handlebars.helpers().size();
hte.registerHelpers(file);
assertTrue(hte.handlebars.helper("test") != null);
assertTrue(hte.handlebars.helpers().size() == initialHelperCount + 2);
}
@Test
public void helperShouldOutputDateToView() throws Exception {
Helper<LocalDate> helper = (s, options) -> LocalDate.now();
hte.registerHelper("today", helper);
String actual = hte.render(new ModelAndView(null, "helper_test.hbs"));
assertTrue(actual.equals("Today is " + LocalDate.now().toString()));
}
} | true |
39ad939e7c64f5a3a8585784dfadd3c95147b412 | Java | grazielags/cp12 | /Reginei/Módulo 4/Java/AulaJava/src/Aula1/Exercicio8.java | WINDOWS-1250 | 748 | 3.859375 | 4 | [] | no_license | package Aula1;
import javax.swing.JOptionPane;
public class Exercicio8 {
public static void main(String[] args) {
/*
* 8. Escrever um programa em que leia dois valores para as variveis A e B, e
* efetuar as trocas dos valores de forma que a varivel A passe a possuir o
* valor da varivel B e a varivel B passe a possuir o valor da varivel A.
* Apresentar os valores trocados.
*/
int A = 0;
int B = 0;
int C = 0;
A = Integer.parseInt(JOptionPane.showInputDialog("Digite um Valor para A: "));
B = Integer.parseInt(JOptionPane.showInputDialog("Digite um Valor para B: "));
C = A;
A = B;
B = C;
JOptionPane.showMessageDialog(null, "A = " + A + "\n B = " + B);
}
}
| true |
4799cd141dc3723b2e2270d0d376226080b4b8c0 | Java | Krulvis/OSBotScripts | /GeneralStoreBuyer/src/generalstoreseller/GeneralStoreSeller.java | UTF-8 | 7,592 | 2.09375 | 2 | [] | no_license | package generalstoreseller;
import api.ATScript;
import api.ATState;
import api.event.listener.inventory.InventoryListener;
import api.util.ATPainter;
import api.util.Timer;
import api.util.gui.GUIWrapper;
import generalstoreseller.states.Buying;
import generalstoreseller.states.Selling;
import generalstoreseller.states.Starting;
import generalstoreseller.util.GUI;
import generalstoreseller.util.SellableItem;
import generalstoreseller.util.SellableItems;
import org.osbot.rs07.api.def.ItemDefinition;
import org.osbot.rs07.api.map.Position;
import org.osbot.rs07.api.model.Item;
import org.osbot.rs07.api.ui.Message;
import org.osbot.rs07.listener.MessageListener;
import org.osbot.rs07.script.ScriptManifest;
import java.awt.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Properties;
/**
* Created by Krulvis on 16-Feb-17.
*/
@ScriptManifest(name = "GeneralStoreSeller", author = "Krulvis", version = 1.04D, logo = "", info = "")
public class GeneralStoreSeller extends ATScript implements InventoryListener {
public static int[] startSellables = {
56,
58,
62,
64,
805,
829,
830,
847,
851,
881,
892,
1517,
1519,
1635,
1660,
1654,
1673,
1692,
2357,
2568,
4542,
11069,
19580,
};
public SellableItems sellables;
public boolean restockWhenOneGone = false;
public int startWorld = -1;
public int turnOver = 0, costs = 0;
public Timer firstWorldTimer = null;
public boolean loadGUI = true;
public int restockAmount = 200;
public Position shopTile = new Position(2466, 3285, 0);
public Buying buyingState;
@Override
public void onStart() {
timer = new Timer();
//setPrivateVersion();
String param = getParameters();
if (param != null) {
if (param.contains("load")) {
System.out.println("Found parameter LOAD");
loadGUI = false;
}
}
}
public void loadSettings() {
System.out.println("Loading settings using params");
sellables = new SellableItems(this);
try {
File file = new File(getSettingsFolder() + "settings.properties");
Properties p = new Properties();
p.load(new FileReader(file));
restockWhenOneGone = Boolean.parseBoolean(p.getProperty("quick_restock", "true"));
System.out.println("Restock when out of one: " + restockWhenOneGone);
restockAmount = Integer.parseInt(p.getProperty("restock_amount", "200"));
System.out.println("Restock amount: " + restockAmount);
//Initiate standard
for (int i = 0; i < GeneralStoreSeller.startSellables.length; i++) {
int id = GeneralStoreSeller.startSellables[i];
sellables.addSellable(new SellableItem(id, restockAmount, this));
}
for (String key : p.stringPropertyNames()) {
if (key.contains("item_")) {
String prop = p.getProperty(key);
if (prop != null) {
try {
int id = Integer.parseInt(prop.contains(",") ? prop.substring(0, prop.indexOf(",")) : prop);
int amount = prop.contains(",") ? Integer.parseInt(prop.substring(prop.indexOf(",") + 1)) : restockAmount;
SellableItem si = new SellableItem(id, amount, this);
System.out.println("Added custom: " + si.getId() + ", " + si.getAmount());
sellables.addSellable(si);
} catch (NumberFormatException e) {
System.out.println("Wrong number format: " + prop);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
sellables.reCheckSellables();
}
@Override
public void update() {
}
@Override
protected void initialize(LinkedList<ATState> statesToAdd) {
statesToAdd.add(new Starting(this));
statesToAdd.add(buyingState = new Buying(this));
statesToAdd.add(new Selling(this));
}
@Override
protected Class<? extends ATPainter> getPainterClass() {
return Painter.class;
}
@Override
protected Class<? extends GUIWrapper> getGUI() {
return loadGUI ? GUI.class : null;
}
public Item[] getInvSellables() {
Item[] invItems = inventory.getItems();
ArrayList<Item> invSellables = new ArrayList<>();
for (Item i : invItems) {
if (i == null) {
continue;
}
ItemDefinition def = i.getDefinition();
if (def != null && isSellable(def)) {
invSellables.add(i);
}
}
return invSellables.toArray(new Item[invSellables.size()]);
}
public Item getSellable() {
Item[] items = inventory.getItems();
for (Item i : items) {
if (i == null) {
continue;
}
ItemDefinition def = ItemDefinition.forId(i.getId());
if (def != null && isSellable(def) && hasPlaceInShop(def) && shop.amountOf(def.isNoted() ? def.getId() - 1 : def.getId()) < 5) {
//System.out.println("Can still sell: " + def.getName() + ": " + i.getID());
return i;
}
}
return null;
}
private boolean hasPlaceInShop(ItemDefinition def) {
final int itemId = def.getUnnotedId();
return !shop.isFull() || shop.contains(itemId);
}
public boolean isSellable(ItemDefinition def) {
if (def == null) {
return false;
}
for (int id : GeneralStoreSeller.startSellables) {
if (def.isNoted() ? def.getId() - 1 == id : def.getId() == id) {
return true;
}
}
return false;
}
public boolean hasNeededSellables() {
return !isLoggedIn() || inventory.getItems().length == 0 || restockWhenOneGone ? !isMissingOneSellable() : inventory.contains(GeneralStoreSeller.startSellables);
}
public boolean isMissingOneSellable() {
for (SellableItem i : sellables.getCurrent()) {
if (!i.hasInInventory()) {
System.out.println("Missing: " + i.getName());
for (Item ii : inventory.getItems()) {
System.out.println(ii == null ? "nullitem" : ii.getName());
}
return true;
}
}
return false;
}
@Override
public void onMessage(Message m) {
if (m != null && m.getTypeId() == 0 && m.getMessage().contains("You haven't got enough.")) {
sellables.removeFromCurrent(atGE.getCurrentID());
buyingState.isBuying = false;
}
}
@Override
public void itemAdded(Item i, int amount) {
ATState s = currentState;
System.out.println("Added: " + i.getName() + ": " + amount);
if (i.getId() == 995 && (s instanceof Selling)) {
turnOver += amount;
}
}
@Override
public void itemRemoved(Item item, int amount) {
}
}
| true |
b07229c50df24ab8036573de6415c1bccb95ec9d | Java | ItAmao/JavaBasic | /day14/src/com/amao/homework/demo01/Test.java | UTF-8 | 1,941 | 3.875 | 4 | [] | no_license | package com.amao.homework.demo01;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {1, 2, 432, 32, 54, 32, 3, 7, 657, 563, 25, 43, 6, 463, 52};
bubble(arr);
selectSort(arr);
printArrays(arr);
}
/**
* Arrays类打印
*/
public static void printArrays(int[] arr) {
Arrays.sort(arr);
System.out.println("Arrays类打印:");
for (int i : arr) {
System.out.print(i + " ");
}
}
/**
* 选择排序
*/
public static void selectSort(int[] arr) {
int min = 0;
int temp = 0;
for (int i = 0; i < arr.length - 1; i++) {
min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (min != i) {
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
System.out.println("选择排序:");
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println("");
System.out.println("=====================================");
}
/**
* 冒泡排序
*
* @param arr
*/
public static void bubble(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("冒泡排序(升序):");
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println("");
System.out.println("=====================================");
}
}
| true |
8d5979f61ab46fe02281aec29801f58ca8a3fd43 | Java | ljtfreitas/spring-state-machine-sample | /src/test/java/com/mindblow/payment/statemachine/BoletoPaymentStateMachineTest.java | UTF-8 | 3,421 | 2.125 | 2 | [] | no_license | package com.mindblow.payment.statemachine;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mindblow.Application;
import com.mindblow.transaction.Transaction;
import com.mindblow.transaction.TransactionStatus;
import com.mindblow.transaction.TransactionStatusType;
import com.mindblow.transaction.payment.BoletoPayment;
import com.mindblow.transaction.payment.BoletoPaymentStatus;
import com.mindblow.transaction.payment.BoletoPaymentStatusType;
import com.mindblow.transaction.payment.event.BoletoPaymentCancelledEvent;
import com.mindblow.transaction.payment.event.BoletoPaymentPaidEvent;
import com.mindblow.transaction.payment.event.BoletoPaymentPrintedEvent;
import com.mindblow.transaction.payment.event.PaymentEventPublisher;
import com.mindblow.transaction.payment.repository.PaymentRepository;
import com.mindblow.transaction.repository.TransactionRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class BoletoPaymentStateMachineTest {
@Autowired
private PaymentRepository paymentRepository;
@Autowired
private TransactionRepository transactionRepository;
@Autowired
private PaymentEventPublisher paymentEventPublisher;
private Transaction transaction;
private BoletoPayment boletoPayment;
@Before
public void setup() {
transaction = new Transaction(TransactionStatus.created());
boletoPayment = new BoletoPayment(BoletoPaymentStatus.created());
transaction.addPayment(boletoPayment);
transactionRepository.save(transaction);
}
@Test
public void onBoletoPaymentPrintedEvent() {
paymentEventPublisher.publish(new BoletoPaymentPrintedEvent(boletoPayment));
boletoPayment = (BoletoPayment) paymentRepository.findOne(boletoPayment.getId());
BoletoPaymentStatus boletoStatus = boletoPayment.getStatus();
assertEquals(BoletoPaymentStatusType.PRINTED, boletoStatus.asType());
transaction = boletoPayment.getTransaction();
assertEquals(TransactionStatusType.WAITING_PAY, transaction.getStatus().asType());
}
@Test
public void onBoletoPaymentPaidEvent() {
boletoPayment.printed();
paymentRepository.save(boletoPayment);
paymentEventPublisher.publish(new BoletoPaymentPaidEvent(boletoPayment));
boletoPayment = (BoletoPayment) paymentRepository.findOne(boletoPayment.getId());
BoletoPaymentStatus boletoStatus = boletoPayment.getStatus();
assertEquals(BoletoPaymentStatusType.PAID, boletoStatus.asType());
transaction = boletoPayment.getTransaction();
assertEquals(TransactionStatusType.PAID, transaction.getStatus().asType());
}
@Test
public void onBoletoPaymentCancelledEvent() {
boletoPayment.printed();
paymentRepository.save(boletoPayment);
paymentEventPublisher.publish(new BoletoPaymentCancelledEvent(boletoPayment));
boletoPayment = (BoletoPayment) paymentRepository.findOne(boletoPayment.getId());
BoletoPaymentStatus boletoStatus = boletoPayment.getStatus();
assertEquals(BoletoPaymentStatusType.CANCELLED, boletoStatus.asType());
transaction = boletoPayment.getTransaction();
assertEquals(TransactionStatusType.CANCELLED, transaction.getStatus().asType());
}
}
| true |
5d6585688f245f0f83b75b148e5cd42f0916dfbb | Java | gnomix/jumi | /jumi-core/src/main/java/fi/jumi/core/runs/DefaultSuiteNotifier.java | UTF-8 | 1,153 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | // Copyright © 2011-2013, Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
package fi.jumi.core.runs;
import fi.jumi.actors.ActorRef;
import fi.jumi.api.drivers.*;
import fi.jumi.core.output.OutputCapturer;
import javax.annotation.concurrent.ThreadSafe;
@ThreadSafe
public class DefaultSuiteNotifier implements SuiteNotifier {
private final CurrentRun currentRun;
public DefaultSuiteNotifier(ActorRef<RunListener> listener, RunIdSequence runIdSequence, OutputCapturer outputCapturer) {
this.currentRun = new CurrentRun(listener, runIdSequence, outputCapturer);
}
@Override
public void fireTestFound(TestId testId, String name) {
currentRun.fireTestFound(testId, name);
}
@Override
public TestNotifier fireTestStarted(TestId testId) {
currentRun.fireTestStarted(testId);
return new DefaultTestNotifier(currentRun, testId);
}
@Override
public void fireInternalError(String message, Throwable cause) {
currentRun.fireInternalError(message, cause);
}
}
| true |
10ff6de0c27cfb48995213ac5ea924ae08690427 | Java | Bit-alg/Complier | /Instruction.java | UTF-8 | 5,303 | 3.546875 | 4 | [] | no_license | package kc;
/**
* PseudoIseg の要素.つまり1つの命令 を格納する要素の定義
*/
class Instruction {
private Operator operator; //オペレータ
private int reg ; //アドレス修飾用
private int addr; //オペランド
/**
Operatorクラスの要素から命令オブジェクトを作るためのコンストラクタ
@param opcode 命令
@param flag その命令のアドレス修飾子
@param address オペランド
*/
Instruction (Operator opcode, int flag, int address) {
operator = opcode;
reg = flag;
addr = address;
}
/**
文字列から命令オブジェクトを作るためのコンストラクタ
@param opcode 文字列形式の命令
@param flag その命令のアドレス修飾子
@param address オペランド
*/
Instruction (String opcode, int flag, int address) {
operator = str2Opeartor (opcode);
reg = flag;
addr = address;
}
/**
* 命令を出力するためのメソッド
*/
String printInstruction() {
/* 命令を出力する際, 命令のop部がop_oprndOuts
内のものかどうかを区別する必要がある.*/
String op_oprndCodeList =
"PUSH PUSHI POP POPI BLT BLE BEQ BNE BGE BGT JUMP";
//命令のop部がop_oprndCodeList 内のものでなければ, opのみを出力
switch (operator) {
case PUSH:
case PUSHI:
case POP:
case BLT:
case BLE:
case BEQ:
case BNE:
case BGE:
case BGT:
case JUMP:
// オペレータとオペランドを出力
return operator.name() + "\t" + addr;
default:
// オペレータのみを出力
return operator.name();
}
}
/**
* operator フィールドの getter
* @return operator
*/
Operator getOperator() {
return operator;
}
/**
* addr フィールドの getter
* @return addr
*/
int getAddr() {
return addr;
}
/**
* reg フィールドの getter
* @return reg
*/
int getReg() {
return reg;
}
/**
* 命令が引数で指定した命令と一致するか判定するメソッド
* @param opcode 命令
* @return 命令が引数の命令と一致すればtrue
*/
boolean equals (Operator opcode) {
return (operator.equals (opcode));
}
/**
* 命令が引数で指定した命令と一致するか判定するメソッド
* @param opcode 文字列形式の命令
* @return 命令が引数の命令と一致すればtrue
*/
boolean equals (String op) {
Operator opcode = str2Opeartor(op);
return (operator.equals (opcode));
}
/**
* StringをOperatorに変換する
* @param str 文字列形式の命令
* @return Operator型の命令
*/
Operator str2Opeartor (String op) {
if (op.equals ("NOP")) return Operator.NOP;
else if (op.equals ("ASSGN")) return Operator.ASSGN;
else if (op.equals ("ADD")) return Operator.ADD;
else if (op.equals ("SUB")) return Operator.SUB;
else if (op.equals ("MUL")) return Operator.MUL;
else if (op.equals ("DIV")) return Operator.DIV;
else if (op.equals ("MOD")) return Operator.MOD;
else if (op.equals ("CSIGN")) return Operator.CSIGN;
else if (op.equals ("AND")) return Operator.AND;
else if (op.equals ("OR")) return Operator.OR;
else if (op.equals ("NOT")) return Operator.NOT;
else if (op.equals ("COMP")) return Operator.COMP;
else if (op.equals ("COPY")) return Operator.COPY;
else if (op.equals ("PUSH")) return Operator.PUSH;
else if (op.equals ("PUSHI")) return Operator.PUSHI;
else if (op.equals ("REMOVE")) return Operator.REMOVE;
else if (op.equals ("POP")) return Operator.POP;
else if (op.equals ("INC")) return Operator.INC;
else if (op.equals ("DEC")) return Operator.DEC;
else if (op.equals ("JUMP")) return Operator.JUMP;
else if (op.equals ("BLT")) return Operator.BLT;
else if (op.equals ("BLE")) return Operator.BLE;
else if (op.equals ("BEQ")) return Operator.BEQ;
else if (op.equals ("BNE")) return Operator.BNE;
else if (op.equals ("BGE")) return Operator.BGE;
else if (op.equals ("BGT")) return Operator.BGT;
else if (op.equals ("HALT")) return Operator.HALT;
else if (op.equals ("INPUT")) return Operator.INPUT;
else if (op.equals ("INPUTC")) return Operator.INPUTC;
else if (op.equals ("OUTPUT")) return Operator.OUTPUT;
else if (op.equals ("OUTPUTC")) return Operator.OUTPUTC;
else if (op.equals ("OUTPUTLN")) return Operator.OUTPUTLN;
else if (op.equals ("LOAD")) return Operator.LOAD;
else return Operator.ERR;
}
}
| true |
b23e6b9c38bbbc1ce0fe55748df093c0e8fd5431 | Java | LoicPi/amisDeLEscalade | /src/main/java/com/adle/projet/dao/LevelDAOImpl.java | UTF-8 | 2,224 | 2.6875 | 3 | [] | no_license | package com.adle.projet.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.adle.projet.entity.Level;
@Repository
public class LevelDAOImpl implements LevelDAO {
private static final Logger logger = LogManager.getLogger( LevelDAOImpl.class );
@Autowired
private SessionFactory sessionFactory;
/**
* Function return the list of levels in database
*/
@Override
public List<Level> getLevels() {
Session session = sessionFactory.getCurrentSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Level> cq = cb.createQuery( Level.class );
Root<Level> root = cq.from( Level.class );
cq.select( root );
Query query = session.createQuery( cq );
logger.info( "Level List : " + query.getResultList() );
return query.getResultList();
}
/**
* Function return a level by the given id
*/
@Override
public Level getLevel( int theId ) {
Session currentSession = sessionFactory.getCurrentSession();
Level level = currentSession.get( Level.class, theId );
logger.info( "Level loaded successfully, Level details = " + level );
return level;
}
/**
* Fucntion return a map of level by the given list of levels
*/
@Override
public Map<Integer, String> getLevelNameOfLevels( List<Level> levels ) {
Map<Integer, String> levelName = new HashMap<Integer, String>();
for ( int i = 1; i <= levels.size(); i++ ) {
levelName.put( i, levels.get( i - 1 ).getLevelName() );
}
logger.info( "MapOfLevel : " + levelName );
return levelName;
}
}
| true |
bec1c1ad463744e4a922bc8798489e7aababe7a6 | Java | sabir012/awttwitter | /src/main/java/com/example/awtsocialnetwork/service/FilterService.java | UTF-8 | 1,675 | 2.28125 | 2 | [] | no_license | package com.example.awtsocialnetwork.service;
import com.example.awtsocialnetwork.Model.FilterModel;
import com.example.awtsocialnetwork.entity.FilterEntity;
import com.example.awtsocialnetwork.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by sabiralizada on 7/10/17.
*/
@Service
public class FilterService {
@Autowired
private FilterRepository filterRepository;
@Autowired
private TopicRepository topicRepository;
@Autowired
private LanguageRepository languageRepository;
@Autowired
private GenderRepository genderRepository;
@Autowired
private TwitterUserRepository userRepository;
@Autowired
private SentimentRepository sentimentRepository;
public FilterModel getAllFilter(){
Iterable<FilterEntity> filterEntities= filterRepository.findAll();
FilterModel filterModel = new FilterModel();
for (FilterEntity filter:filterEntities) {
switch (filter.getName()){
case "topic": filterModel.setTopics(topicRepository.findAll()); break;
case "language": filterModel.setLanguages(languageRepository.findAll()); break;
case "gender": filterModel.setGenders(genderRepository.findAll()); break;
case "twitter_user": filterModel.setTwitterUsers(userRepository.findAll()); break;
case "sentiment": filterModel.setSentiments(sentimentRepository.findAll()); break;
default:
System.out.println("NO SUCH TABLE IN DATABASE");
}
}
return filterModel;
}
}
| true |
d472e510e5ea689c3f20788ba4937813e2de7e35 | Java | wardm5/Practice_It | /4th_Edition/Chapter 11 - Java Collections/countCommon.java | UTF-8 | 624 | 3.859375 | 4 | [] | no_license | // Write a method countCommon that takes two Lists of integers as parameters and returns the number of unique
// integers that occur in both lists. Use one or more Sets as storage to help you solve this problem.
public int countCommon(List<Integer> arr1, List<Integer> arr2) {
HashSet<Integer> set = new HashSet<Integer>();
int count = 0;
for (int i = 0; i < arr1.size(); i++) {
set.add(arr1.get(i));
}
for (int i = 0; i < arr2.size(); i++) {
if (set.contains(arr2.get(i))) {
set.remove(arr2.get(i));
count++;
}
}
return count;
}
| true |
946cd6c20b74d4df9e3d1b9d77b88450204bf617 | Java | yue31313/shou_ji_zhu_shou | /src/com/example/playtabtest/BaseActivity.java | UTF-8 | 1,731 | 2.25 | 2 | [] | no_license | package com.example.playtabtest;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Window;
import android.view.WindowManager;
public class BaseActivity extends Activity {
protected ProgressDialog mpDialog;
protected Context context = this;
protected void mpDialogShow(String message) {
mpDialog = new ProgressDialog(context);
mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mpDialog.setMessage(message);
mpDialog.setIndeterminate(true);
mpDialog.setCancelable(false);
mpDialog.show();
}
protected void fullScreen() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
protected void noTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
protected void noTitle_FullScreen() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
protected void landscape() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
protected void portrait() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
protected byte[] bitmapToBytes(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
protected Bitmap bytesToBimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
}
| true |
42c906b876db27d652f206abb5cb289c510c8522 | Java | 0jinxing/wechat-apk-source | /com/tencent/mm/compatible/e/d.java | UTF-8 | 3,997 | 1.703125 | 2 | [] | no_license | package com.tencent.mm.compatible.e;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Looper;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.sdk.platformtools.ab;
public final class d
{
public static int Lr()
{
int i = 0;
AppMethodBeat.i(92923);
if (q.etn.esf == 1)
{
AppMethodBeat.o(92923);
return i;
}
int j = Camera.getNumberOfCameras();
Camera.CameraInfo localCameraInfo = new Camera.CameraInfo();
i = 0;
label38: if (i < j)
{
Camera.getCameraInfo(i, localCameraInfo);
if (localCameraInfo.facing == 0)
ab.d("MicroMsg.CameraUtil", "tigercam get bid %d", new Object[] { Integer.valueOf(i) });
}
while (true)
{
ab.d("MicroMsg.CameraUtil", "tigercam getBackCameraId %d", new Object[] { Integer.valueOf(i) });
AppMethodBeat.o(92923);
break;
i++;
break label38;
i = 0;
}
}
public static int Ls()
{
AppMethodBeat.i(92924);
int i = Camera.getNumberOfCameras();
Camera.CameraInfo localCameraInfo = new Camera.CameraInfo();
int j = 0;
if (j < i)
{
Camera.getCameraInfo(j, localCameraInfo);
if (localCameraInfo.facing == 1)
ab.d("MicroMsg.CameraUtil", "tigercam get fid %d", new Object[] { Integer.valueOf(j) });
}
while (true)
{
ab.d("MicroMsg.CameraUtil", "tigercam getBackCameraId %d", new Object[] { Integer.valueOf(j) });
AppMethodBeat.o(92924);
return j;
j++;
break;
j = 0;
}
}
public static boolean Lt()
{
boolean bool = true;
AppMethodBeat.i(92925);
if (q.etc.erj == 1)
AppMethodBeat.o(92925);
while (true)
{
return bool;
if ((Build.VERSION.SDK_INT == 10) && (Build.MODEL.equals("GT-S5360")))
{
AppMethodBeat.o(92925);
}
else
{
bool = false;
AppMethodBeat.o(92925);
}
}
}
public static d.a.a a(Context paramContext, int paramInt, Looper paramLooper)
{
AppMethodBeat.i(92926);
if (q.etc.erj == 1)
{
ab.d("MicroMsg.CameraUtil", "openCamera(), CameraUtilImpl20, cameraId = ".concat(String.valueOf(paramInt)));
new e();
paramContext = e.b(paramLooper);
AppMethodBeat.o(92926);
}
while (true)
{
return paramContext;
if (q.etc.erb)
{
ab.d("MicroMsg.CameraUtil", "openCamera(), CameraUtilImplConfig, cameraId = ".concat(String.valueOf(paramInt)));
new i();
paramContext = i.a(paramInt, paramLooper);
AppMethodBeat.o(92926);
}
else if (Build.MODEL.equals("M9"))
{
new j();
paramContext = j.b(paramLooper);
AppMethodBeat.o(92926);
}
else if (getNumberOfCameras() > 1)
{
ab.d("MicroMsg.CameraUtil", "openCamera(), CameraUtilImpl23, cameraId = ".concat(String.valueOf(paramInt)));
new g();
paramContext = g.a(paramContext, paramInt, paramLooper);
AppMethodBeat.o(92926);
}
else
{
new f();
paramContext = f.a(paramInt, paramLooper);
AppMethodBeat.o(92926);
}
}
}
public static int getNumberOfCameras()
{
AppMethodBeat.i(92922);
int i;
if ((q.etc.erb) && (q.etc.erh))
{
new i();
i = i.getNumberOfCameras();
AppMethodBeat.o(92922);
}
while (true)
{
return i;
new g();
i = Camera.getNumberOfCameras();
AppMethodBeat.o(92922);
}
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes5-dex2jar.jar
* Qualified Name: com.tencent.mm.compatible.e.d
* JD-Core Version: 0.6.2
*/ | true |
c7e00d2199dc531be39013f2f75369acb4d6cc81 | Java | percym/loanapplicationmanager | /loan-model-impl/src/main/java/com/loanscompany/lam/model/settings/applicant/ApplicantPersonalDetailsSettings.java | UTF-8 | 2,601 | 1.828125 | 2 | [] | no_license | package com.loanscompany.lam.model.settings.applicant;
import com.loanscompany.lam.imodel.member.IMember;
import com.loanscompany.lam.imodel.settings.applicant.IApplicantAddressSettings;
import com.loanscompany.lam.imodel.settings.applicant.IApplicantPersonalDetailsSettings;
import com.loanscompany.lam.model.general.Active;
import com.loanscompany.lam.model.general.TimeActiveRecord;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
/**
* @author percym
* <p>
* Implementation for the {@link IApplicantAddressSettings} class
*/
@Entity
@Data
@Audited
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Table(schema = "data", name = "applicant_personal_settings")
@AttributeOverrides({
@AttributeOverride(name = "id", column = @Column(name = "applicant_serial")),
@AttributeOverride(name = "startDate", column = @Column(name = "applicant_start_date")),
@AttributeOverride(name = "endDate", column = @Column(name = "applicant_end_date")),
@AttributeOverride(name = "createdBy", column = @Column(name = "applicant_created_by")),
@AttributeOverride(name = "createdOn", column = @Column(name = "applicant_created_on")),
@AttributeOverride(name = "updatedBy", column = @Column(name = "applicant_updated_by")),
@AttributeOverride(name = "updatedOn", column = @Column(name = "applicant_updated_on"))
})
public class ApplicantPersonalDetailsSettings extends TimeActiveRecord implements IApplicantPersonalDetailsSettings {
private static final long serialVersionUID = -5803233040844849239L;
@NotNull
@Column(name = "applicant_depedendants")
private Boolean requireNumberOfDependants;
@NotNull
@Column(name = "applicant_children")
private Boolean requireNumberOfChildren;
@NotNull
@Column(name = "applicant_country")
private Boolean requireCountryOfBirth;
@NotNull
@Column(name = "applicant_place_birth")
private Boolean requirePlaceOfBirth;
@NotNull
@Column(name = "applicant_nationality")
private Boolean requireNationality;
@NotNull
@Column(name = "applicant_citizenship")
private Boolean requireCitizenShip;
@NotNull
@Column(name = "applicant_race")
private Boolean requireRace;
@NotNull
@Column(name = "applicant_email")
private Boolean requireEmail;
}
| true |
ce3cb7e19a9204faa0d22a4b196d7620ff83bf43 | Java | KhaingZinHtwe/AbstractFactoryPatternTest | /Rectangle.java | UTF-8 | 563 | 3.765625 | 4 | [] | no_license | package AbstractFactoryPattern;
public class Rectangle implements Shape {
public double width,length;
public Rectangle(double width, double length) {
super();
this.width = width;
this.length = length;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("Inside Rectangle::draw() method.");
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return width*length;
}
@Override
public double getPerimeter() {
// TODO Auto-generated method stub
return 2*(width+length);
}
}
| true |
62d398f151da33afbd2f65efe0060ffd72375d1d | Java | ryukato/foundation_algorithm | /foundation.algorithm/src/main/java/sort/QuickSort.java | UTF-8 | 1,436 | 3.453125 | 3 | [] | no_license | package sort;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import util.ComparableUtil;
public class QuickSort<E extends Comparable<E>> {
public void sort(E[] source, int low, int high){
int pivotIndex = 0;
if(high > low){
pivotIndex = partition(source, low, high, pivotIndex);
sort(source, low, pivotIndex -1);
sort(source, pivotIndex + 1, high);
}
}
private int partition(E[] source, int low, int high, int pivotIndex) {
int j = low;
E pivotItem = source[low];
for(int i = low +1; i <= high; i++){
if(less(source[i], pivotItem)){
j++;
exchange(source, i, j);
}
pivotIndex = j;
}
exchange(source, low, pivotIndex);
print(source, low, high, pivotIndex);
return pivotIndex;
}
private void print(E[] source, int low, int high, int pivotIndex) {
E pivotItem = source[pivotIndex];
String joinedElements = Arrays.stream(source).map(new Function<E, String>() {
@Override
public String apply(E t) {
if(pivotItem.equals(t)){
return String.format("|%s|", String.valueOf(t));
}else{
return String.valueOf(t);
}
}
}).collect(Collectors.joining(" "));
System.out.println(joinedElements);
}
private void exchange(E[] source, int i, int j){
E tmp = source[i];
source[i] = source[j];
source[j] = tmp;
}
private boolean less(E e1, E e2) {
return ComparableUtil.less(e1, e2);
}
}
| true |
88e4dbbbb78e7a9644eb6a736105ed96019b2527 | Java | Ph4i1ur3/Denizen | /plugin/src/main/java/com/denizenscript/denizen/utilities/LegacySavesUpdater.java | UTF-8 | 9,055 | 2.125 | 2 | [
"MIT"
] | permissive | package com.denizenscript.denizen.utilities;
import com.denizenscript.denizen.Denizen;
import com.denizenscript.denizen.objects.NPCTag;
import com.denizenscript.denizen.objects.PlayerTag;
import com.denizenscript.denizen.utilities.debugging.Debug;
import com.denizenscript.denizencore.DenizenCore;
import com.denizenscript.denizencore.flags.AbstractFlagTracker;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.TimeTag;
import com.denizenscript.denizencore.scripts.ScriptHelper;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.YamlConfiguration;
import com.denizenscript.denizencore.utilities.text.StringHolder;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;
public class LegacySavesUpdater {
public static void updateLegacySaves() {
Debug.log("==== UPDATING LEGACY SAVES TO NEW FLAG ENGINE ====");
File savesFile = new File(Denizen.getInstance().getDataFolder(), "saves.yml");
if (!savesFile.exists()) {
Debug.echoError("Legacy update went weird: file doesn't exist?");
return;
}
YamlConfiguration saveSection;
try {
FileInputStream fis = new FileInputStream(savesFile);
String saveData = ScriptHelper.convertStreamToString(fis, false);
fis.close();
if (saveData.trim().length() == 0) {
Debug.log("Nothing to update.");
savesFile.delete();
return;
}
saveSection = YamlConfiguration.load(saveData);
if (saveSection == null) {
Debug.echoError("Something went very wrong: legacy saves file failed to load!");
return;
}
}
catch (Throwable ex) {
Debug.echoError(ex);
return;
}
if (!savesFile.renameTo(new File(Denizen.getInstance().getDataFolder(), "saves.yml.bak"))) {
Debug.echoError("Legacy saves file failed to rename!");
}
if (saveSection.contains("Global")) {
Debug.log("==== Update global data ====");
YamlConfiguration globalSection = saveSection.getConfigurationSection("Global");
if (globalSection.contains("Flags")) {
applyFlags("Server", DenizenCore.serverFlagMap, globalSection.getConfigurationSection("Flags"));
}
if (globalSection.contains("Scripts")) {
YamlConfiguration scriptsSection = globalSection.getConfigurationSection("Scripts");
for (StringHolder script : scriptsSection.getKeys(false)) {
YamlConfiguration scriptSection = scriptsSection.getConfigurationSection(script.str);
if (scriptSection.contains("Cooldown Time")) {
long time = Long.parseLong(scriptSection.getString("Cooldown Time"));
TimeTag cooldown = new TimeTag(time);
DenizenCore.serverFlagMap.setFlag("__interact_cooldown." + script.low, cooldown, cooldown);
}
}
}
}
if (saveSection.contains("Players")) {
Debug.log("==== Update player data ====");
YamlConfiguration playerSection = saveSection.getConfigurationSection("Players");
for (StringHolder plPrefix : playerSection.getKeys(false)) {
YamlConfiguration subSection = playerSection.getConfigurationSection(plPrefix.str);
for (StringHolder uuidString : subSection.getKeys(false)) {
if (uuidString.str.length() != 32) {
Debug.echoError("Cannot update data for player with non-ID entry listed: " + uuidString);
continue;
}
try {
UUID id = UUID.fromString(uuidString.str.substring(0, 8) + "-" + uuidString.str.substring(8, 12) + "-" + uuidString.str.substring(12, 16) + "-" + uuidString.str.substring(16, 20) + "-" + uuidString.str.substring(20, 32));
PlayerTag player = PlayerTag.valueOf(id.toString(), CoreUtilities.errorButNoDebugContext);
if (player == null) {
Debug.echoError("Cannot update data for player with id: " + uuidString);
continue;
}
YamlConfiguration actual = subSection.getConfigurationSection(uuidString.str);
AbstractFlagTracker tracker = player.getFlagTracker();
if (actual.contains("Flags")) {
applyFlags(player.identify(), tracker, actual.getConfigurationSection("Flags"));
}
if (actual.contains("Scripts")) {
YamlConfiguration scriptsSection = actual.getConfigurationSection("Scripts");
for (StringHolder script : scriptsSection.getKeys(false)) {
YamlConfiguration scriptSection = scriptsSection.getConfigurationSection(script.str);
if (scriptSection.contains("Current Step")) {
tracker.setFlag("__interact_step." + script, new ElementTag(scriptSection.getString("Current Step")), null);
}
if (scriptSection.contains("Cooldown Time")) {
long time = Long.parseLong(scriptSection.getString("Cooldown Time"));
TimeTag cooldown = new TimeTag(time);
tracker.setFlag("__interact_cooldown." + script, cooldown, cooldown);
}
}
}
player.reapplyTracker(tracker);
}
catch (Throwable ex) {
Debug.echoError("Error updating flags for player with ID " + uuidString.str);
Debug.echoError(ex);
}
}
}
}
if (saveSection.contains("NPCs")) {
final YamlConfiguration npcsSection = saveSection.getConfigurationSection("NPCs");
new BukkitRunnable() {
@Override
public void run() {
Debug.log("==== Late update NPC data ====");
for (StringHolder npcId : npcsSection.getKeys(false)) {
YamlConfiguration actual = npcsSection.getConfigurationSection(npcId.str);
NPCTag npc = NPCTag.valueOf(npcId.str, CoreUtilities.errorButNoDebugContext);
if (npc == null) {
Debug.echoError("Cannot update data for NPC with id: " + npcId.str);
continue;
}
AbstractFlagTracker tracker = npc.getFlagTracker();
if (actual.contains("Flags")) {
applyFlags(npc.identify(), tracker, actual.getConfigurationSection("Flags"));
}
npc.reapplyTracker(tracker);
Debug.log("==== Done late-updating NPC data ====");
}
}
}.runTaskLater(Denizen.getInstance(), 3);
}
Denizen.getInstance().saveSaves(false);
Debug.log("==== Done updating legacy saves (except NPCs) ====");
}
public static void applyFlags(String object, AbstractFlagTracker tracker, YamlConfiguration section) {
try {
if (section == null || section.getKeys(false).isEmpty()) {
return;
}
for (StringHolder flagName : section.getKeys(false)) {
if (flagName.low.endsWith("-expiration")) {
continue;
}
TimeTag expireAt = null;
if (section.contains(flagName + "-expiration")) {
long expireTime = Long.parseLong(section.getString(flagName + "-expiration"));
expireAt = new TimeTag(expireTime);
}
Object value = section.get(flagName.str);
ObjectTag setAs = CoreUtilities.objectToTagForm(value, CoreUtilities.errorButNoDebugContext);
tracker.setFlag(flagName.low, setAs, expireAt);
}
}
catch (Throwable ex) {
Debug.echoError("Error while updating legacy flags for " + object);
Debug.echoError(ex);
}
}
}
| true |
7dbdeb1e18d3ef7a9c14ccb26769593b1b0a1c4b | Java | BGCX067/eyet-java-web-svn-to-git | /trunk/EyeTWeb/src/lib/event/ErrorEvent.java | UTF-8 | 537 | 2.171875 | 2 | [] | no_license | package lib.event;
import java.util.HashMap;
import java.util.Map;
import com.eyet.framework.util.JsonObject;
import com.eyet.framework.web.event.EventSupport;
public class ErrorEvent extends EventSupport {
public void adderror(){
this.display();
}
public void errorjson(){
Map<String,Object> jsonMap = new HashMap<String,Object>();
jsonMap.put("statusCode",200);
jsonMap.put("message","操作成功");
JsonObject jobj = JsonObject.fromObject(jsonMap);
this.displayJson(jobj.toString());
}
}
| true |
2daa92418902950ffde84f65040067bcfd7c956d | Java | huanshilang1985/JavaFamily | /src/main/java/com/zh/java/data/stack/s1_ArrayStack.java | UTF-8 | 1,691 | 4.1875 | 4 | [] | no_license | package com.zh.java.data.stack;
/**
* @Author zhanghe
* @Desc: 数组实现的顺序栈
* 栈是一种抽象的数据结构
* @Date 2018/11/5 19:13
*/
public class s1_ArrayStack {
private String[] items; //数组
private int count; //栈的元素个数
private int n; //栈的大小
public s1_ArrayStack(){
}
/**
* 初始化数组
* @param n 栈的大小
*/
public s1_ArrayStack(int n){
this.items = new String[n];
this.n = n;
this.count = 0;
}
/**
* 入栈操作
* @param item 入栈元素
* @return boolean
*/
public boolean push(String item){
//如果数组空间不够,返回false,入栈失败
if(count == n){
return false;
}
//将item放到下标为count的位置,并且count加1
items[count] = item;
++count;
return true;
}
/**
* 出栈操作
* @return String
*/
public String pup(){
//如果栈为空,返回false,出栈失败
if(count == 0){
return null;
}
//返回下标为count-1的数组元素,并且栈内元素个数count减1
String item = items[count - 1];
--count;
return item;
}
public static void main(String[] args) {
s1_ArrayStack stock = new s1_ArrayStack(2);
System.out.println(stock.push("111"));
System.out.println(stock.push("2222"));
System.out.println(stock.push("wlkjlaj"));
System.out.println(stock.pup());
System.out.println(stock.push("333"));
System.out.println(stock.pup());
}
}
| true |
50fe982f6d0e76338aaf95639e2e4022a1df4446 | Java | riiichard/Tom-and-Jerry-Sokoban | /ui/Main/Main.java | UTF-8 | 3,256 | 2.796875 | 3 | [] | no_license | package Main;
import Model.Board;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class Main extends JFrame implements ActionListener{
private final int OFFSET = 50;
private JLabel jl;
private JLabel js;
private JLabel jsp;
private JLabel jll;
private JTextField jt;
public Main(boolean b, String name) {
super("Tom & Jerry");
if(!b){
welcome();
}
else {
InitUI(name);
playMusic();
}
}
private void welcome() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 290));
((JPanel) getContentPane()).setBorder(new EmptyBorder(30, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("PLAY");
btn.setActionCommand("myButton");
btn.addActionListener(this);
jl = new JLabel(" Hi, welcome to my project! ");
jl.setFont(new Font("TimesRoman", Font.HANGING_BASELINE, 30));
js = new JLabel(" ");
jll = new JLabel(" What is your name? ");
jll.setFont(new Font("TimesRoman", Font.PLAIN, 20));
jsp = new JLabel(" ");
jt = new JTextField(10);
add(jl);
add(js);
add(jll);
add(jsp);
add(jt);
add(btn);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("myButton")){
Main soko = new Main(true,jt.getText());
soko.setVisible(true);
}
}
public void InitUI(String name) {
Board board = new Board();
board.setPlayerName(name);
add(board);
playMusic();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(board.getBoardWidth() + 4*OFFSET,
board.getBoardHeight() + 4*OFFSET);
setLocationRelativeTo(null);
setTitle("Tom & Jerry");
}
public static void main(String[] args) throws MalformedURLException, IOException{
Main sokoban = new Main(false,"Tom");
sokoban.setVisible(true);
}
private void playMusic(){
try {
URL cb;
File f = new File("res/music.wav");
cb = f.toURL();
AudioClip aau;
aau = Applet.newAudioClip(cb);
aau.play();
aau.loop();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
| true |
21abb3d001211bc9d066be9bff4d09540032d4b2 | Java | MarselSidikov/JAVA_IT_PARK_WORK_4 | /Themes/Lambda/src/ru/itpark/functional/Main.java | UTF-8 | 869 | 3.1875 | 3 | [] | no_license | package ru.itpark.functional;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
StringModifyRule reverseRule = new StringModifyRule() {
@Override
public String modify(String source) {
return new StringBuilder(source).reverse().toString();
}
};
StringModifyRule smileRule = new StringModifyRule() {
@Override
public String modify(String source) {
return source + "=)";
}
};
List<String> lines = new ArrayList<>();
lines.add("Марсель");
lines.add("Алексей");
lines.add("Даниил");
lines.add("Алмаз");
lines.add("Загир");
StringsModifier modifier = new StringsModifier();
List<String> reversed = modifier.modifyAll(lines, smileRule);
System.out.println(reversed);
}
}
| true |
47cd78f50f54a5f381de958a7b9901480735acda | Java | lasterz/tetris | /src/TetrisApplication.java | UTF-8 | 1,309 | 2.78125 | 3 | [] | no_license |
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import controller.TetrisGameController;
import view.HoldBlockView;
import view.MainFrame;
import view.NextBlockView;
import view.StatusBar;
import view.TetrisView;
public class TetrisApplication {
private JFrame frame;
/**
*
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TetrisApplication window = new TetrisApplication();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TetrisApplication() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new MainFrame();
TetrisGameController controller = new TetrisGameController(frame);
JPanel statusBar = new StatusBar(controller);
frame.getContentPane().add(statusBar);
JPanel tetrisView = new TetrisView(controller);
frame.getContentPane().add(tetrisView);
JPanel nextBlocksView = new NextBlockView(controller);
frame.getContentPane().add(nextBlocksView);
JPanel holdingBlockView = new HoldBlockView(controller);
frame.getContentPane().add(holdingBlockView);
}
}
| true |
f4495c802c9d7e2b17ea6e2428dc58cc937f3978 | Java | jontmy/aoc-java | /src/main/java/solvers/aoc2018/day18/Landscape.java | UTF-8 | 5,687 | 3.375 | 3 | [] | no_license | package solvers.aoc2018.day18;
import java.util.ArrayList;
import java.util.List;
record Landscape(char[][] area, int width, int height) {
protected static final char BARREN = '.', FORESTED = '|', LUMBERYARD = '#';
protected static Landscape parse(List<String> input) {
assert !input.isEmpty();
var width = input.get(0).length();
var height = input.size();
var area = new char[width][height];
for (int y = 0; y < height; y++) {
var cs = input.get(y);
for (int x = 0; x < width; x++) {
area[x][y] = cs.charAt(x);
}
}
return new Landscape(area, width, height);
}
protected static Landscape from(Landscape landscape) {
var width = landscape.width();
var height = landscape.height;
var area = new char[width][height];
for (int x = 0; x < landscape.width(); x++) {
System.arraycopy(landscape.area()[x], 0, area[x], 0, landscape.height());
}
return new Landscape(area, width, height);
}
// Returns the eight acres surrounding an acre. (Acres on the edges of the lumber collection area
// might have fewer than eight adjacent acres; the missing acres aren't counted.)
private List<Character> adjacent(int x, int y) {
var adjacent = new ArrayList<Character>();
if (x > 0) adjacent.add(area[x - 1][y]);
if (x < height - 1) adjacent.add(area[x + 1][y]);
if (y > 0) {
adjacent.add(area[x][y - 1]);
if (x > 0) adjacent.add(area[x - 1][y - 1]);
if (x < height - 1) adjacent.add(area[x + 1][y - 1]);
}
if (y < height - 1) {
adjacent.add(area[x][y + 1]);
if (x > 0) adjacent.add(area[x - 1][y + 1]);
if (x < height - 1) adjacent.add(area[x + 1][y + 1]);
}
return adjacent;
}
// Returns the number of acres surrounding an acre at the specified coordinates that match the specified type.
private int adjacent(int x, int y, char type) {
return (int) adjacent(x, y).stream()
.filter(c -> c == type)
.count();
}
/*
The change to each acre is based entirely on the contents of that acre as well as the number of open,
wooded, or lumberyard acres adjacent to it at the start of each minute.
Changes happen across all acres simultaneously, each of them using the state of all acres at the
beginning of the minute and changing to their new form by the end of that same minute.
Changes that happen during the minute don't affect each other.
*/
protected Landscape derive() {
var derived = new char[width][height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
var acre = area[x][y];
switch (acre) {
case BARREN -> {
// An open acre will become filled with trees if three or more adjacent acres contained trees.
// Otherwise, nothing happens.
if (adjacent(x, y, FORESTED) >= 3) {
derived[x][y] = FORESTED;
} else {
derived[x][y] = BARREN;
}
}
case FORESTED -> {
// An acre filled with trees will become a lumberyard if three or more adjacent acres were lumberyards.
// Otherwise, nothing happens.
if (adjacent(x, y, LUMBERYARD) >= 3) {
derived[x][y] = LUMBERYARD;
} else {
derived[x][y] = FORESTED;
}
}
case LUMBERYARD -> {
// An acre containing a lumberyard will remain a lumberyard if it was adjacent to at least
// one other lumberyard and at least one acre containing trees. Otherwise, it becomes open.
if (adjacent(x, y, LUMBERYARD) >= 1 && adjacent(x, y, FORESTED) >= 1) {
derived[x][y] = LUMBERYARD;
} else {
derived[x][y] = BARREN;
}
}
default -> throw new IllegalStateException(String.valueOf(acre));
}
}
}
return new Landscape(derived, width, height);
}
protected Landscape derive(int minutes) {
var derived = this;
for (int i = 0; i < minutes; i++) {
derived = derived.derive();
}
return derived;
}
// Multiplying the number of wooded acres by the number of lumberyards gives the total resource value.
protected int value() {
int forested = 0, lumberyards = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
char c = area[x][y];
if (c == Landscape.FORESTED) forested++;
else if (c == Landscape.LUMBERYARD) lumberyards++;
}
}
return forested * lumberyards;
}
@Override
@SuppressWarnings("DuplicatedCode")
public String toString() {
var sb = new StringBuilder();
sb.append(width).append(" x ").append(height).append(" landscape:\n");
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
sb.append(area[x][y]);
}
sb.append("\n");
}
return sb.toString();
}
}
| true |
abf43bdfbba0f4a5a9a03eefdf406c69742a10b8 | Java | Azure/azure-sdk-for-java | /sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/redis/passwordless/data/jedis/AzureRedisCredentialSupplier.java | UTF-8 | 1,256 | 2.328125 | 2 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"CC0-1.0",
"BSD-3-Clause",
"UPL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.spring.cloud.autoconfigure.implementation.redis.passwordless.data.jedis;
import com.azure.identity.extensions.implementation.template.AzureAuthenticationTemplate;
import java.util.Properties;
import java.util.function.Supplier;
/**
* AzureRedisCredentialSupplier that provide a String as the password to connect Azure Redis.
*
* @since 4.6.0
*/
public class AzureRedisCredentialSupplier implements Supplier<String> {
private final AzureAuthenticationTemplate azureAuthenticationTemplate;
/**
* Create {@link AzureRedisCredentialSupplier} instance.
* @param properties properties to initialize AzureRedisCredentialSupplier.
*/
public AzureRedisCredentialSupplier(Properties properties) {
azureAuthenticationTemplate = new AzureAuthenticationTemplate();
azureAuthenticationTemplate.init(properties);
}
@Override
public String get() {
return azureAuthenticationTemplate.getTokenAsPassword();
}
AzureRedisCredentialSupplier(AzureAuthenticationTemplate azureAuthenticationTemplate) {
this.azureAuthenticationTemplate = azureAuthenticationTemplate;
}
}
| true |
209287380b7624d9ec12866746eb1130c4539e27 | Java | gioargyr/MyOCD | /MyOCD/src/base/Series.java | UTF-8 | 1,376 | 2.75 | 3 | [] | no_license | package base;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
public class Series {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String pathName = "I:\\Tobeformalized\\Homeland";
String seriesName = "Homeland";
String season = "05";
String episodesNamePath = pathName + "\\episodes.txt";
String resultNamePath = pathName + "\\result.txt";
System.out.println(resultNamePath);
File episodesFile = new File(episodesNamePath);
File output = new File(resultNamePath);
LineIterator episodesNameIter = FileUtils.lineIterator(episodesFile);
int epiNum = 1;
while (episodesNameIter.hasNext()) {
String epiName = episodesNameIter.next().trim().replaceAll("\"", "");
if(epiNum < 10) {
Files.append(seriesName + " - S" + season + "E0" + epiNum + " - " + epiName + "\n", output, Charsets.UTF_8);
}
else if (epiNum < 20){
Files.append(seriesName + " - S" + season + "E" + epiNum + " - " + epiName + "\n", output, Charsets.UTF_8);
}
else {
Files.append(seriesName + " - S" + season + "E" + epiNum + " - " + epiName + "\n", output, Charsets.UTF_8);
}
epiNum++;
}
}
}
| true |
7307bb6459b4aed7c629de1a1981a613c05ddad6 | Java | StefanSinapov/TelerikAcademy | /08. JavaScript UI & DOM/Teamwork/Blaze/src/main/java/com/team/blaze/exceptions/ExceptionLogger.java | UTF-8 | 537 | 2.859375 | 3 | [
"MIT"
] | permissive | package com.team.blaze.exceptions;
public final class ExceptionLogger
{
public static void Log(Exception exception)
{
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
String methodName = stackTraceElements[2].getMethodName();
String className = stackTraceElements[2].getClassName();
System.err.println("Called in - Class: " + className + " Method: " + methodName);
System.err.println(exception.getMessage());
System.err.println(exception);
}
}
| true |
638b1ac86dd9fbc5d698c565f23959970a0fa8f3 | Java | klimovm/code | /src/main/java/kurs1/week1/Work9_dopolnit1.java | UTF-8 | 745 | 3.25 | 3 | [] | no_license | package kurs1.week1;
import java.util.Scanner;
/**
* Created by Mihail on 17.04.2016.
*/
//Перевод с числа с десятичной системы счисления в двоичную, и наоборот. Пользователь сам вводит число
public class Work9_dopolnit1 {
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
System.out.println("Введите число");
int num = scr.nextInt();
String b = Integer.toBinaryString(num);
// String res = String.format("%x", num);
System.out.println("В двоичной: " + b);
System.out.println("В десятичной: " + Integer.parseInt(b, 2));
}
}
| true |
a4556f7c89d8e8e6bfb9251303c00a1510c3413d | Java | dydaniely/Parselog | /src/main/java/com/log/Parser/domain/AccessLog.java | UTF-8 | 1,923 | 2.140625 | 2 | [] | no_license | package com.log.Parser.domain;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Entity
public class AccessLog {
@Id
@GeneratedValue
private long id;
private String ip;
private LocalDateTime accessDate;
private String requestType;
private String httpStatus;
private String userAgent;
private String status;
private LocalTime responseTime;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "logFileId")
private LogFile logFile;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public LocalDateTime getAccessDate() {
return accessDate;
}
public void setAccessDate(LocalDateTime accessDate) {
this.accessDate = accessDate;
}
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public String getHttpStatus() {
return httpStatus;
}
public void setHttpStatus(String httpStatus) {
this.httpStatus = httpStatus;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalTime getResponseTime() {
return responseTime;
}
public void setResponseTime(LocalTime responseTime) {
this.responseTime = responseTime;
}
public LogFile getLogFile() {
return logFile;
}
public void setLogFile(LogFile logFile) {
this.logFile = logFile;
}
}
| true |
036c2a5d12b8218a6d756d0af07013f72c160f8f | Java | yeziyu-Y/JavaHomework | /ComputerStoreSystem/SamsungMemory.java | TIS-620 | 399 | 2.796875 | 3 | [] | no_license |
public class SamsungMemory implements Memory{
String Name;
int volume;
double price;
public SamsungMemory() {
this.Name = "SamsungMemory";
this.volume = 32;
this.price = 950;
}
public String MWork() {
return this.Name+"+";
}
public double getMprice() {
return this.price;
}
public String Minfo() {
return String.valueOf(this.volume)+" "+this.price;
}
}
| true |
5c796cf4a245e898f28f20f573f79479d1428ae5 | Java | sunwenjie/hris_pro | /src/com/kan/base/domain/define/ReportDTO.java | GB18030 | 5,249 | 2.1875 | 2 | [] | no_license | package com.kan.base.domain.define;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.kan.base.util.KANUtil;
/**
* װReport - HeaderDetail
*
* @author Kevin
*/
public class ReportDTO implements Serializable {
/**
* Serial Version UID
*/
private static final long serialVersionUID = -732022950611228412L;
// װReportHeaderVO
private ReportHeaderVO reportHeaderVO = new ReportHeaderVO();
// װReportDetailVO - ǰReportHeaderVO
private List<ReportDetailVO> reportDetailVOs = new ArrayList<ReportDetailVO>();
// װReportSearchDetailVO - ǰReportHeaderVO
private List<ReportSearchDetailVO> reportSearchDetailVOs = new ArrayList<ReportSearchDetailVO>();
// ǰTableӱϵ
private List<TableRelationVO> tableRelationVOs = new ArrayList<TableRelationVO>();
// ǰreportӱϵ
private List<ReportRelationVO> reportRelationVOs = new ArrayList<ReportRelationVO>();
// ǰбʹõ
private SearchDTO searchDTO = new SearchDTO();
public ReportHeaderVO getReportHeaderVO() {
return reportHeaderVO;
}
public void setReportHeaderVO(ReportHeaderVO reportHeaderVO) {
this.reportHeaderVO = reportHeaderVO;
}
public List<ReportDetailVO> getReportDetailVOs() {
return reportDetailVOs;
}
public void setReportDetailVOs(List<ReportDetailVO> reportDetailVOs) {
this.reportDetailVOs = reportDetailVOs;
}
public SearchDTO getSearchDTO() {
return searchDTO;
}
public void setSearchDTO(SearchDTO searchDTO) {
this.searchDTO = searchDTO;
}
public List<ReportSearchDetailVO> getReportSearchDetailVOs() {
return reportSearchDetailVOs;
}
public void setReportSearchDetailVOs(
List<ReportSearchDetailVO> reportSearchDetailVOs) {
this.reportSearchDetailVOs = reportSearchDetailVOs;
}
// ȡReportDetailVO
public ReportDetailVO getReportDetailVO(final String columnId) {
if (reportDetailVOs != null && reportDetailVOs.size() > 0) {
for (ReportDetailVO reportDetailVO : reportDetailVOs) {
if (reportDetailVO.getColumnId().equals(columnId)) {
return reportDetailVO;
}
}
}
return null;
}
// ȡReportSearchDetailVO
public ReportSearchDetailVO getReportSearchDetailVO(final String columnId) {
if (reportSearchDetailVOs != null && reportSearchDetailVOs.size() > 0) {
for (ReportSearchDetailVO reportSearchDetailVO : reportSearchDetailVOs) {
if (reportSearchDetailVO.getColumnId().equals(columnId)) {
return reportSearchDetailVO;
}
}
}
return null;
}
// ȡ
public String getReportName(final HttpServletRequest request) {
if (reportHeaderVO != null) {
if (request.getLocale().getLanguage().equalsIgnoreCase("ZH")) {
return reportHeaderVO.getNameZH();
} else {
return reportHeaderVO.getNameEN();
}
}
return "";
}
// ȡǰбǷҪҳ
public boolean isPaged() {
if (reportHeaderVO != null && reportHeaderVO.getUsePagination() != null
&& reportHeaderVO.getUsePagination().trim().equals("1")) {
return true;
}
return false;
}
// ȡǰбÿҳ¼
public int getPageSize() {
if (reportHeaderVO != null && reportHeaderVO.getUsePagination() != null
&& reportHeaderVO.getUsePagination().trim().equals("1")) {
if (reportHeaderVO.getPageSize() != null
&& reportHeaderVO.getPageSize().matches("[0-9]*")) {
return Integer.valueOf(reportHeaderVO.getPageSize());
}
}
return 0;
}
// ȡǰбԤҳ
public int getLoadPages() {
if (reportHeaderVO != null && reportHeaderVO.getUsePagination() != null
&& reportHeaderVO.getUsePagination().trim().equals("1")) {
if (reportHeaderVO.getLoadPages() != null
&& reportHeaderVO.getLoadPages().matches("[0-9]*")) {
return Integer.valueOf(reportHeaderVO.getLoadPages());
}
}
return 0;
}
// ȡǰǷ
public boolean isSearchFirst() {
if (reportHeaderVO != null && reportHeaderVO.getIsSearchFirst() != null
&& reportHeaderVO.getIsSearchFirst().trim().equals("1")) {
return true;
}
return false;
}
// ȡǷֱӵ
public boolean isExportFirst() {
return (KANUtil.filterEmpty(reportHeaderVO.getExportExcelType()) != null && reportHeaderVO
.getExportExcelType().trim().equals("2")) ? true : false;
}
// ȡǷֱӵ&&
public boolean isExportFirstAndSearchFirst() {
return (!isSearchFirst() && isExportFirst());
}
public List<TableRelationVO> getTableRelationVOs() {
return tableRelationVOs;
}
public void setTableRelationVOs(List<TableRelationVO> tableRelationVOs) {
this.tableRelationVOs = tableRelationVOs;
}
public List<ReportRelationVO> getReportRelationVOs() {
return reportRelationVOs;
}
public void setReportRelationVOs(List<ReportRelationVO> reportRelationVOs) {
this.reportRelationVOs = reportRelationVOs;
}
}
| true |
d4e6302051c3359c7af5aa7083ef0175302c8e3d | Java | cclauson/homomophismproblem | /src/LinearRHS.java | UTF-8 | 431 | 2.734375 | 3 | [] | no_license | // right hand side of linear rewrite rule
// T is node type
public class LinearRHS<T> {
public final String stringInitial;
public final T nodeStart;
public final T nodeEnd;
public final String stringFinal;
public LinearRHS(String stringInitial, T nodeStart, T nodeEnd, String stringFinal) {
this.stringInitial = stringInitial;
this.nodeStart = nodeStart;
this.nodeEnd = nodeEnd;
this.stringFinal = stringFinal;
}
}
| true |
4b9550969c9cc288823217840a7df993c5f9642e | Java | ankit-narang/Xmart-Coder | /IOS Libraries in Java/iPhoneOS7.0/src/org/xmart/objc/frameworks/cocoa/Foundation/NSDataDetector.java | UTF-8 | 1,029 | 1.679688 | 2 | [] | no_license | package org.xmart.objc.frameworks.cocoa.Foundation;
import java.util.*;
import java.io.*;
import org.xmart.objc.type.*;
import org.xmart.objc.annotation.*;
@ObjCFramework("Foundation")
public class NSDataDetector extends NSRegularExpression {
public NSDataDetector() {}
@ObjCPropertyGetter(selector = "checkingTypes")
public native @Unsigned @LongLong long getCheckingTypes();
@ObjCProperty public @Unsigned @LongLong long checkingTypes;
@ObjCMethodSign(sign = "- (id)initWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error;", selector = "initWithTypes:error:")
public native NSDataDetector initWithTypes$error$(@Unsigned @LongLong long checkingTypes, NSError[] error);
@ObjCMethodSign(sign = "+ (NSDataDetector *)dataDetectorWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error;", selector = "dataDetectorWithTypes:error:")
public static native NSDataDetector dataDetectorWithTypes$error$(@Unsigned @LongLong long checkingTypes, NSError[] error);
}
| true |
82b27f64f91d378ca4cac95fb2ac681341c455c3 | Java | uladzik1993/EPAM_Training | /by/epam/training/module02/decomposition/task03/Module02Task03.java | UTF-8 | 587 | 3.609375 | 4 | [] | no_license | package by.epam.training.module02.decomposition.task03;
// Вычислить площадь правильного шестиугольника со стороной а,
// используя метод вычисления площади треугольника.
public class Module02Task03 {
public static void main(String[] args) {
int a = 3;
System.out.printf("Площадь шестиугольника равна: " + 6 * areaTriangle(a));
}
public static double areaTriangle(int a) {
return (Math.sqrt(3) / 4) * Math.pow(a, 2);
}
}
| true |
b1916a0ad8487f269492327b4aeefd93ceb7f5b7 | Java | alexChanCN/turing | /src/main/java/cn/edu/hdu/lab505/tlts/service/PunchService.java | UTF-8 | 5,389 | 2.328125 | 2 | [] | no_license | package cn.edu.hdu.lab505.tlts.service;
import cn.edu.hdu.lab505.tlts.common.AbstractCurdServiceSupport;
import cn.edu.hdu.lab505.tlts.common.AppException;
import cn.edu.hdu.lab505.tlts.common.ICurdDaoSupport;
import cn.edu.hdu.lab505.tlts.dao.IAttendanceDao;
import cn.edu.hdu.lab505.tlts.dao.IPunchDao;
import cn.edu.hdu.lab505.tlts.dao.IStudentDao;
import cn.edu.hdu.lab505.tlts.domain.Attendance;
import cn.edu.hdu.lab505.tlts.domain.Lesson;
import cn.edu.hdu.lab505.tlts.domain.Punch;
import cn.edu.hdu.lab505.tlts.domain.Student;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by hhx on 2017/1/10.
*/
@Service
public class PunchService extends AbstractCurdServiceSupport<Punch> implements IPunchService {
@Autowired
private IPunchDao punchDao;
@Autowired
private IStudentDao studentDao;
@Autowired
private IAttendanceDao attendanceDao;
@Autowired
private ILessonService lessonService;
@Autowired
private Cache punchTimeCache;
private final static String punch_time_key = "punch";
private final static long allow_time = 3 * 60 * 1000;
private Cache getPunchTimeCache() {
return punchTimeCache;
}
public IAttendanceDao getAttendanceDao() {
return attendanceDao;
}
public ILessonService getLessonService() {
return lessonService;
}
@Override
protected ICurdDaoSupport<Punch> getCurdDao() {
return punchDao;
}
protected IStudentDao getStudentDao() {
return studentDao;
}
@Transactional
private void punch(Student student, Date date) throws AppException {
Punch origin = ((IPunchDao) getCurdDao()).getByStudentAndDate(student, date);
if (origin != null) {
throw new AppException("无需重复签到!");
}
Punch punch = new Punch();
punch.setDate(date);
punch.setStudent(student);
((IPunchDao) getCurdDao()).insert(punch);
}
@Override
public String studentPunch(Student student) throws AppException {
long timestamp = System.currentTimeMillis();
Element element = getPunchTimeCache().get(punch_time_key);
if (element != null) {
long punchTime = (long) element.getObjectValue();
if ((timestamp - punchTime) <= allow_time) {
punch(student, new Date());
return String.valueOf(student.getName() + "同学,你已签到成功!");
} else {
throw new AppException("只能在规定的时间内签到。");
}
} else {
throw new AppException("只能在规定的时间内签到。");
}
}
@Override
@Transactional
public String studentPunch(String weChatId) throws AppException {
Student student = getStudentDao().getByWeChatId(weChatId);
if (student == null) {
throw new AppException("您尚未绑定,请输入学号姓名进行绑定,如:123456某某");
}
return String.valueOf(studentPunch(student));
}
@Override
@Transactional
public void studentPunch(Student student, Date date) throws AppException {
punch(student, date);
}
@Override
@Transactional()
public String letPunch() throws AppException {
Lesson lesson = getLessonService().getDefaultLesson();
if (lesson == null) {
throw new AppException("目前没有任何班级");
}
long punchTime = System.currentTimeMillis();
getPunchTimeCache().put(new Element(punch_time_key, punchTime));
Date date = new Date();
Attendance attendance = getAttendanceDao().getByLessonAndDate(lesson, date);
if (attendance == null) {
attendance = new Attendance();
attendance.setDate(date);
attendance.setLesson(lesson);
getAttendanceDao().insert(attendance);
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String s = simpleDateFormat.format(date);
return "开始签到时间为:" + s + ",三分钟内允许签到。";
}
@Override
@Transactional(readOnly = true)
public List<Punch> findByLesson(Lesson lesson) {
List<Attendance> attendanceList = getAttendanceDao().findByLesson(lesson);
if (attendanceList.isEmpty()) {
return new ArrayList<>();
}
Date start = attendanceList.get(attendanceList.size() - 1).getDate();
Date end = attendanceList.get(0).getDate();
List<Punch> punches = ((IPunchDao) getCurdDao()).findByDate(start, end);
return punches;
}
@Override
public List<Punch> findDefaultLessonPunch() {
Lesson lesson = getLessonService().getDefaultLesson();
return findByLesson(lesson);
}
@Override
@Transactional
public int deleteByStudentAndDate(Long sid, Date date) {
Student student = new Student();
student.setId(sid);
return ((IPunchDao) getCurdDao()).deleteByStudentAndDate(student, date);
}
}
| true |
c2c568ef177d2f4eb0e632544da7982b744a8d71 | Java | technokratos/zuul-eureka-rest-example | /capture/src/test/java/com/ognio/rest/MainTest.java | UTF-8 | 2,373 | 2.359375 | 2 | [] | no_license | package com.ognio.rest;
import com.ognio.rest.api.CaptureController;
import com.ognio.rest.api.data.Area;
import com.ognio.rest.api.data.Feature;
import com.ognio.rest.api.data.FeatureCollection;
import com.ognio.rest.api.data.Point;
import com.ognio.rest.service.MappingService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
/**
* Get a location point in a certain area;
* Conquer a location point;
* Show your score;
*
* @author Denis B. Kulikov<br/>
* date: 24.08.2019:21:16<br/>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = CaptureGameRest.class)
public class MainTest {
private static final long FIRST_CLIENT_ID = 1L;
private static final Long SECOND_CLIENT_ID = 2L;
private static final Area AREA = new Area(new Point(new double[]{-0.5946078, 51.5235359}), new Point(new double[]{-0.1355294, 52.6008404}));
@Autowired
private CaptureController captureController;
@Autowired
private MappingService mappingService;
@Test
public void test() {
FeatureCollection points = captureController.getPoints(AREA);
Long firstPoint = points.getFeatures().keySet().iterator().next();
Feature firstFeature = points.getFeatures().get(firstPoint);
assertTrue("The point should be captured by first request", captureController.conquer(FIRST_CLIENT_ID, firstFeature.getGeometry()));
assertFalse("The point should not be captured by second request", captureController.conquer(SECOND_CLIENT_ID, firstFeature.getGeometry()));
assertFalse("The point already captured by the same client", captureController.conquer(FIRST_CLIENT_ID, firstFeature.getGeometry()));
assertEquals("The frist client should capture 1 point", Long.valueOf(3), captureController.score(FIRST_CLIENT_ID));
assertEquals("The frist client should capture 1 point", Long.valueOf(0), captureController.score(SECOND_CLIENT_ID));
FeatureCollection updatedPoints = captureController.getPoints(AREA);
assertFalse("The udpated points should not be contained already captured point", updatedPoints.getFeatures().containsKey(firstPoint));
}
}
| true |
470a7230e209636e3529880c7febba99d3a806b6 | Java | AhmedKhMasoud/MyGraduationProject | /app/src/main/java/com/ArabProgrammers/CollegeProject/uploadIndexAndName.java | UTF-8 | 609 | 2.578125 | 3 | [] | no_license | package com.ArabProgrammers.CollegeProject;
public class uploadIndexAndName {
private String arrName;
private int arrIndex;
public uploadIndexAndName() {
}
public uploadIndexAndName(String arrName, int arrIndex) {
this.arrName = arrName;
this.arrIndex = arrIndex;
}
public String getArrName() {
return arrName;
}
public void setArrName(String arrName) {
this.arrName = arrName;
}
public int getArrIndex() {
return arrIndex;
}
public void setArrIndex(int arrIndex) {
this.arrIndex = arrIndex;
}
}
| true |
29a7a3b9663ad98adcaf28912ee3a117e7e99573 | Java | chase3718/BCJavaExcercises | /stuffy-jpa-demo/src/main/java/com/stuffy/StuffyJpaDemoApplication.java | UTF-8 | 3,258 | 3.1875 | 3 | [] | no_license | package com.stuffy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.List;
import com.stuffy.business.Stuffy;
import com.stuffy.db.StuffyDB;
import com.stuffy.util.*;
@SpringBootApplication
public class StuffyJpaDemoApplication {
public static void main(String[] args) {
SpringApplication.run(StuffyJpaDemoApplication.class, args);
System.out.println("Welcome to the Stuffy Dispenser");
displayMenu();
String action = "";
while (!action.equalsIgnoreCase("exit")) {
action = Console.getString("Enter a command: ", true, "list", "add", "del", "help", "exit", "sel");
if (action.equalsIgnoreCase("list")) {
displayAllStuffies();
} else if (action.equalsIgnoreCase("add")) {
addStuffy();
} else if (action.equalsIgnoreCase("del")) {
deleteStuffy();
} else if (action.equalsIgnoreCase("help")) {
displayMenu();
} else if (action.equalsIgnoreCase("sel")) {
selectStuffy();
}
}
System.out.println("Bye");
}
public static void displayMenu() {
System.out.println("Command Menu");
System.out.println("===============================");
System.out.println("list - List all stuffies");
System.out.println("sel - Select a stuffy");
System.out.println("add - Add a stuffy");
System.out.println("del - Delete a stuffy");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application");
}
private static void displayAllStuffies() {
System.out.println("Stuffy List");
System.out.println("==========================================");
List<Stuffy> stuffies = StuffyDB.getAll();
StringBuilder sb = new StringBuilder();
for (Stuffy p : stuffies) {
sb.append(StringUtils.padWithSpaces(p.getId(), 4));
sb.append(StringUtils.padWithSpaces(p.getType(), 10));
sb.append(StringUtils.padWithSpaces(p.getColor(), 10));
sb.append(StringUtils.padWithSpaces(p.getSize(), 10));
sb.append(p.getLimbs());
sb.append("\n");
}
System.out.println(sb.toString());
}
private static void selectStuffy() {
int id = Console.getInt("Select a stuffy by ID: ");
Stuffy s = StuffyDB.get(id);
if (s != null) {
System.out.println("You chose a " + s.getSize() + ", " + s.getColor() + " " + s.getType() + " with " + s.getLimbs() + " limbs.");
} else {
System.out.println("That stuffy does not exist");
}
}
private static void addStuffy() {
String type = Console.getString("Enter stuffy type: ", true);
String color = Console.getString("Enter stuffy color: ", true);
String size = Console.getString("Enter stuffy size: ", true, "x-small", "small", "medium", "large", "x-large",
"xs", "s", "m", "l", "xl");
int limbs = Console.getInt("Enter number of limbs: ", -1, 100);
Stuffy stuffy = new Stuffy(type, color, size, limbs);
StuffyDB.insert(stuffy);
System.out.println("Stuffy has been added.\n");
}
private static void deleteStuffy() {
int code = Console.getInt("Enter stuffy ID to delete: ");
Stuffy p = StuffyDB.get(code);
if (p != null) {
StuffyDB.delete(p);
System.out.println("Stuffy has been deleted.\n");
} else {
System.out.println("No stuffy matches that ID.\n");
}
}
}
| true |
c0aab5f53437455d14b33c1847145bc465817326 | Java | angrylittlebird/juc | /src/main/java/com/learning/flowcontrol/countdownlatch/CountDownLatchDemo3.java | UTF-8 | 1,730 | 3.65625 | 4 | [] | no_license | package com.learning.flowcontrol.countdownlatch;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @Author: ZHANG
* @Date: 2020/3/8
* @Description: 互相等待
*/
public class CountDownLatchDemo3 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch begin = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(5);
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
int finalI = i;
Runnable task = () -> {
try {
System.out.println("runner " + (finalI + 1) + " is ready.");
begin.await();
System.out.println("runner " + (finalI + 1) + " start running.");
TimeUnit.SECONDS.sleep(3);
System.out.println("runner " + (finalI + 1) + " crossed end point.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
end.countDown();
}
};
executorService.submit(task);
}
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + ": transmit signal grab.");
begin.countDown();
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + ": wait all runners to cross end point.");
end.await();
System.out.println(Thread.currentThread().getName() + ": race is over.");
executorService.shutdown();
}
}
| true |
f73278cf8ec1b034c25a8a9a589d5bbff43d1fe1 | Java | shwndi/ThinkInJava | /src/dataType/BufferAndString.java | UTF-8 | 862 | 3.59375 | 4 | [] | no_license | package dataType;
/**
* 引用和值的区别
*
* @author czy
* @date 2020-12-17
*/
public class BufferAndString {
public static void main(String[] args) {
String s1 = "hellow";
String s2 = "world";
change(s1, s2);
StringBuffer b1 = new StringBuffer("hellow");
StringBuffer b2 = new StringBuffer("world");
change(b1, b2);
System.out.println(s1 + "------------" + s2);
System.out.println(b1 + "------------" + b2);
// List b = Arrays.asList(1,2,3,4,5);
// List list = b.subList(0, b.indexOf(3));
// System.out.println(list);
// System.out.println(b.indexOf(3));
}
private static void change(StringBuffer b1, StringBuffer b2) {
b1 = b2;
b2.append(b1);
}
private static void change(String s1, String s2) {
s1 = s2;
s2 = s1 + s2;
}
}
| true |
3b5b56719f372bb5c281605c508fe1a5f3c8556d | Java | soulcure/airplay | /DongleClient/core/src/main/java/swaiotos/channel/iot/im/Message.java | UTF-8 | 2,821 | 2.46875 | 2 | [] | no_license | package swaiotos.channel.iot.im;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
public class Message {
public enum CMD {
CONNECT,
DISCONNECT,
UPDATE,
GET_CLIENT,
REPLY,
ONLINE,
OFFLINE,
BIND,
UNBIND,
UPDATE_DEVICE_INFO,
JOIN,
LEAVE
}
final String id;
final long timestamp;
final CMD cmd;
final String source;
final Map<String, String> payload;
Message(String id, CMD cmd, String source, Map<String, String> payload) {
this.id = id;
this.cmd = cmd;
this.source = source;
this.timestamp = System.currentTimeMillis();
this.payload = payload != null ? payload : new LinkedHashMap<String, String>();
}
Message(String in) throws JSONException {
JSONObject object = new JSONObject(in);
id = object.getString("id");
cmd = CMD.valueOf(object.getString("cmd"));
source = object.getString("source");
timestamp = object.getLong("timestamp");
payload = new LinkedHashMap<>();
JSONObject extra = object.getJSONObject("payload");
Iterator<String> keys = extra.keys();
while (keys.hasNext()) {
String key = keys.next();
payload.put(key, extra.getString(key));
}
}
public Message(Message.CMD cmd, String source) {
this(cmd, source, null);
}
public Message(Message.CMD cmd, String source, Map<String, String> payload) {
this(UUID.randomUUID().toString(), cmd, source, payload);
}
public Message reply(String source) {
return new Message(id, Message.CMD.REPLY, source, null);
}
public String getPayload(String key) {
return payload.get(key);
}
public void putPayload(String key, String value) {
payload.put(key, value);
}
@Override
public String toString() {
JSONObject object = new JSONObject();
try {
object.put("id", id);
} catch (JSONException e) {
e.printStackTrace();
}
try {
object.put("cmd", cmd.name());
} catch (JSONException e) {
e.printStackTrace();
}
try {
object.put("source", source);
} catch (JSONException e) {
e.printStackTrace();
}
try {
object.put("timestamp", timestamp);
} catch (JSONException e) {
e.printStackTrace();
}
try {
object.put("payload", new JSONObject(payload));
} catch (JSONException e) {
e.printStackTrace();
}
return object.toString();
}
}
| true |
f731b7b4acb920fcd5db905937a56047cda5a729 | Java | KnHdd0126/LeetCoder | /A283_MoveZeroes.java | UTF-8 | 402 | 2.4375 | 2 | [] | no_license | package leetcoder.LeetCoder;
/**
* Created by yanghang on 2018/3/30.
* for The knowledge system
*/
public class A283_MoveZeroes {
public void moveZeroes(int[] nums) {
int isNotZeroCounts = 0;
for(int num:nums){
if(num!=0) nums[isNotZeroCounts++] = num;
}
while (isNotZeroCounts<nums.length){
nums[isNotZeroCounts++]=0;
}
}
}
| true |
bc7b3181144795fd4dbc1691717fce5bca175c95 | Java | yezheny/MvpOkhttpUtils | /OkHttpUtils/src/main/java/com/pcjz/http/okhttp/exception/FromJsonToBeanFailException.java | UTF-8 | 342 | 1.984375 | 2 | [] | no_license | package com.pcjz.http.okhttp.exception;
/**
* 从JSON转换成BEAN的异常
*
*/
public class FromJsonToBeanFailException extends Exception {
private static final long serialVersionUID = 5895223930808591547L;
public FromJsonToBeanFailException(String msg) {
super(msg);
}
public FromJsonToBeanFailException() {
super();
}
}
| true |
58a60ed0aa3cb495a08dfc51c5f29e9b29b27954 | Java | tairoroberto/PageView | /app/src/main/java/br/com/digitalhouse/pageview/MainActivity.java | UTF-8 | 2,341 | 2.75 | 3 | [] | no_license | package br.com.digitalhouse.pageview;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private LinearLayout linearCategories;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
linearCategories = findViewById(R.id.linearCategories);
// Lista de fragmentos para mostrar, aqui coloquei 4 fotos
List<Fragment> fragments = new ArrayList<>();
fragments.add(PhotoFragment.newInstance(R.drawable.android_image, "Android texto de test 1"));
fragments.add(PhotoFragment.newInstance(R.drawable.android_image_2, "Android texto de test 2"));
fragments.add(PhotoFragment.newInstance(R.drawable.android_image, "Android texto de test 3"));
fragments.add(PhotoFragment.newInstance(R.drawable.android_image_2, "Android texto de test 4"));
// pageStateAdapter para mostrar os fragmentos de fotos no view pager
PhotoPageStateAdapter pageStateAdapter = new PhotoPageStateAdapter(getSupportFragmentManager(), fragments);
// Vincula o pageStateAdapter com o viewpager
viewPager.setAdapter(pageStateAdapter);
// For para a quantidade de categorias aqui estou percorrendo 5 vezes
//adicionar os items dinamicamente no container
for (int i = 0; i < 5; i++) {
addCategoryListItems(linearCategories, "Texto para a categoria " + i);
}
}
// seto o texto e adiciono no container
private void addCategoryListItems(LinearLayout container, String text) {
//Infla o layout
LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.category_item, null);
//Procura a view do texto
TextView textViewCategory = layout.findViewById(R.id.category_item_name);
//seta o texto
textViewCategory.setText(text);
//adiciona no container
container.addView(layout);
}
}
| true |
7937b4fe6426220ae467569d9072bb5f21db9b09 | Java | blackoon/valley-api | /src/main/java/com/hylanda/api/PowerController.java | UTF-8 | 1,289 | 1.765625 | 2 | [] | no_license | package com.hylanda.api;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author zhangy
* @E-mail:blackoon88@gmail.com
* @version 创建时间:2017年12月8日 下午3:58:15
* note
*/
@Controller
@RequestMapping("/powerbi")
public class PowerController {
@RequestMapping(value = { "/" }, method = RequestMethod.GET)
public void getPowerBi(HttpServletRequest request,HttpServletResponse response){
}
@RequestMapping(value = { "/api/explore/reports/{id}/modelsAndExploration" }, method = RequestMethod.GET)
public void getReportsModelsAndExploration(HttpServletRequest request,HttpServletResponse response){
}
@RequestMapping(value = { "/api/explore/reports/{id}/conceptualschema" }, method = RequestMethod.POST)
public void getReportsConceptualschema(HttpServletRequest request,HttpServletResponse response){
}
@RequestMapping(value = { "/api/explore/reports/{id}/querydata" }, method = RequestMethod.POST)
public void getReportsquerydata(HttpServletRequest request,HttpServletResponse response){
}
}
| true |
aab4d9f07b25f4d2c3a268411a9dea98d7b67b06 | Java | Techopath/JavaProgrammingB15VA | /src/day_14_string_manipulation/stringStartsEndsWith.java | UTF-8 | 1,539 | 3.84375 | 4 | [] | no_license | package day_14_string_manipulation;
public class stringStartsEndsWith {
public static void main(String[] args) {
String selenium = "Selenium";
System.out.println(selenium.startsWith("sel"));//true
System.out.println(selenium.endsWith("ium"));//true
System.out.println(selenium.startsWith("Sel"));
System.out.println(selenium.contains("len"));
System.out.println(selenium.endsWith(" um")); ///false because of space
//Mr. --> man
//Mrs ..> married woman
// Ms. ..> single woman
//Dr. ..> Doctor
//Prof. ..> Professor
String name ="Mr.Omer, Ms.Aysha";
if (name.startsWith("Mr.")){
System.out.println("Man");
}else if (name.startsWith("Ms")){
System.out.println("Single woman");
}else if (name.startsWith("Dr.")){
System.out.println("Doctor");
}else if (name.startsWith("Mrs.")){
System.out.println("Married woman");
}else if (name.startsWith("Prof.")) {
System.out.println("Professor");
}
System.out.println(name.contains("Ms."));
//website google.com
String website = "www.google.com";
//if website ends with .com print english site
//if website ends with .gov print government
if (website.endsWith(".com")){
System.out.println("English website");
}else if (website.endsWith(".gov")){
System.out.println("Governmental website");
}
}
}
| true |
1e400e2511bbaf117b35a1a5393228cbc3536e19 | Java | qiuchili/ggnn_graph_classification | /program_data/github_java_program_data/38/305.java | UTF-8 | 1,679 | 2.71875 | 3 | [
"MIT"
] | permissive | package trans;
import main.Updater;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.Collection;
/**
* Created by Barr on 29-Sep-14.
*
*/
public class Queue extends AbstractAnalyser {
public Queue(Updater i) {
super(i);
}
@Override
public String getNameOfClass() {
return "Queue";
}
@Override
public ClassNode identify(Collection<ClassNode> classNodes) {
for (ClassNode classNode : classNodes){
int amountOfNodes = 0, found = 0;
if (classNode.superName.equals("java/lang/Object")){
for (FieldNode fieldNode : classNode.fields){
if (fieldNode.desc.equals(String.format("L%s;", instance.getClassName("CacheableNode"))) && fieldNode.access == 0x0000){
found++;
}
amountOfNodes++;
}
}
if (found == 1 && amountOfNodes == 1){
return classNode;
}
}
return null;
}
@Override
public ClassNode manipulate(ClassNode classNode) {
if (classNode != null){
System.out.println("* Queue '" + classNode.name + "' [Extends " + classNode.superName + "]");
for (FieldNode fieldNode : classNode.fields) {
System.out.println(" ~ Head() : " + classNode.name + "." + fieldNode.name);
}
} else {
System.out.println("* Queue 'BROKEN'");
}
System.out.println();
return classNode;
}
}
| true |
3242fb1e728488499fb1bd4c469b7a01a2510467 | Java | fanyi3315/ghidrARMloader | /src/main/java/ghidrarmloader/ARMRegister.java | UTF-8 | 2,597 | 2.703125 | 3 | [] | no_license | package ghidrarmloader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
public class ARMRegister {
String Name;
String PeriphName;
Integer Offset;
Integer Address;
Integer Size;
Integer Dbid;
Integer InitVal;
Boolean HaveFlags = false;
ArrayList<ARMField> Fields;
HashMap<Integer, ARMField> FieldsByDbid = new HashMap<Integer, ARMField>();
protected Boolean haveFlags() {
return HaveFlags;
}
public ARMRegister(String periphname, String name, Integer offset, Integer address, Integer size, Integer dbid,Integer initval) {
super();
Name = name;
Offset = offset;
Address = address;
Dbid = dbid;
Size = size;
PeriphName = periphname;
InitVal = initval;
Fields = new ArrayList<ARMField>();
}
protected Integer getInitVal() {
return InitVal;
}
public String getCStructName() {
if (Name.length() < PeriphName.length())
return PeriphName + "_" + Name;
if (Name.substring(0, PeriphName.length()) != PeriphName)
return PeriphName + "_" + Name;
return Name;
}
public String getCStruct() {
// Apparently Ghidra doesn't decompile bitfields access so well.. yet...
// Still this is not a reason to be ready for the moment it does...
String ret = "struct {\n";
Integer curroff = 0;
Integer reservedcnt = 0;
// by construction this is "order by offset"
if (!HaveFlags)
return "";
for (ARMField f : Fields) {
if (f.getOffset() > curroff) {
ret += "unsigned int RESERVED_" + reservedcnt.toString()
+ " :"
+ Integer.toString(f.getOffset() - curroff) + ";\n";
curroff = f.getOffset() ;
reservedcnt++;
}
ret += "unsigned int " + f.getName() + " :" + f.getBitWidth() + ";\n";
curroff += f.getBitWidth();
}
ret += "} " + getCStructName() + " ;";
///System.out.println(ret);
return ret;
}
public void addField(String fname, Integer foffset, Integer fbitwidth, Integer faccess, String fdescr,
Integer dbid) {
ARMField f = new ARMField(dbid, fbitwidth, foffset, faccess, fname, fdescr);
Fields.add(f);
FieldsByDbid.put(dbid, f);
HaveFlags = true;
}
public void addField(String fname, Integer foffset, Integer fbitwidth, Integer faccess, Integer dbid) {
addField(fname, foffset, fbitwidth, faccess, "", dbid);
}
protected String getName() {
return Name;
}
protected Integer getOffset() {
return Offset;
}
protected Integer getAddress() {
return Address;
}
protected Integer getSize() {
return Size;
}
protected Integer getDbid() {
return Dbid;
}
Set<Integer> getFieldsDbids() {
return FieldsByDbid.keySet();
}
}
| true |
bb0b4697a041419a4a7643575f1fa79032c87c0e | Java | AvinashTiwari/TestingFramework | /Generic/src/main/java/collection/hashsample/Hash5.java | UTF-8 | 309 | 2.296875 | 2 | [] | no_license | package collection.hashsample;
import java.util.LinkedList;
public class Hash5 {
public static void main(String[] args) {
var list = new LinkedList<>();
list.add(5);
list.add(6);
list.addFirst(7);
list.addLast(8);
var firstppek = list.peek();
}
}
| true |
7468c7f4d6fdfeb31043de2fb083e21a67c9e5e8 | Java | Timk90/web-service-soap | /src/main/java/com/servicesoapex/mapperService/MapperService.java | UTF-8 | 1,557 | 2.5 | 2 | [] | no_license | package com.servicesoapex.mapperService;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.servicesoapex.dao.ResultDAO;
import com.servicesoapex.mapper.MapperResultDAO;
import com.servicesoapex.util.MyServiceUtil;
/*
* Работа с БД осуществляется через сервис, а не непосредственно через маппер.
* Это позволяется добавлять проверки и использовать разные мапперы при необходимости.
* В частности, здесь добавлена проверка кода результата. Если поиск числа завершился с кодом ОК,
* то данные заносятся в БД, в противном случае ничего не происходит.
*/
@Service
public class MapperService {
final static Logger logger = Logger.getLogger(MapperService.class);
@Autowired
MapperResultDAO mapper;
//два метода обертки для маппера
public void insert(ResultDAO result) {
//Проверка кода результата, если записи найдены, то запись попадает в БД.
if(result.getCode().equals("00.Result.OK")) {
mapper.insertResult(result);
logger.info("Note has been added to DB "+ result);
}
}
public List<ResultDAO> selectAll(){
return mapper.allResults();
}
}
| true |
daf9fde5f7bfe327333ad75f0b18abd1609f775c | Java | kenyujy/concurrentDemo | /src/main/java/c2t2_ReentryLock/ReentryLock2.java | UTF-8 | 1,089 | 3.734375 | 4 | [] | no_license | package c2t2_ReentryLock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentryLock2 {
Lock lock= new ReentrantLock(); //ReentrantLock 必须手动释放
void m1(){
try{
lock.lock(); //synchronized(this)
for (int i=0; i<10; i++){
TimeUnit.SECONDS.sleep(1);
System.out.println(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock(); //手动释放锁
}
}
void m2(){
lock.lock(); //锁定同一把锁
System.out.println("m2 ....");
lock.unlock(); //手动释放锁
}
public static void main(String[] args){
ReentryLock2 r2 = new ReentryLock2();
new Thread(()->r2.m1()).start();
try{
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->r2.m2()).start();
}
}
| true |
e29ab5761ebb3a6b8e19edd2fa5c867f26a7674a | Java | LutherDub/nomina | /src/vistas/ComplementoVista.java | UTF-8 | 18,627 | 2.03125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vistas;
/**
*
* @author LuiferV
*/
public class ComplementoVista extends javax.swing.JDialog {
/**
* Creates new form ComplementoVista
*/
public ComplementoVista(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jpnconsultar = new javax.swing.JPanel();
btnconsultarcomplemento = new javax.swing.JButton();
lblconsultacomplemento = new javax.swing.JTextField();
lblcomplemento1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jlbcomplemento = new javax.swing.JLabel();
lblcomplemento = new javax.swing.JLabel();
txtcomplemento = new javax.swing.JTextField();
lblnombrecomplemento = new javax.swing.JLabel();
txtnombrecomplemento = new javax.swing.JTextField();
lbldescripcion = new javax.swing.JLabel();
txtdescripcioncomplemento = new javax.swing.JTextField();
lblestadocomplemento = new javax.swing.JLabel();
txtestadocomplemento = new javax.swing.JTextField();
lblvalorcomplemento = new javax.swing.JLabel();
txtvalorcomplemento = new javax.swing.JTextField();
btnguardarcomplemento = new javax.swing.JButton();
btnlimpiarcomplemento = new javax.swing.JButton();
btnactualizarcomplemento = new javax.swing.JButton();
btneliminarcomplemento = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tbcomplemento = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jpnconsultar.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102)), "Consultar Complementos"));
btnconsultarcomplemento.setText("Consultar");
btnconsultarcomplemento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnconsultarcomplementoActionPerformed(evt);
}
});
lblconsultacomplemento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lblconsultacomplementoActionPerformed(evt);
}
});
lblcomplemento1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblcomplemento1.setText("Id Complemento");
javax.swing.GroupLayout jpnconsultarLayout = new javax.swing.GroupLayout(jpnconsultar);
jpnconsultar.setLayout(jpnconsultarLayout);
jpnconsultarLayout.setHorizontalGroup(
jpnconsultarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpnconsultarLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblcomplemento1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblconsultacomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnconsultarcomplemento)
.addContainerGap())
);
jpnconsultarLayout.setVerticalGroup(
jpnconsultarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpnconsultarLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jpnconsultarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnconsultarcomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblconsultacomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblcomplemento1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)), "Agregar"));
jlbcomplemento.setFont(new java.awt.Font("Calibri Light", 1, 24)); // NOI18N
jlbcomplemento.setText("Complementos");
lblcomplemento.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblcomplemento.setText("Id Complemento");
lblnombrecomplemento.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblnombrecomplemento.setText("Nombre");
lbldescripcion.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lbldescripcion.setText("Descripcion");
txtdescripcioncomplemento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtdescripcioncomplementoActionPerformed(evt);
}
});
lblestadocomplemento.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblestadocomplemento.setText("Estado");
lblvalorcomplemento.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblvalorcomplemento.setText("Valor");
btnguardarcomplemento.setText("Guardar");
btnguardarcomplemento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnguardarcomplementoActionPerformed(evt);
}
});
btnlimpiarcomplemento.setText("Limpiar");
btnactualizarcomplemento.setText("Actualizar");
btneliminarcomplemento.setText("Eliminar");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblcomplemento)
.addComponent(lblnombrecomplemento)
.addComponent(lbldescripcion)
.addComponent(lblestadocomplemento)
.addComponent(lblvalorcomplemento))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtcomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtdescripcioncomplemento)
.addComponent(txtnombrecomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtestadocomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtvalorcomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 21, Short.MAX_VALUE)
.addComponent(btnguardarcomplemento)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnlimpiarcomplemento)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnactualizarcomplemento)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btneliminarcomplemento)
.addGap(21, 21, 21))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jlbcomplemento)
.addGap(87, 87, 87))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jlbcomplemento)
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtcomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblcomplemento))
.addGap(29, 29, 29)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblnombrecomplemento)
.addComponent(txtnombrecomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbldescripcion)
.addComponent(txtdescripcioncomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtestadocomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblestadocomplemento))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtvalorcomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblvalorcomplemento))
.addGap(48, 48, 48)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnguardarcomplemento)
.addComponent(btnlimpiarcomplemento)
.addComponent(btnactualizarcomplemento)
.addComponent(btneliminarcomplemento))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
tbcomplemento.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Nombres", "Descripcion", "Estado", "Valor"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tbcomplemento);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE)
.addComponent(jpnconsultar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jpnconsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(21, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnconsultarcomplementoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnconsultarcomplementoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnconsultarcomplementoActionPerformed
private void lblconsultacomplementoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lblconsultacomplementoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_lblconsultacomplementoActionPerformed
private void txtdescripcioncomplementoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtdescripcioncomplementoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtdescripcioncomplementoActionPerformed
private void btnguardarcomplementoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnguardarcomplementoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnguardarcomplementoActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ComplementoVista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ComplementoVista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ComplementoVista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ComplementoVista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ComplementoVista dialog = new ComplementoVista(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnactualizarcomplemento;
private javax.swing.JButton btnconsultarcomplemento;
private javax.swing.JButton btneliminarcomplemento;
private javax.swing.JButton btnguardarcomplemento;
private javax.swing.JButton btnlimpiarcomplemento;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel jlbcomplemento;
private javax.swing.JPanel jpnconsultar;
private javax.swing.JLabel lblcomplemento;
private javax.swing.JLabel lblcomplemento1;
private javax.swing.JTextField lblconsultacomplemento;
private javax.swing.JLabel lbldescripcion;
private javax.swing.JLabel lblestadocomplemento;
private javax.swing.JLabel lblnombrecomplemento;
private javax.swing.JLabel lblvalorcomplemento;
private javax.swing.JTable tbcomplemento;
private javax.swing.JTextField txtcomplemento;
private javax.swing.JTextField txtdescripcioncomplemento;
private javax.swing.JTextField txtestadocomplemento;
private javax.swing.JTextField txtnombrecomplemento;
private javax.swing.JTextField txtvalorcomplemento;
// End of variables declaration//GEN-END:variables
}
| true |
82b42afb8066a4a1091d2401a7aa0114586fcce3 | Java | njuNbaAnalysis/nba_analysis | /NBA_analysis/src/main/java/compare/PlayerFoulsComp.java | UTF-8 | 288 | 2.703125 | 3 | [] | no_license | package compare;
import java.util.Comparator;
import logic.players.Player;
public class PlayerFoulsComp implements Comparator<Player> {
public int compare(Player o1, Player o2) {
// TODO Auto-generated method stub
return (int)(o2.getFouls() - o1.getFouls());
}
}
| true |
b611f9df3a8a53fd351603313b4b54c89e475ed1 | Java | PhuongThao09/ZingMP3 | /Tool/dex2jar/out/com/google/android/gms/common/i.java | UTF-8 | 2,920 | 1.601563 | 2 | [] | no_license | //
// Decompiled by Procyon v0.5.30
//
package com.google.android.gms.common;
import android.app.PendingIntent;
import com.google.android.gms.common.internal.safeparcel.a;
import android.os.Parcelable;
import com.google.android.gms.common.internal.safeparcel.b;
import android.os.Parcel;
import android.os.Parcelable$Creator;
public class i implements Parcelable$Creator<ConnectionResult>
{
static void a(final ConnectionResult connectionResult, final Parcel parcel, final int n) {
final int a = b.a(parcel);
b.a(parcel, 1, connectionResult.b);
b.a(parcel, 2, connectionResult.c());
b.a(parcel, 3, (Parcelable)connectionResult.d(), n, false);
b.a(parcel, 4, connectionResult.e(), false);
b.a(parcel, a);
}
public ConnectionResult a(final Parcel parcel) {
String g = null;
int n = 0;
final int b = a.b(parcel);
PendingIntent pendingIntent = null;
int n2 = 0;
while (parcel.dataPosition() < b) {
final int a = com.google.android.gms.common.internal.safeparcel.a.a(parcel);
int n4 = 0;
int n5 = 0;
switch (com.google.android.gms.common.internal.safeparcel.a.a(a)) {
default: {
com.google.android.gms.common.internal.safeparcel.a.b(parcel, a);
final int n3 = n;
n4 = n2;
n5 = n3;
break;
}
case 1: {
final int d = com.google.android.gms.common.internal.safeparcel.a.d(parcel, a);
n5 = n;
n4 = d;
break;
}
case 2: {
final int d2 = com.google.android.gms.common.internal.safeparcel.a.d(parcel, a);
n4 = n2;
n5 = d2;
break;
}
case 3: {
pendingIntent = com.google.android.gms.common.internal.safeparcel.a.a(parcel, a, (android.os.Parcelable$Creator<PendingIntent>)PendingIntent.CREATOR);
final int n6 = n2;
n5 = n;
n4 = n6;
break;
}
case 4: {
g = com.google.android.gms.common.internal.safeparcel.a.g(parcel, a);
final int n7 = n2;
n5 = n;
n4 = n7;
break;
}
}
final int n8 = n4;
n = n5;
n2 = n8;
}
if (parcel.dataPosition() != b) {
throw new a.a("Overread allowed size end=" + b, parcel);
}
return new ConnectionResult(n2, n, pendingIntent, g);
}
public ConnectionResult[] a(final int n) {
return new ConnectionResult[n];
}
}
| true |
a0a7104659dbba851e298a3d492c1147fa87836c | Java | saudet/deeplearning4j | /rl4j/rl4j-core/src/main/java/org/deeplearning4j/rl4j/learning/sync/qlearning/QLearning.java | UTF-8 | 5,533 | 1.523438 | 2 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown"
] | permissive | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.rl4j.learning.sync.qlearning;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.gym.StepReply;
import org.deeplearning4j.rl4j.learning.sync.ExpReplay;
import org.deeplearning4j.rl4j.learning.sync.IExpReplay;
import org.deeplearning4j.rl4j.learning.sync.SyncLearning;
import org.deeplearning4j.rl4j.mdp.MDP;
import org.deeplearning4j.rl4j.network.dqn.IDQN;
import org.deeplearning4j.rl4j.policy.EpsGreedy;
import org.deeplearning4j.rl4j.space.ActionSpace;
import org.deeplearning4j.rl4j.space.Encodable;
import org.deeplearning4j.rl4j.util.DataManager.StatEntry;
import org.nd4j.linalg.api.ndarray.INDArray;
import java.util.ArrayList;
import java.util.List;
/**
* @author rubenfiszel (ruben.fiszel@epfl.ch) 7/19/16.
* <p>
* Mother class for QLearning in the Discrete domain and
* hopefully one day for the Continuous domain.
*/
@Slf4j
public abstract class QLearning<O extends Encodable, A, AS extends ActionSpace<A>>
extends SyncLearning<O, A, AS, IDQN> {
@Getter
final private IExpReplay<A> expReplay;
public QLearning(QLConfiguration conf) {
super(conf);
expReplay = new ExpReplay<>(conf.getExpRepMaxSize(), conf.getBatchSize(), conf.getSeed());
}
protected abstract EpsGreedy<O, A, AS> getEgPolicy();
public abstract MDP<O, A, AS> getMdp();
protected abstract IDQN getCurrentDQN();
protected abstract IDQN getTargetDQN();
protected abstract void setTargetDQN(IDQN dqn);
protected INDArray dqnOutput(INDArray input) {
return getCurrentDQN().output(input);
}
protected INDArray targetDqnOutput(INDArray input) {
return getTargetDQN().output(input);
}
protected void updateTargetNetwork() {
log.info("Update target network");
setTargetDQN(getCurrentDQN().clone());
}
public IDQN getNeuralNet() {
return getCurrentDQN();
}
public abstract QLConfiguration getConfiguration();
protected abstract void preEpoch();
protected abstract void postEpoch();
protected abstract QLStepReturn<O> trainStep(O obs);
protected StatEntry trainEpoch() {
InitMdp<O> initMdp = initMdp();
O obs = initMdp.getLastObs();
double reward = initMdp.getReward();
int step = initMdp.getSteps();
Double startQ = Double.NaN;
double meanQ = 0;
int numQ = 0;
List<Double> scores = new ArrayList<>();
while (step < getConfiguration().getMaxEpochStep() && !getMdp().isDone()) {
if (getStepCounter() % getConfiguration().getTargetDqnUpdateFreq() == 0) {
updateTargetNetwork();
}
QLStepReturn<O> stepR = trainStep(obs);
if (!stepR.getMaxQ().isNaN()) {
if (startQ.isNaN())
startQ = stepR.getMaxQ();
numQ++;
meanQ += stepR.getMaxQ();
}
if (stepR.getScore() != 0)
scores.add(stepR.getScore());
reward += stepR.getStepReply().getReward();
obs = stepR.getStepReply().getObservation();
incrementStep();
step++;
}
meanQ /= (numQ + 0.001); //avoid div zero
StatEntry statEntry = new QLStatEntry(getStepCounter(), getEpochCounter(), reward, step, scores,
getEgPolicy().getEpsilon(), startQ, meanQ);
return statEntry;
}
@AllArgsConstructor
@Builder
@Value
public static class QLStatEntry implements StatEntry {
int stepCounter;
int epochCounter;
double reward;
int episodeLength;
List<Double> scores;
float epsilon;
double startQ;
double meanQ;
}
@AllArgsConstructor
@Builder
@Value
public static class QLStepReturn<O> {
Double maxQ;
double score;
StepReply<O> stepReply;
}
@Data
@AllArgsConstructor
@Builder
@EqualsAndHashCode(callSuper = false)
@JsonDeserialize(builder = QLConfiguration.QLConfigurationBuilder.class)
public static class QLConfiguration implements LConfiguration {
int seed;
int maxEpochStep;
int maxStep;
int expRepMaxSize;
int batchSize;
int targetDqnUpdateFreq;
int updateStart;
double rewardFactor;
double gamma;
double errorClamp;
float minEpsilon;
int epsilonNbStep;
boolean doubleDQN;
@JsonPOJOBuilder(withPrefix = "")
public static final class QLConfigurationBuilder {
}
}
}
| true |
7f13dfdbe5e25e7d32fc75787ae14483602875f4 | Java | bezpalkovitalii/G48Automation | /src/main/java/projectGitHub/pages/code/CodePage.java | UTF-8 | 745 | 1.984375 | 2 | [] | no_license | package projectGitHub.pages.code;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import projectGitHub.pages.BaseProjectPage;
import projectGitHub.pages.XMLPage;
public class CodePage extends BaseProjectPage {
public CodePage(WebDriver driver) {
super(driver);
}
private final By xml = By.xpath("//a[@title = 'pom.xml']");
private final By commitMessageText = By.xpath("//a[@data-test-selector='commit-tease-commit-message']");
public XMLPage openXML() {
driver.findElement(xml).click();
return new XMLPage(driver);
}
public CodePage showCommitMessage() {
LOG.info(driver.findElements(commitMessageText).get(0).getText());
return this;
}
}
| true |
7dbc68bcd57643b5438f082c1ece4f6ab23a34d5 | Java | ksawant1/VisitorPattern | /arrayvisitors/src/arrayvisitors/visitors/MissingIntsVisitor.java | UTF-8 | 1,870 | 3.34375 | 3 | [] | no_license | package arrayvisitors.visitors;
import arrayvisitors.adt.MyArray;
import arrayvisitors.util.MyLogger;
import arrayvisitors.util.Results;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* a visitor class that finds missing integers stored in myarray and sends to result for printing
* @author Krupa Sawant
*/
public class MissingIntsVisitor implements Visitor {
Results results;
List<Integer> missing = new ArrayList<>();
//sets the result instance
public MissingIntsVisitor(Results results) {
this.results = results;
MyLogger.getInstance().writeMessage("constructor for missingints visitor", MyLogger.DebugLevel.CONSTRUCTOR);
}
//mainly for calling findMissingInt()
public void visit(Element myElement) {
findMissingInt((MyArray) myElement);
MyLogger.getInstance().writeMessage("visit() inside missingintsvisitor calls private methods inside the visitor", MyLogger.DebugLevel.MISSINGINTSVISITOR);
}
private void findMissingInt(MyArray myArray) {
Set<Integer> integers = new TreeSet<>();
MyLogger.getInstance().writeMessage("findingMisssingInt() inside missingintsvisitor counts all numbers between 0 and 99 that are missing int two arrays and prints in results", MyLogger.DebugLevel.MISSINGINTSVISITOR);
//for counting missing integers in arrays and send to results
for (int x : myArray.getArray())
integers.add(x);
List<Integer> missingInteger = IntStream.range(00, 99)
.filter(num -> !integers.contains(num))
.boxed()
.collect(Collectors.toList());
missing.addAll(missingInteger);
//passes set to results
results.storeMissingInteger(missing);
}
@Override
public String toString() {
return "MissingIntsVisitor{" +
"results=" + results +
", missing=" + missing +
'}';
}
}
| true |
3d4692869b0e4fc0ea6aa213f67d3be775d07c6c | Java | CrystalshardCA/Ruby | /src/main/java/ca/crystalshard/adapter/persistance/StorageQuery.java | UTF-8 | 349 | 2.09375 | 2 | [
"MIT"
] | permissive | package ca.crystalshard.adapter.persistance;
import java.util.List;
public interface StorageQuery {
StorageQuery addParameter(String name, Object value);
int executeUpdate();
<T> T executeAndFetchFirst(Class<T> returnType);
<T> List<T> executeAndFetch(Class<T> returnType);
<T> T executeUpdateWithKey(Class<T> keyClass);
}
| true |
a410650c5fccffb7cf91c8c7105a92be65724d64 | Java | lsj113602/Studyweb_ssm | /src/com/lsj/studyweb/model/Resources.java | UTF-8 | 2,495 | 1.859375 | 2 | [] | no_license | package com.lsj.studyweb.model;
import java.util.Date;
public class Resources {
private String refrenceid;
private String restitle;
private String restext;
private String rescategory;
private String reskonwge;
private String rescourse;
private String filesrc;
private String fileimgsrc;
private String uploadauthor;
private Date uploadtime;
private Integer downnum;
public String getRefrenceid() {
return refrenceid;
}
public void setRefrenceid(String refrenceid) {
this.refrenceid = refrenceid == null ? null : refrenceid.trim();
}
public String getRestitle() {
return restitle;
}
public void setRestitle(String restitle) {
this.restitle = restitle == null ? null : restitle.trim();
}
public String getRestext() {
return restext;
}
public void setRestext(String restext) {
this.restext = restext == null ? null : restext.trim();
}
public String getRescategory() {
return rescategory;
}
public void setRescategory(String rescategory) {
this.rescategory = rescategory == null ? null : rescategory.trim();
}
public String getReskonwge() {
return reskonwge;
}
public void setReskonwge(String reskonwge) {
this.reskonwge = reskonwge == null ? null : reskonwge.trim();
}
public String getRescourse() {
return rescourse;
}
public void setRescourse(String rescourse) {
this.rescourse = rescourse == null ? null : rescourse.trim();
}
public String getFilesrc() {
return filesrc;
}
public void setFilesrc(String filesrc) {
this.filesrc = filesrc == null ? null : filesrc.trim();
}
public String getFileimgsrc() {
return fileimgsrc;
}
public void setFileimgsrc(String fileimgsrc) {
this.fileimgsrc = fileimgsrc == null ? null : fileimgsrc.trim();
}
public String getUploadauthor() {
return uploadauthor;
}
public void setUploadauthor(String uploadauthor) {
this.uploadauthor = uploadauthor == null ? null : uploadauthor.trim();
}
public Date getUploadtime() {
return uploadtime;
}
public void setUploadtime(Date uploadtime) {
this.uploadtime = uploadtime;
}
public Integer getDownnum() {
return downnum;
}
public void setDownnum(Integer downnum) {
this.downnum = downnum;
}
} | true |
2dcf45ab8214002847ec6f83b7950aaaf82b6870 | Java | itiskawa/projet-rigel | /src/ch/epfl/rigel/astronomy/MoonModel.java | UTF-8 | 4,732 | 2.75 | 3 | [] | no_license | package ch.epfl.rigel.astronomy;
import ch.epfl.rigel.coordinates.EclipticCoordinates;
import ch.epfl.rigel.coordinates.EclipticToEquatorialConversion;
import ch.epfl.rigel.coordinates.EquatorialCoordinates;
import ch.epfl.rigel.math.Angle;
/**
* Moon model
* @author Victor Borruat (300666)
* @author Raphaël Selz (302980)
*/
public enum MoonModel implements CelestialObjectModel<Moon> {
/**
* single element of the enumeration
*/
MOON;
/**
* declaration & initialisation of constants used in at method in order:
* average longitude (lo)
* average longitude at perigee (p0)
* longitude at ascending node (No)
* orbital inclination (i)
* orbit eccentricity (e)
*/
private final double l0 = Angle.ofDeg(91.929336);
private final double p0 = Angle.ofDeg(130.143076);
private final double n0 = Angle.ofDeg(291.682547);
private final double i = Angle.ofDeg(5.145396);
private final double e = 0.0549;
/**
* calculator method for a model of the Moon, at a given time
*
* @param daysSinceJ2010 - days since J2010 (days)
* @param eclToEq - ecliptic to equatorial coordinate conversion (conversion of given time)
* @return corresponding Moon (in time & space)
*/
@Override
public Moon at(double daysSinceJ2010, EclipticToEquatorialConversion eclToEq) {
/*
* declaration & initialisation of variables (in order)
* Sun respective to given parameters (s)
* Sun's mean anomaly (sunMeanAnomaly)
* Sun's ecliptic longitude (sunEclLon)
*/
Sun s = SunModel.SUN.at(daysSinceJ2010, eclToEq);
double sunMeanAnomaly = s.meanAnomaly();
double sunEclLon = s.eclipticPos().lon();
/*
* declaration & initialisation of variables to compute orbital longitude (in order):
*
* average orbital longitude (l)
* mean anomaly (meanAnomaly)
* eviction (ev)
* correction of annual equation (ae)
* correction 3 (a3)
* corrected mean anomaly (corrMeanAnom)
* center equation correction (ec)
* correction 4 (a4)
* corrected orbital longitude (corrL)
* variation (v)
* true orbital longitude (trueL)
*/
double l = Angle.ofDeg(13.1763966) * daysSinceJ2010 + l0;
double meanAnomaly = l - Angle.ofDeg(0.1114041) * daysSinceJ2010 - p0;
double ev = Angle.ofDeg(1.2739) * Math.sin(2 * (l - sunEclLon) - meanAnomaly);
double ae = Angle.ofDeg(0.1858) * Math.sin(sunMeanAnomaly);
double a3 = Angle.ofDeg(0.37) * Math.sin(sunMeanAnomaly);
double corrMeanANom = meanAnomaly + ev - ae - a3;
double ec = Angle.ofDeg(6.2886) * Math.sin(corrMeanANom);
double a4 = Angle.ofDeg(0.214) * Math.sin(2 * corrMeanANom);
double corrL = l + ev + ec - ae + a4;
double v = Angle.ofDeg(0.6583) * Math.sin(2 * (corrL - sunEclLon));
double trueL = corrL + v;
/*
* declaration & initialisation of variables to calculate geocentric ecliptic coordinates (in order)
*
* ascending node longitude (n)
* corrected ascending node longitude (corrN)
* ecliptic longitude of Moon (eclLon)
* ecliptic latitude of Moon (eclLat)
*
*/
double n = n0 - Angle.ofDeg(0.0529539) * daysSinceJ2010;
double corrN = n - Angle.ofDeg(0.16) * Math.sin(sunMeanAnomaly);
double eclLon = Math.atan2(Math.sin(trueL - corrN) * Math.cos(i), Math.cos(trueL - corrN)) + corrN;
double eclLat = Math.asin(Math.sin(trueL - corrN) * Math.sin(i));
/*
* declaration & initialisation of phase variable (phaseF)
*/
double phaseF = (1 - Math.cos(trueL - sunEclLon)) / 2.0;
/*
* declaration & initialisation of variables to compute angular size (in order)
* distance Earth-Moon (rho)
* angular size of Moon (angularSizeFromEarth)
*/
double rho = (1 - e * e) / (1 + e * Math.cos(corrMeanANom+ ec));
double angularSizeFromEarth = Angle.ofDeg(0.5181) / rho;
/*
* declaration & initialisation of variables to calculate the coordinate conversion (in order)
* ecliptic coordinates from calculated lon & lat (ecl)
* relative equatorial coordinates (eq) - obtained through conversion using eclToEq parameter
*/
eclLon = Angle.normalizePositive(eclLon);
EclipticCoordinates ecl = EclipticCoordinates.of(eclLon, eclLat);
EquatorialCoordinates eq = eclToEq.apply(ecl);
return new Moon(eq, (float)angularSizeFromEarth, 0, (float)phaseF);
}
}
| true |
be49070f206fb4dee1ef1b30f04906e8e87b4311 | Java | In-Street/webflux | /webflux-websocket/src/main/java/cyf/demo/websocket/handler/HelloWebSocketHandler.java | UTF-8 | 801 | 2.328125 | 2 | [] | no_license | package cyf.demo.websocket.handler;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;
import java.util.function.Function;
/**
* @author Cheng Yufei
* @create 2018-05-12 上午10:14
**/
@Component
public class HelloWebSocketHandler implements WebSocketHandler {
@Override
public Mono<Void> handle(WebSocketSession session) {
Function<WebSocketMessage, WebSocketMessage> function = msg -> {
return session.textMessage("服务端:" + msg.getPayloadAsText());
};
return session.send(session.receive().map(function));
}
}
| true |
4276fbd384500aea861ae5324ed5241a02de28e3 | Java | ljh-dobest/association-android | /app/src/main/java/com/ike/communityalliance/bean/JoinUsers.java | UTF-8 | 658 | 2.03125 | 2 | [] | no_license | package com.ike.communityalliance.bean;
/**
* Created by Min on 2017/3/17.
*/
public class JoinUsers {
private String userId;
private String userPortraitUrl;
public JoinUsers(String userId, String userPortraitUrl) {
this.userId = userId;
this.userPortraitUrl = userPortraitUrl;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserPortraitUrl() {
return userPortraitUrl;
}
public void setUserPortraitUrl(String userPortraitUrl) {
this.userPortraitUrl = userPortraitUrl;
}
}
| true |
9c1c35d347f85c5571a2acc52e6deb70cbf75f94 | Java | SpacePingu/Javapop | /src/interfaz/Admin.java | UTF-8 | 26,949 | 2.21875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package interfaz;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import logica.FacturasMetodos;
import logica.Tienda;
import static logica.Tienda.tienda;
import logica.Usuarios;
import static logica.Usuarios.clientes;
/**
*
* @author adryh
*/
public class Admin extends javax.swing.JFrame {
/**
* Creates new form Admin
*/
public Admin() {
initComponents();
this.setLocationRelativeTo(null);
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
ImageIcon img = new ImageIcon(s + "\\src\\logos\\logo32.png");
this.setIconImage(img.getImage());
System.out.println(clientes);
rellenarUsuarios();
rellenarTienda();
rellenarControlFacturas();
}
public void rellenarUsuarios() {
DefaultTableModel model = (DefaultTableModel) jTableUsers.getModel();
Object rowData[] = new Object[12];
for (int i = 0; i < clientes.size(); i++) {
rowData[0] = clientes.get(i).getDni();
rowData[1] = clientes.get(i).getNombre();
rowData[2] = clientes.get(i).getCorreo();
rowData[3] = clientes.get(i).getClave();
rowData[4] = clientes.get(i).getCiudad();
rowData[5] = clientes.get(i).getCodigo_postal();
rowData[6] = clientes.get(i).getTarjeta_credito();
rowData[7] = clientes.get(i).isPremium();
rowData[8] = clientes.get(i).getDescripcion();
rowData[9] = clientes.get(i).getHorario();
rowData[10] = clientes.get(i).getTelefono();
rowData[11] = clientes.get(i).getWeb();
model.addRow(rowData);
}
}
public void rellenarTienda() {
DefaultTableModel model = (DefaultTableModel) jTableProductos.getModel();
Object rowData[] = new Object[10];
for (int i = 0; i < tienda.size(); i++) {
rowData[0] = tienda.get(i).getId();
rowData[1] = tienda.get(i).getVendedor().getNombre();
rowData[2] = tienda.get(i).getTitulo();
rowData[3] = tienda.get(i).getPrecio();
rowData[4] = tienda.get(i).getDescripcion();
rowData[5] = tienda.get(i).getCategoria();
rowData[6] = tienda.get(i).getCondicion();
switch (tienda.get(i).getEstado()) {
case 0:
rowData[7] = "En venta";
break;
case 1:
rowData[7] = "Reservado";
break;
case 2:
rowData[7] = "En proceso de compra";
break;
default:
rowData[7] = "Vendido";
continue;
}
rowData[8] = tienda.get(i).getUbicacionCiudad() + ", " + tienda.get(i).getUbicacionCP();
rowData[9] = tienda.get(i).getFecha();
model.addRow(rowData);
}
}
public void rellenarControlFacturas() {
DefaultTableModel model = (DefaultTableModel) jTableFacturas.getModel();
Object rowData[] = new Object[5];
for (int i = 0; i < FacturasMetodos.facturas.size(); i++) {
rowData[0] = FacturasMetodos.facturas.get(i).getFechaVenta();
rowData[1] = FacturasMetodos.facturas.get(i).getTitulo();
rowData[2] = FacturasMetodos.facturas.get(i).getVendedor().getCorreo();
rowData[3] = FacturasMetodos.facturas.get(i).getComprador().getCorreo();
rowData[4] = FacturasMetodos.facturas.get(i).getPrecio();
model.addRow(rowData);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTableUsers = new javax.swing.JTable();
jButtonBANHAMMER = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTableProductos = new javax.swing.JTable();
jButtonEliminarProd = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
jTableFacturas = new javax.swing.JTable();
jPanel4 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
jTextFacturaEscrita = new javax.swing.JTextArea();
jButtonDescargarFactura = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jButtonAtras = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("JAVAPOP - ADMIN");
setLocation(new java.awt.Point(500, 200));
setResizable(false);
jTableUsers.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"DNI", "Nombre", "Email", "Contraseña", "Ciudad", "CP", "Nº Tarjeta", "PREMIUM", "Descripción", "Horario", "Teléfono", "Web"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTableUsers.setToolTipText("");
jTableUsers.setShowGrid(false);
jTableUsers.setShowHorizontalLines(true);
jTableUsers.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(jTableUsers);
jTableUsers.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jButtonBANHAMMER.setText("BAN HAMMER");
jButtonBANHAMMER.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonBANHAMMERActionPerformed(evt);
}
});
jButton1.setText("Ver productos del Usuario");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 1171, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonBANHAMMER, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(27, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(151, 151, 151)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 434, Short.MAX_VALUE)
.addComponent(jButtonBANHAMMER, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(16, 16, 16))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2)
.addContainerGap())
);
jTabbedPane1.addTab("CONTROL DE USUARIOS", jPanel1);
jTableProductos.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Vendedor", "Título", "Precio ( € )", "Descripción", "Categoría", "Condicion", "Estado", "Ubicación ", "Fecha"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTableProductos.setDragEnabled(true);
jTableProductos.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(jTableProductos);
if (jTableProductos.getColumnModel().getColumnCount() > 0) {
jTableProductos.getColumnModel().getColumn(3).setResizable(false);
jTableProductos.getColumnModel().getColumn(5).setResizable(false);
jTableProductos.getColumnModel().getColumn(6).setResizable(false);
jTableProductos.getColumnModel().getColumn(7).setResizable(false);
jTableProductos.getColumnModel().getColumn(7).setPreferredWidth(10);
jTableProductos.getColumnModel().getColumn(8).setResizable(false);
jTableProductos.getColumnModel().getColumn(9).setResizable(false);
}
jButtonEliminarProd.setText("Eliminar Producto");
jButtonEliminarProd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonEliminarProdActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButtonEliminarProd, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(0, 633, Short.MAX_VALUE)
.addComponent(jButtonEliminarProd, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jTabbedPane1.addTab("CONTROL DE PRODUCTOS", jPanel3);
jTableFacturas.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Fecha de venta", "Titulo de producto", "Vendedor", "Comprador", "Precio de venta"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTableFacturas.getTableHeader().setReorderingAllowed(false);
jTableFacturas.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jTableFacturasMouseReleased(evt);
}
});
jScrollPane4.setViewportView(jTableFacturas);
if (jTableFacturas.getColumnModel().getColumnCount() > 0) {
jTableFacturas.getColumnModel().getColumn(0).setResizable(false);
jTableFacturas.getColumnModel().getColumn(1).setResizable(false);
jTableFacturas.getColumnModel().getColumn(2).setResizable(false);
jTableFacturas.getColumnModel().getColumn(3).setResizable(false);
jTableFacturas.getColumnModel().getColumn(4).setResizable(false);
}
jPanel4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jTextFacturaEscrita.setEditable(false);
jTextFacturaEscrita.setColumns(20);
jTextFacturaEscrita.setRows(5);
jScrollPane3.setViewportView(jTextFacturaEscrita);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
.addContainerGap())
);
jButtonDescargarFactura.setText("Descargar factura");
jButtonDescargarFactura.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonDescargarFactura.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDescargarFacturaActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 668, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(236, 236, 236)
.addComponent(jButtonDescargarFactura, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(20, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButtonDescargarFactura))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 642, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(31, Short.MAX_VALUE))
);
jTabbedPane1.addTab("CONTROL FACTURAS", jPanel2);
jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 36)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("PANEL DE ADMINISTRADOR");
jButtonAtras.setText("Cerrar sesión de Admin");
jButtonAtras.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAtrasActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(312, 312, 312)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1388, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(81, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane1)
.addGap(39, 39, 39)
.addComponent(jButtonAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//borra un usuario directamente junto con todos los productos asociados
private void jButtonBANHAMMERActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBANHAMMERActionPerformed
String eliminar = (String) jTableUsers.getValueAt(jTableUsers.getSelectedRow(), 2);
int eliminado = JOptionPane.showConfirmDialog(this, "¿Estás seguro que deseas eliminar este usuario?"
+ "\n¡¡ Esto eliminará tambien todos los productos asociados a este perfil !!"
+ "\n¿Seguro que quieres hacerlo?",
"AVISO", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
System.out.print(eliminar);
if (eliminado == JOptionPane.YES_OPTION) {
if (eliminar != null) {
for (int i = 0; i < Tienda.tienda.size(); i++) {
if (Tienda.tienda.get(i).getVendedor().getCorreo().equals(eliminar)) {
Tienda.tienda.remove(i);
}
}
Usuarios.hashClientes.remove(eliminar);
Usuarios.volcarHashMapClientes();
Usuarios.guardarClientes();
Tienda.guardarTienda();
Admin a = new Admin();
a.setVisible(true);
this.dispose();
JOptionPane.showMessageDialog(null, "Usuario " + eliminar + " eliminado, "
+ "\ntodos sus artículos también se han dado de baja");
} else {
JOptionPane.showMessageDialog(null, "Ningún usuario seleccionado");
}
}
}//GEN-LAST:event_jButtonBANHAMMERActionPerformed
private void jButtonAtrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAtrasActionPerformed
Log l = null;
try {
l = new Log();
} catch (IOException ex) {
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
}
l.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButtonAtrasActionPerformed
//Elimina el producto y su imagen asociada
private void jButtonEliminarProdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarProdActionPerformed
int eliminar = jTableProductos.getSelectedRow();
if (eliminar != -1) {
int a = JOptionPane.showConfirmDialog(this, "Esto eliminará para siempre la publicación."
+ "\n¿Seguro que deseas continuar?",
"AVISO", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
String id = (String) jTableProductos.getValueAt(eliminar, 0);
File f = new File(".\\src\\IconosProductos\\" + id + ".jpg");
if (a == JOptionPane.YES_OPTION) {
try {
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
//recarga el ArrayList tienda después de eliminar el deseado.
Tienda.tienda.remove(eliminar);
Tienda.guardarTienda();
Admin b = new Admin();
b.setVisible(true);
this.dispose();
JOptionPane.showMessageDialog(null, "Artículo Eliminado");
}
} else {
JOptionPane.showMessageDialog(null, "Ningún artículo seleccionado");
}
}//GEN-LAST:event_jButtonEliminarProdActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
}//GEN-LAST:event_jButton1ActionPerformed
// Se mostrará por pantalla toda la información de la factura en directo.
private void jTableFacturasMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableFacturasMouseReleased
int i = jTableFacturas.getSelectedRow();
if (i != -1) {
jTextFacturaEscrita.setText(FacturasMetodos.facturas.get(i).toString());
}
}//GEN-LAST:event_jTableFacturasMouseReleased
private void jButtonDescargarFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDescargarFacturaActionPerformed
int selected = jTableFacturas.getSelectedRow();
FacturasMetodos.facturaseleccionada = FacturasMetodos.facturas.get(selected);
if (selected != -1) {
FacturasMetodos.generarFicheroFactura(FacturasMetodos.facturaseleccionada);
} else {
JOptionPane.showMessageDialog(rootPane, "No has seleccionado ningún artículo");
}
}//GEN-LAST:event_jButtonDescargarFacturaActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButtonAtras;
private javax.swing.JButton jButtonBANHAMMER;
private javax.swing.JButton jButtonDescargarFactura;
private javax.swing.JButton jButtonEliminarProd;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTable jTableFacturas;
private javax.swing.JTable jTableProductos;
private javax.swing.JTable jTableUsers;
private javax.swing.JTextArea jTextFacturaEscrita;
// End of variables declaration//GEN-END:variables
}
| true |
7af799de1050e5d9b1df03c2853c734364c59da8 | Java | areyouok/jetcache | /jetcache-test/src/test/java/com/alicp/jetcache/anno/method/ClassUtilTest.java | UTF-8 | 3,664 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | /**
* Created on 13-09-09 15:46
*/
package com.alicp.jetcache.anno.method;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* @author <a href="mailto:areyouok@gmail.com">huangli</a>
*/
public class ClassUtilTest {
private static final String[] hidePack = new String[]{"com.alicp.jetcache.anno"};
interface I1 extends Serializable {
}
interface I2 {
}
interface I3 extends I1, I2 {
}
class C1 {
public void foo() {
}
public String foo(I1 p) {
return null;
}
public String foo2(I1 p) {
return null;
}
public void foo3(byte p2, short p3, char p4, int p5, long p6, float p7, double p8, boolean p9) {
}
}
@Test
public void testGetAllInterfaces() throws Exception {
class CI1 implements I3 {
}
class CI2 extends CI1 implements Cloneable, I1 {
}
Object obj = new CI2();
Class<?>[] is = ClassUtil.getAllInterfaces(obj);
assertEquals(3, is.length);
}
@Test
public void testGenerateCacheName() throws Exception {
Method m1 = C1.class.getMethod("foo");
Method m2 = C1.class.getMethod("foo", I1.class);
Method m3 = C1.class.getMethod("foo2", I1.class);
Method m4 = C1.class.getMethod("foo3", byte.class, short.class, char.class, int.class, long.class, float.class, double.class, boolean.class);
String s1 = "m.ClassUtilTest$C1." + m1.getName() + "()";
String s2 = ClassUtil.generateCacheName(m1, hidePack);
assertEquals(s1, s2);
s1 = "m.ClassUtilTest$C1." + m2.getName() + "(Lm.ClassUtilTest$I1;)";
s2 = ClassUtil.generateCacheName(m2, hidePack);
assertEquals(s1, s2);
s1 = "c.a.j.a.m.ClassUtilTest$C1." + m3.getName() + "(Lc.a.j.a.m.ClassUtilTest$I1;)";
s2 = ClassUtil.generateCacheName(m3, null);
assertEquals(s1, s2);
s1 = "m.ClassUtilTest$C1." + m4.getName() + "(BSCIJFDZ)";
s2 = ClassUtil.generateCacheName(m4, hidePack);
assertEquals(s1, s2);
}
@Test
public void removeHiddenPackageTest() {
String[] hs = {"com.foo", "com.bar."};
assertEquals("Foo", ClassUtil.removeHiddenPackage(hs, "com.foo.Foo"));
assertEquals("foo.Bar", ClassUtil.removeHiddenPackage(hs, "com.bar.foo.Bar"));
assertEquals("", ClassUtil.removeHiddenPackage(hs, "com.foo"));
assertEquals("com.bar.foo.Bar", ClassUtil.removeHiddenPackage(null, "com.bar.foo.Bar"));
assertEquals(null, ClassUtil.removeHiddenPackage(hs, null));
}
@Test
public void getShortClassNameTest() {
assertNull(ClassUtil.getShortClassName(null));
assertEquals("j.l.String", ClassUtil.getShortClassName("java.lang.String"));
assertEquals("String", ClassUtil.getShortClassName("String"));
}
@Test
public void testGetMethodSig() throws Exception {
Method m1 = C1.class.getMethod("foo");
Method m2 = C1.class.getMethod("foo", I1.class);
Method m3 = C1.class.getMethod("foo2", I1.class);
String s1 = m1.getName() + "()V";
String s2 = ClassUtil.getMethodSig(m1);
assertEquals(s1, s2);
s1 = m2.getName() + "(L" + I1.class.getName().replace('.', '/') + ";)Ljava/lang/String;";
s2 = ClassUtil.getMethodSig(m2);
assertEquals(s1, s2);
s1 = m3.getName() + "(L" + I1.class.getName().replace('.', '/') + ";)Ljava/lang/String;";
s2 = ClassUtil.getMethodSig(m3);
assertEquals(s1, s2);
}
}
| true |
2814fab7234a286e8259f827b483a919165a1583 | Java | rawnaq94/Locations---Ex4 | /locations/src/utils/CsvService.java | UTF-8 | 3,289 | 2.703125 | 3 | [] | no_license | package utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import models.ScanInfo;
import models.WifiNetwork;
/*
* handles all csv related operations
*/
public class CsvService {
private static final String csvDelim = ",";
public static String toString(Map<ScanInfo, List<WifiNetwork>> scans) {
String csv = "Time,ID,Lat,Lon,Alt,#WiFi networks (up to 10),";
for (int i = 1; i <= 10; i++) {
csv += String.format("SSID%d,MAC%d,Frequncy%d,Signal%d", i, i, i, i);
if (i < 10)
csv += ",";
}
csv += "\n";
for (Entry<ScanInfo, List<WifiNetwork>> entry : scans.entrySet()) {
ScanInfo info = entry.getKey();
List<WifiNetwork> networks = entry.getValue();
List<WifiNetwork> networksSortedAndLimited = networks.stream()
.sorted((x, y) -> (-1) * Double.compare(x.signal, y.signal)).limit(10).collect(Collectors.toList());
csv += String.format("%s,%s,%s,%s,%s,%d,", info.time, info.id, info.latitude, info.longitude, info.altitude,
networksSortedAndLimited.size());
for (int i = 0; i < networksSortedAndLimited.size(); i++) {
WifiNetwork network = networksSortedAndLimited.get(i);
csv += String.format("%s,%s,%s,%s", network.ssid, network.mac, network.frequency, network.signal);
if (i < networksSortedAndLimited.size() - 1)
csv += ",";
}
csv += "\n";
}
return csv;
}
public static Map<ScanInfo, List<WifiNetwork>> read(Path csvFilePath) {
Map<ScanInfo, List<WifiNetwork>> scans = new HashMap<ScanInfo, List<WifiNetwork>>();
try {
List<String> lines = Files.readAllLines(csvFilePath);
String first = lines.get(0);
if (!first.contains("WigleWifi") || !first.contains("model=")) {
System.err
.println("Bad format of file '" + csvFilePath.getFileName() + "'. expecting WigleWifi format.");
return scans;
}
String id = first.split(csvDelim)[2].replace("model=", "");
for (int i = 2; i < lines.size(); i++) {
String[] parts = lines.get(i).split(csvDelim);
if (parts.length <= 10 || !parts[10].equals("WIFI"))
continue;
WifiNetwork network = new WifiNetwork(parts[1], parts[0], parts[4], Double.parseDouble(parts[5]));
SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = parser.parse(parts[3]);
ScanInfo scanInfo = new ScanInfo(date, id, Double.parseDouble(parts[6]), Double.parseDouble(parts[7]),
Double.parseDouble(parts[8]));
if (scans.containsKey(scanInfo)) {
scans.get(scanInfo).add(network);
} else {
List<WifiNetwork> networks = new LinkedList<WifiNetwork>();
networks.add(network);
scans.put(scanInfo, networks);
}
}
} catch (FileNotFoundException e) {
System.err.println("File not found at " + csvFilePath);
} catch (IOException e) {
System.err.println(e.toString());
System.err.println(csvFilePath);
} catch (ParseException e) {
System.err.println(e.toString());
System.err.println(csvFilePath);
}
return scans;
}
}
| true |
4d206975bb178c5d2f88f9474f125334364e7281 | Java | kamentr/API_Restaurant | /src/main/java/net/kodar/restaurantapi/business/processor/productstatus/ProductStatusProcessorImpl.java | UTF-8 | 1,209 | 1.898438 | 2 | [
"MIT"
] | permissive | package net.kodar.restaurantapi.business.processor.productstatus;
import org.springframework.stereotype.Service;
import net.kodar.restaurantapi.business.processor.ProcessorGenericImpl;
import net.kodar.restaurantapi.business.transformer.param.productstatus.ProductStatusParamTransformer;
import net.kodar.restaurantapi.business.transformer.result.productstatus.ProductStatusResultTransformer;
import net.kodar.restaurantapi.business.validator.productstatus.ProductStatusValidatorImpl;
import net.kodar.restaurantapi.data.entities.ProductStatus;
import net.kodar.restaurantapi.dataaccess.dao.productstatus.ProductStatusDaoImpl;
import net.kodar.restaurantapi.presentation.param.ProductStatusParam;
import net.kodar.restaurantapi.presentation.result.ProductStatusResult;
@Service
public class ProductStatusProcessorImpl extends ProcessorGenericImpl<ProductStatusParam, ProductStatusResult, Long, ProductStatus, ProductStatusDaoImpl, ProductStatusParamTransformer, ProductStatusResultTransformer, ProductStatusValidatorImpl> implements ProductStatusProcessor{
@Override
public Long getID(ProductStatusParam param) {
// TODO Auto-generated method stub
return param.getId();
}
}
| true |
6975c84a72939435a8f4faf51f63c2f60368f873 | Java | jimforcode/mq | /src/main/java/com/zeus/service/impl/HostsServiceImpl.java | UTF-8 | 820 | 2.046875 | 2 | [] | no_license | package com.zeus.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zeus.dao.HostsMapper;
import com.zeus.dto.Pagination;
import com.zeus.model.Hosts;
import com.zeus.service.HostsService;
@Service
public class HostsServiceImpl implements HostsService {
@Autowired
HostsMapper hostsMapper;
@Override
public List<Hosts> listHosts(Pagination page) {
Map<String, Object> map = new HashMap<String, Object>();
if (page != null && page.getFirstResult() != null && page.getRows() != null) {
map.put("firstResult", page.getFirstResult());
map.put("rows", page.getRows());
}
return hostsMapper.getHostsList(map);
}
}
| true |
78c850b58eba1a19c4a880db70ad24e18fb42741 | Java | matrix1412/UTS-GUI | /form_login/src/form_login/Form_loginController.java | UTF-8 | 898 | 2.390625 | 2 | [] | no_license | package form_login;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.showConfirmDialog;
public class Form_loginController {
@FXML
private TextField tf_user;
@FXML
private PasswordField tf_password;
@FXML
void onExitClick(ActionEvent event) {
int ok=JOptionPane.showConfirmDialog(null, "Yakin Mau Keluar?","Konfirmasi",JOptionPane.YES_NO_OPTION);
if(ok==0){
System.exit(0);
}
}
@FXML
void onSubmitClick(ActionEvent event) {
System.out.println("Username = " + tf_user.getText());
System.out.println("Password = " + tf_password.getText());
int login = showConfirmDialog(null, "Selamat Datang","Welcome",JOptionPane.CLOSED_OPTION);
}
} | true |
3bb6ece01e48cee9069c3a014c3d4ce649afe535 | Java | UlkuIslamoglu/SeleniumFrameworkB14 | /src/test/java/Denemeler/Friday1.java | UTF-8 | 903 | 1.921875 | 2 | [] | no_license | package Denemeler;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.security.Key;
import java.util.concurrent.TimeUnit;
public class Friday1 {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://rahulshettyacademy.com/AutomationPractice/");
driver.findElement(By.id("alertbtn")).click();
driver.switchTo().alert().accept();
WebElement box=driver.findElement(By.id("id=name"));
box.sendKeys("Ulku");
driver.findElement(By.id("confirmbtn")).click();
driver.switchTo().alert().dismiss();
driver.quit();
}
}
| true |
e12186935d318ab3eebe48866b4be67ee2811ce6 | Java | SoftwareEngineering-teamH/MD_Converter | /MD2HTML/test/MD2HTML/TextBlockTest.java | UTF-8 | 495 | 2.4375 | 2 | [] | no_license | package MD2HTML;
import static org.junit.Assert.*;
import org.junit.Test;
public class TextBlockTest {
@Test
public void testCreateString() {
TextBlock test_TextBlock1 = new TextBlock();
TextBlock test_TextBlock2 = new TextBlock();
test_TextBlock1.md_data="abc";
test_TextBlock1.node_type = 6;
assertEquals(test_TextBlock1.md_data,test_TextBlock2.create("abc").md_data);
assertEquals(test_TextBlock1.node_type,test_TextBlock2.create("abc").node_type);
}
}
| true |
9a87360b86d84b20bd88f81a6f5105b3acafa6d4 | Java | cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning | /ast_results/niparasc_papanikolis-submarine/papanikolis-android/src/com/niparasc/papanikolis/bluetooth/AcceptThread.java | UTF-8 | 2,909 | 1.90625 | 2 | [] | no_license | // isComment
package com.niparasc.papanikolis.bluetooth;
import java.io.IOException;
import java.util.UUID;
import com.badlogic.gdx.Gdx;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public class isClassOrIsInterface extends Thread {
public static final String isVariable = AcceptThread.class.isMethod();
private BluetoothManager isVariable;
private final BluetoothServerSocket isVariable;
public isConstructor(BluetoothManager isParameter) {
this.isFieldAccessExpr = isNameExpr;
// isComment
// isComment
BluetoothServerSocket isVariable = null;
try {
isNameExpr = this.isFieldAccessExpr.isMethod().isMethod(isNameExpr.isFieldAccessExpr, isNameExpr.isMethod(isNameExpr.isFieldAccessExpr));
} catch (IOException isParameter) {
isNameExpr.isFieldAccessExpr.isMethod(isNameExpr, "isStringConstant");
}
isNameExpr = isNameExpr;
}
public void isMethod() {
BluetoothSocket isVariable = null;
// isComment
while (true) {
try {
isNameExpr.isFieldAccessExpr.isMethod(isNameExpr, "isStringConstant");
isNameExpr = isNameExpr.isMethod();
} catch (Exception isParameter) {
isNameExpr.isFieldAccessExpr.isMethod(isNameExpr, "isStringConstant");
isNameExpr.isMethod(isNameExpr.isFieldAccessExpr);
break;
}
// isComment
if (isNameExpr != null) {
// isComment
isMethod(isNameExpr);
try {
isNameExpr.isFieldAccessExpr.isMethod(isNameExpr, "isStringConstant");
isNameExpr.isMethod();
} catch (IOException isParameter) {
isNameExpr.isFieldAccessExpr.isMethod(isNameExpr, isNameExpr.isMethod());
}
break;
}
}
}
/**
* isComment
*/
public void isMethod(BluetoothSocket isParameter) {
isNameExpr.isFieldAccessExpr.isMethod(isNameExpr, "isStringConstant");
isNameExpr.isMethod(new ConnectedThread(isNameExpr, isNameExpr));
isNameExpr.isMethod().isMethod();
// isComment
// isComment
// isComment
isNameExpr.isFieldAccessExpr.isMethod(new Runnable() {
@Override
public void isMethod() {
isNameExpr.isMethod(isNameExpr.isFieldAccessExpr);
}
});
}
/**
* isComment
*/
public void isMethod() {
try {
isNameExpr.isFieldAccessExpr.isMethod(isNameExpr, "isStringConstant");
isNameExpr.isMethod();
} catch (IOException isParameter) {
isNameExpr.isFieldAccessExpr.isMethod(isNameExpr, "isStringConstant");
}
}
}
| true |
1aeb10500d8608d397ba25e1c548073d60c296f1 | Java | amira-abdelhafiez/MusicPlayer | /app/src/main/java/com/example/amira/musicplayer/ui/SplashscreenActivity.java | UTF-8 | 1,043 | 2.578125 | 3 | [] | no_license | package com.example.amira.musicplayer.ui;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import com.example.amira.musicplayer.R;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class SplashscreenActivity extends AppCompatActivity {
private static final int SPLASH_DISPLAY_LENGTH = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
launchHomeScreen();
}
} , SPLASH_DISPLAY_LENGTH);
}
private void launchHomeScreen(){
Intent intent = new Intent(SplashscreenActivity.this , HomeActivity.class);
startActivity(intent);
this.finish();
}
}
| true |
6e9e45dd1dac255db925f289b16fdeb2d547ad15 | Java | pnaranjo/tp1ayp2 | /src/clases/CajaDeAhorroEnDolares.java | UTF-8 | 613 | 2.390625 | 2 | [] | no_license | package clases;
import java.util.ArrayList;
import excepciones.ArrayTitularesException;
import excepciones.MontoException;
public class CajaDeAhorroEnDolares extends CajaDeAhorro{
public CajaDeAhorroEnDolares(double monto, ArrayList<PersonaFisica> titulares,double tasaDeInteres) throws MontoException, ArrayTitularesException {
super(monto, titulares, tasaDeInteres);
//costoMantenimiento = Banco.getCostoDeMantenimientoPesos() * Banco.getTipoDeCambioVigente();
costoMantenimiento = Banco.getCostoDeMantenimientoDolares();
setTipoCuenta("CajaDeAhorroEnDolares");
setTipoMoneda("Dolares");
}
}
| true |
fce5cb4bb094817bbcc4241fc7f49eff3734485f | Java | vbarakam/sample1 | /src/com/yahoo/util3/FlattenBinaryTreetoLinkedList.java | UTF-8 | 642 | 3.1875 | 3 | [] | no_license | package com.yahoo.util3;
public class FlattenBinaryTreetoLinkedList {
private TreeNode prev = null;
public static void main(String args[]){
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
root.right = new TreeNode(5);
root.right.right = new TreeNode(6);
FlattenBinaryTreetoLinkedList tree = new FlattenBinaryTreetoLinkedList();
tree.process(root);
}
private void process(TreeNode root) {
if (root == null) {
return;
}
process(root.right);
process(root.left);
root.right = prev;
root.left = null;
prev = root;
}
}
| true |
7265e74085cdd61807bbf436912e1e5014746330 | Java | tanvidadu/RentRobes | /app/src/main/java/com/example/tanvidadu/learnit/TypeWiseListFragment.java | UTF-8 | 3,796 | 2.375 | 2 | [] | no_license | package com.example.tanvidadu.learnit;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OnFragmentInteractionListener} interface
* to handle interaction events.
*/
public class TypeWiseListFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private ArrayList<RobesForRent> robeToBeDisplayed;
private final String List_Items = "List_Items";
public TypeWiseListFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_type_wise_list, container, false);
if( savedInstanceState != null && robeToBeDisplayed == null){
robeToBeDisplayed = savedInstanceState.getParcelableArrayList(List_Items);
}
final ListView listView ;
final RobesAdapter robesAdapter = new RobesAdapter(getActivity(), robeToBeDisplayed);
listView = (ListView) rootView.findViewById(R.id.List_View_items);
if( robeToBeDisplayed != null ) {
listView.setAdapter(robesAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListener.onFragmentInteraction(position);
}
});
}
return rootView;
}
private void runOnUiThread(Runnable runnable) {
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(int position) {
if (mListener != null) {
mListener.onFragmentInteraction(position);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e){
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(int position);
}
public void setRobeToBeDisplayed(ArrayList<RobesForRent> robeToBeDisplayed) {
this.robeToBeDisplayed = robeToBeDisplayed;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList(List_Items , robeToBeDisplayed);
super.onSaveInstanceState(outState);
}
}
| true |
17ec538276767e0a9cd7e05f88cc24f70514b2bd | Java | lqxlqh/basicStudy | /Demo1/src/designMode/_01creatorType/_05prototypePattern/Attachment.java | UTF-8 | 489 | 3.15625 | 3 | [] | no_license | package designMode._01creatorType._05prototypePattern;
/**
* @author lin
* @create 2020-01-02
* @Info(原型模式--浅克隆)
* @Notes--(附件类--区分浅克隆和深克隆)
*/
public class Attachment {
//附件名
private String name;
public void download(){
System.out.println("下载附件,文件名为:"+ name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| true |
a092c42936890f1f69841cea4c9073bf3fce61ff | Java | rahulgidde/ParkingLotProblem | /src/main/java/service/ParkingLotSystem.java | UTF-8 | 2,557 | 3.375 | 3 | [] | no_license | package service;
import exception.DriverType;
import exception.ParkingLotException;
import exception.VehicleType;
import java.util.ArrayList;
public class ParkingLotSystem {
FirstLot firstLot = new FirstLot();
SecondLot secondLot = new SecondLot();
ArrayList list1 = firstLot.getList();
ArrayList list2 = secondLot.getList();
static int flag = 0;
public void park(Vehicle vehicle) {
switch (flag) {
case 0:
firstLot.getSlot(vehicle);
flag++;
break;
case 1:
secondLot.getSlot(vehicle);
flag--;
break;
default:
System.out.println("Invalid Choice");
}
}
public void unPark(Vehicle vehicle) {
if (list1.contains(vehicle))
firstLot.removeSlot(vehicle);
if (list2.contains(vehicle))
secondLot.removeSlot(vehicle);
}
public void getHandicapParking(Vehicle vehicle) {
for (int slot = 1; slot <= list1.size(); slot++) {
if (list2.size() == 0 || list1.get(slot) == null)
firstLot.getSlot(vehicle);
else if (list2.size() == 0 || list2.get(slot) == null)
secondLot.getSlot(vehicle);
}
}
public void largeCarParking(Vehicle vehicle) throws ParkingLotException {
for(int slot=1; slot<=list1.size(); slot++) {
if (list1.size() == 0 || list1.get(slot) == null && list1.get(slot+1) == null)
firstLot.getSlot(vehicle);
else if (list2.size() == 0 || list2.get(slot) == null && list2.get(slot+1) == null)
secondLot.getSlot(vehicle);
else
throw new ParkingLotException(ParkingLotException.ExceptionType.PARKING_FULL,"Parking Full");
}
}
public void getParking(Vehicle vehicle, DriverType driverType,VehicleType vehicleType) throws ParkingLotException {
switch (driverType) {
case NORMAL_DRIVER:
if( VehicleType.SMALL_VEHICLE == vehicleType)
park(vehicle);
else if(VehicleType.LARGE_VEHICLE == vehicleType && list1.size() != 0 || list2.size() != 0)
largeCarParking(vehicle);
else
park(vehicle);
break;
case HANDICAP_DRIVER:
getHandicapParking(vehicle);
break;
default:
System.out.println("Invalid Type");
}
}
}
| true |
3a90ad6e5c49f9d12f12952ed69809011f48bfd8 | Java | mi-erasmusmc/ontobrowser | /emc-master/clinical-pa/src/main/java/org/lhasalimited/etransafe/wp6/clinical/api/model/result/Result.java | UTF-8 | 5,062 | 1.96875 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright © 2019 Lhasa Limited
* File created: 19 Aug 2019 by Tima Camara
* Creator : Tima Camara
* Version : $Id$
*/
package org.lhasalimited.etransafe.wp6.clinical.api.model.result;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.validation.Valid;
import org.lhasalimited.etransafe.wp6.clinical.api.model.DataClassKey;
import org.lhasalimited.etransafe.wp6.clinical.api.model.query.DataType;
import org.lhasalimited.etransafe.wp6.clinical.api.model.query.SearchFilter;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
/**
*
* @author Tima Camara
* @since 19 Aug 2019
*/
public class Result implements Serializable
{
private static final long serialVersionUID = 1L;
@JsonProperty("origin")
private String origin;
@JsonProperty("dataType")
private DataType dataType;
@JsonProperty("dataClassKey")
private DataClassKey dataClassKey;
@JsonProperty("querySearchFilter")
private SearchFilter querySearchFilter = null;
@JsonProperty("fields")
@Valid
private List<DataClassResult> fields = null;
public Result origin(String origin)
{
this.origin = origin;
return this;
}
/**
* Get origin
*
* @return origin
*/
@ApiModelProperty(value = "")
public String getOrigin()
{
return origin;
}
public void setOrigin(String origin)
{
this.origin = origin;
}
public Result dataType(DataType dataType)
{
this.dataType = dataType;
return this;
}
/**
* Get dataType
*
* @return dataType
*/
@ApiModelProperty(value = "")
@Valid
public DataType getDataType()
{
return dataType;
}
public void setDataType(DataType dataType)
{
this.dataType = dataType;
}
public Result dataClassKey(DataClassKey dataClassKey)
{
this.dataClassKey = dataClassKey;
return this;
}
/**
* Get dataClassKey
*
* @return dataClassKey
*/
@ApiModelProperty(value = "")
@Valid
public DataClassKey getDataClassKey()
{
return dataClassKey;
}
public void setDataClassKey(DataClassKey dataClassKey)
{
this.dataClassKey = dataClassKey;
}
public Result querySearchFilter(SearchFilter querySearchFilter)
{
this.querySearchFilter = querySearchFilter;
return this;
}
/**
* Get querySearchFilter
*
* @return querySearchFilter
*/
@ApiModelProperty(value = "")
@Valid
public SearchFilter getQuerySearchFilter()
{
return querySearchFilter;
}
public void setQuerySearchFilter(SearchFilter querySearchFilter)
{
this.querySearchFilter = querySearchFilter;
}
public Result fields(List<DataClassResult> fields)
{
this.fields = fields;
return this;
}
public Result addFieldsItem(DataClassResult fieldsItem)
{
if (this.fields == null)
{
this.fields = new ArrayList<>();
}
this.fields.add(fieldsItem);
return this;
}
/**
* Get fields
*
* @return fields
*/
@ApiModelProperty(value = "")
@Valid
public List<DataClassResult> getFields()
{
return fields;
}
public void setFields(List<DataClassResult> fields)
{
this.fields = fields;
}
@Override
public boolean equals(java.lang.Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Result result = (Result) o;
return Objects.equals(this.origin, result.origin) &&
Objects.equals(this.dataType, result.dataType) &&
Objects.equals(this.dataClassKey, result.dataClassKey) &&
Objects.equals(this.querySearchFilter, result.querySearchFilter) &&
Objects.equals(this.fields, result.fields);
}
@Override
public int hashCode()
{
return Objects.hash(origin, dataType, dataClassKey, querySearchFilter, fields);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class Result {\n");
sb.append(" origin: ").append(toIndentedString(origin)).append("\n");
sb.append(" dataType: ").append(toIndentedString(dataType)).append("\n");
sb.append(" dataClassKey: ").append(toIndentedString(dataClassKey)).append("\n");
sb.append(" querySearchFilter: ").append(toIndentedString(querySearchFilter)).append("\n");
sb.append(" fields: ").append(toIndentedString(fields)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
/* ---------------------------------------------------------------------*
* This software is the confidential and proprietary
* information of Lhasa Limited
* Granary Wharf House, 2 Canal Wharf, Leeds, LS11 5PS
* ---
* No part of this confidential information shall be disclosed
* and it shall be used only in accordance with the terms of a
* written license agreement entered into by holder of the information
* with LHASA Ltd.
* --------------------------------------------------------------------- */ | true |
9900d5689bd32e36113b983e55aa72742cc42fd5 | Java | MooNkirA/spring-note | /spring-sample/55-spring-beanpostprocessor/src/main/java/com/moon/springsample/processor/CustomBeanPostProcessor.java | UTF-8 | 1,558 | 2.890625 | 3 | [] | no_license | package com.moon.springsample.processor;
import com.moon.springsample.bean.Cat;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
/**
* 自定义 BeanPostProcessor 实现
*
* @author MooNkirA
* @version 1.0
* @date 2022-05-16 15:31
* @description
*/
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Cat) {
System.out.println("基于实现 BeanPostProcessor 接口 postProcessBeforeInitialization() 方法," + beanName + "初始化之前调用");
Cat cat = (Cat) bean;
// 模拟功能增强,这里只是设置属性
cat.setName("在 BeanPostProcessor 接口中设置的名称");
cat.setAge(1);
return cat;
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Cat) {
System.out.println("基于实现 BeanPostProcessor 接口 postProcessAfterInitialization() 方法," + beanName + "初始化之后调用");
Cat cat = (Cat) bean;
// 模拟功能增强,这里只是设置属性
cat.setColor("pink");
cat.setAge(cat.getAge() + 1);
return cat;
}
return bean;
}
} | true |
5145144541ef92ada0ae1e52b950370815cef883 | Java | steveleejava0902/studytest | /studyTest1/src/halucinor/PBook2.java | UHC | 4,111 | 2.625 | 3 | [] | no_license | package halucinor;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class PBook2 implements KeyListener {
JFrame mainFrame = new JFrame();
JPanel mainPane = new JPanel();
JTextArea menuDisplay = new JTextArea();
JTextArea printDisplay = new JTextArea();
JTextField inputDisplay = new JTextField();
JScrollPane printScrollPane ;
//MODE 0 31 Է¸ ̸Է 32 Է¸ ȭȣ Է 33 Է¸ ̸ ߺ
int MODE = 0;
String name, phone;
ArrayList<phoneItem> phonelist = new ArrayList<phoneItem>();
public PBook2() {
makeDisplay();
makephonelist();
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
int keyN = arg0.getKeyCode();
System.out.println(keyN);
//menu1
if(keyN == 49 || keyN == 97) {
menu1();
}
//inputʱȭ
inputDisplay.setText("");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PBook2 pb = new PBook2();
}
//---------------------------backend logic-------------------------------------------------------------
public void makeDisplay() {
mainFrame.setTitle("phoneBook");
mainFrame.setSize(600, 400);
mainFrame.setDefaultCloseOperation(3);
mainFrame.setLocationRelativeTo(null);
menuDisplay.setBorder(new TitledBorder("menu"));
menuDisplay.setSize(240, 230);
menuDisplay.setLocation(10, 20);
menuDisplay.setEditable(false);
printDisplay.setSize(240, 230);
printDisplay.setLocation(255, 20);
printDisplay.setEditable(false);
printDisplay.setFocusable(false);
printDisplay.setRequestFocusEnabled(false);
printDisplay.setWrapStyleWord(true);
printDisplay.setLineWrap(true);
printScrollPane = new JScrollPane(printDisplay);
printScrollPane.setBorder(new TitledBorder("display"));
printScrollPane.setSize(240, 230);
printScrollPane.setLocation(255, 20);
inputDisplay.setBorder(new TitledBorder("input"));
inputDisplay.setSize(400, 40);
inputDisplay.setLocation(10, 250);
inputDisplay.addKeyListener(this);
mainPane.setBorder(new TitledBorder("main"));
mainPane.setLayout(null);
mainPane.setLocation(0, 0);
mainPane.add(menuDisplay);
mainPane.add(printScrollPane);
mainPane.add(inputDisplay);
mainFrame.getContentPane().add(mainPane,null);
// mainFrame.getContentPane().add(printScrollPane,null);
// mainFrame.getContentPane().add(inputPane,null);
//mainFrame.pack();
mainFrame.setVisible(true);
inputDisplay.requestFocus();
menuDisplay.setText(Properties.menu_EX1);
}
public void makephonelist() {
try {
DataInputStream ds = new DataInputStream(new FileInputStream(new File(Properties.file_PATH)));
String phoneLine = ds.readLine();
while(phoneLine != null) {
String[] splited = phoneLine.split(",");
phonelist.add(new phoneItem(splited[0],splited[1]));
phoneLine = ds.readLine();
}
} catch (Exception e) {
System.out.println("cannot read file!");
}
}
public void menu1() {
//initialize printDisplay
printDisplay.setText("");
for(phoneItem item:phonelist) {
printDisplay.append(item.toString() + "\n");
}
}
public void menu2_name() {
}
public void menu2_phone() {
}
public void menu2() {
}
public void menu2_force() {
}
public void menu2_no() {
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
| true |
76cae35eecae3567285bdd557dcd1979622c8849 | Java | scotmatson/mine-explorer | /src/engine/Messages.java | UTF-8 | 1,364 | 3.0625 | 3 | [] | no_license | package engine;
// TODO Implement randomizer to present user with various lines of text based upon their actions.
public class Messages {
public static void newGame() {
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@**MINE*EXPLORER**@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@//=========\\\\@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@////#########\\\\\\@@@@@@@@@@@");
System.out.println("@@@@@@@@@@||#############||@@@@@@@@@@");
System.out.println("@@@@@@@@@@||######'######||@@@@@@@@@@");
System.out.println("@@@@@@@@@@||####'''''####||@@@@@@@@@@");
System.out.println("@@@@@@@@@@||##'''''''''##||@@@@@@@@@@");
System.out.println("@@@@@@@@@@||#'''''''''''#||@@@@@@@@@@");
System.out.println("@@@@@@@@@@|_______________|@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("\nNew Game? (Y)es to play, (N)o to quit.");
System.out.print(">> ");
}
public static void noGame() {
System.out.println("Too bad, maybe next time.");
}
public static void unknownEntry() {
System.out.println("Invalid selection, please try again.\n");
}
public static void noExit() {
System.out.println("You can't go that way!");
}
}
| true |
17342f9ed9086896ea13c016ea8b350cfa36add9 | Java | xiatianyu11/hibernate-tutorial | /FirstHibernateProj/src/com/rain/dto/UserRole.java | UTF-8 | 506 | 2.125 | 2 | [] | no_license | package com.rain.dto;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
@Entity
public class UserRole {
@EmbeddedId
private UserRoleId userRoleId;
private String description;
public UserRoleId getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(UserRoleId userRoleId) {
this.userRoleId = userRoleId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| true |
2a1e8c1debb61e5f33368d6f4998105f545d2469 | Java | ixxus/alfresco-bulk-import | /amp/src/main/java/org/alfresco/extension/bulkimport/impl/BulkImportThreadPoolExecutor.java | UTF-8 | 7,482 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2007 Peter Monks
* 2012 Alain Sahli - Fix for issue 109: http://code.google.com/p/alfresco-bulk-filesystem-import/issues/detail?id=109.
*
* 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.
*
* This file is part of an unsupported extension to Alfresco.
*
*/
package org.alfresco.extension.bulkimport.impl;
import java.util.concurrent.*;
import org.alfresco.extension.bulkimport.util.ThreadPauser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.alfresco.extension.bulkimport.util.LogUtils.*;
/**
* This class provides a simplified <code>ThreadPoolExecutor</code>
* that uses sensible defaults for the bulk import tool. Note that calls to
* <code>execute</code> and <code>submit</code> can block.
*
* @author Peter Monks (pmonks@gmail.com)
*/
public class BulkImportThreadPoolExecutor
extends ThreadPoolExecutor
{
private final static Log log = LogFactory.getLog(BulkImportThreadPoolExecutor.class);
private final static int DEFAULT_THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 4;
private final static long DEFAULT_KEEP_ALIVE_TIME = 10L;
private final static TimeUnit DEFAULT_KEEP_ALIVE_TIME_UNIT = TimeUnit.MINUTES;
private final static int DEFAULT_QUEUE_CAPACITY = 100; // Batches
private final int queueCapacity;
private final ThreadPauser pauser;
private final Semaphore queueSemaphore;
public BulkImportThreadPoolExecutor(final ThreadPauser pauser,
final int threadPoolSize,
final int queueCapacity,
final long keepAliveTime,
final TimeUnit keepAliveTimeUnit)
{
super(threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize, // Core pool size
threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize, // Max pool size (same as core pool size)
keepAliveTime <= 0 ? DEFAULT_KEEP_ALIVE_TIME : keepAliveTime, // Keep alive
keepAliveTimeUnit == null ? DEFAULT_KEEP_ALIVE_TIME_UNIT : keepAliveTimeUnit, // Keep alive units
new LinkedBlockingQueue<Runnable>(), // Queue of maximum size
new BulkImportThreadFactory(), // Thread factory
new ThreadPoolExecutor.AbortPolicy()); // Rejection handler (shouldn't ever be called, due to the use of a semaphone before task submission)
this.queueCapacity = queueCapacity;
this.pauser = pauser;
final int queuePlusPoolSize = (queueCapacity <= 0 ? DEFAULT_QUEUE_CAPACITY : queueCapacity) +
(threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize);
this.queueSemaphore = new Semaphore(queuePlusPoolSize);
if (debug(log)) debug(log, "Created new bulk import thread pool." +
" Thread Pool Size=" + (threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize) +
", Queue Capacity=" + ((queueCapacity <= 0 ? DEFAULT_QUEUE_CAPACITY : queueCapacity) + 2) +
", Keep Alive Time=" + (keepAliveTime <= 0 ? DEFAULT_KEEP_ALIVE_TIME : keepAliveTime) +
" " + String.valueOf(keepAliveTimeUnit == null ? DEFAULT_KEEP_ALIVE_TIME_UNIT : keepAliveTimeUnit));
}
/**
* @see {@link ThreadPoolExecutor#beforeExecute(Thread, Runnable)}
*/
@Override
protected void beforeExecute(final Thread thread, final Runnable runnable)
{
super.beforeExecute(thread, runnable);
try
{
pauser.blockIfPaused();
}
catch (final InterruptedException ie) // Curse you checked exceptions!!!!
{
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
}
}
/**
* @see {@link ThreadPoolExecutor#execute(Runnable)}
*/
@Override
public void execute(final Runnable command)
{
try
{
if (debug(log) && queueSemaphore.availablePermits() <= 0) debug(log, "Worker threads are saturated, scanning will block.");
queueSemaphore.acquire();
}
catch (final InterruptedException ie)
{
Thread.currentThread().interrupt();
throw new RuntimeException(ie); // Checked exceptions are the bane of my existence...
}
try
{
if (super.isTerminating() || super.isShutdown() || super.isTerminated())
{
if (debug(log)) debug(log, "New work submitted during shutdown - ignoring new work.");
}
else
{
super.execute(new Runnable()
{
@Override
public void run()
{
try
{
command.run();
}
finally
{
// Note: queueSemaphore must be released by the worker thread, not the scanner thread!
queueSemaphore.release();
}
}
});
}
}
catch (final RejectedExecutionException ree)
{
// If this triggers, it's a bug in the back-pressure logic
queueSemaphore.release();
throw new IllegalStateException("Worker threads were saturated (available permits = " + String.valueOf(queueSemaphore.availablePermits()) + "), " +
"but scanning didn't block, resulting in a RejectedExecutionException. " +
"This is probably a bug in the bulk import tool - please raise an issue at https://github.com/pmonks/alfresco-bulk-import/issues/, including this full stack trace (and all \"caused by\" stack traces).",
ree);
}
}
/**
* @return The current size (number of items) on the queue.
*/
public int getQueueSize()
{
return(getQueue().size());
}
/**
* @return The maximum possible capacity of the queue.
*/
public int getQueueCapacity()
{
return(queueCapacity);
}
/**
* @return Is the work queue for this thread pool empty?
*/
public boolean isQueueEmpty()
{
return(getQueue().isEmpty());
}
}
| true |
f8245f3b51eca7ed5a3c41550a1763ce020392f6 | Java | fanqi1909/csreview | /leet-code/src/main/java/org/jace/cs/review/lc/interval/p1353/MaxNumberOfEventsCanBeAttended.java | UTF-8 | 3,489 | 3.09375 | 3 | [] | no_license | package org.jace.cs.review.lc.interval.p1353;
import org.jace.cs.review.lc.dp.Util;
import java.util.*;
public class MaxNumberOfEventsCanBeAttended {
public int maxEvents(int[][] events) {
Arrays.sort(events, (e1, e2) -> {
if(e1[0] == e2[0]) {
return e1[1] - e2[1];
} else {
return e1[0] - e2[0];
}
});
Util.print2DArray(events);
TreeMap<int[], Integer> orderedEvents = new TreeMap<>((e1, e2)->{
if(e1[0] != e2[0]) {
return e1[0] - e2[0];
} else {
return e1[1] - e2[1];
}
});
int lastDay = 0;
int firstDay = 0;
for(int[] event : events) {
lastDay = Math.max(lastDay, event[1]);
firstDay = Math.min(firstDay, event[0]);
orderedEvents.put(event, orderedEvents.getOrDefault(event, 0) + 1);
}
int maxEvent = 0;
for(int i = firstDay; i <= lastDay && !orderedEvents.isEmpty(); i++) {
int minClosing = lastDay + 1;
int[] selectedEvent = null;
for(int[] event : orderedEvents.keySet()) {
if(event[0] <= i && event[1] >= i) {
if(event[1] <= minClosing) {
minClosing = event[1];
selectedEvent = event;
}
} else if(event[0] >=i) {
break;
}
}
if(selectedEvent != null) {
maxEvent++;
orderedEvents.put(selectedEvent, orderedEvents.get(selectedEvent) - 1);
if(orderedEvents.get(selectedEvent) == 0) {
orderedEvents.remove(selectedEvent);
}
}
}
return maxEvent;
}
public static void main(String[] args) {
MaxNumberOfEventsCanBeAttended sol = new MaxNumberOfEventsCanBeAttended();
System.out.println(sol.maxEvents(new int[][]{
new int[]{1, 5},
new int[]{1, 5},
new int[]{1, 5},
new int[]{2, 3},
new int[]{2, 3},
}));
//
System.out.println(sol.maxEvents(new int[][]{
new int[]{1, 2},
new int[]{1, 2},
new int[]{3, 3},
new int[]{1, 5},
new int[]{1, 5},
}));
// [[1,2],[1,2],[3,3],[1,5],[1,5]]
System.out.println(sol.maxEvents(new int[][]{
new int[]{1, 2},
new int[]{2, 3},
new int[]{3, 4}
}));
System.out.println(sol.maxEvents(new int[][]{
new int[]{1,2},
new int[]{2,3},
new int[]{3,4},
new int[]{1,2},
}));
System.out.println(sol.maxEvents(new int[][]{
new int[]{1,4},
new int[]{4,4},
new int[]{2,2},
new int[]{3,4},
new int[]{1,1},
}));
System.out.println(sol.maxEvents(new int[][]{
new int[]{1,100000}
}));
System.out.println(sol.maxEvents(new int[][]{
new int[]{1,1},
new int[]{1,2},
new int[]{1,3},
new int[]{1,4},
new int[]{1,5},
new int[]{1,6},
new int[]{1,7}
}));
}
} | true |
1e89aea45f73628f8e91b246a1ba9f7383e09147 | Java | slowfarm/HackMoscow | /app/src/main/java/ru/eva/hackmoscow/model/Properties.java | UTF-8 | 980 | 2.078125 | 2 | [] | no_license |
package ru.eva.hackmoscow.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Properties {
@SerializedName("id")
@Expose
private String id;
@SerializedName("date")
@Expose
private String date;
@SerializedName("time")
@Expose
private String time;
@SerializedName("radiusparam")
@Expose
private String radiusparam;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getRadiusparam() {
return radiusparam;
}
public void setRadiusparam(String radiusparam) {
this.radiusparam = radiusparam;
}
}
| true |
dc46986b52a18fcfecba3d83563006ccd56c1f04 | Java | bozo666/projetoEscolaJSF | /src/escola2020/repositorio/EquipamentoRepositorio.java | UTF-8 | 677 | 2.4375 | 2 | [] | no_license | package escola2020.repositorio;
import java.sql.SQLException;
import java.util.ArrayList;
import escola2020.dominio.Equipamentos;
public interface EquipamentoRepositorio {
public void inserir(Equipamentos equipamento) throws SQLException;
public void atualizar(Equipamentos equipamento) throws SQLException;
public void excluir(int codigo) throws SQLException;
public Equipamentos get(int codigo) throws SQLException;
/**
* Retorna um vetor com todos os registros do BD
* @return ArrayList<Usuario> com todos os registros, ou um objeto vazio
* @throws SQLException
*/
public ArrayList<Equipamentos> getAll() throws SQLException;
}
| true |
f01d2e774070e0a8751f7c6cb38537e5c3b7ce2f | Java | zjhwlj/roll_call | /wh-server/src/main/java/com/wanghuan/controller/sys/ClassController.java | UTF-8 | 2,514 | 2.296875 | 2 | [] | no_license | package com.wanghuan.controller.sys;
import com.wanghuan.model.sys.ClassEntity;
import com.wanghuan.model.sys.PageResult;
import com.wanghuan.service.sys.ClassService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
/*@PreAuthorize("hasRole('ADMI')")*/
public class ClassController {
private Logger log = LoggerFactory.getLogger(ClassController.class);
@Resource(name = "ClassServiceImpl")
private ClassService classService;
@GetMapping("/course/{courseName}")
public ClassEntity courseGet(@PathVariable String courseName) {
ClassEntity classEntity = classService.getClassEntityByCourseName(courseName);
log.debug("The method is ending");
return classEntity;
}
@GetMapping("/course/all")
public List<ClassEntity> allClasss(){
return classService.allClasss();
}
/**
* 获取user表数据
*
* @param courseName
* @param pageSize
* @param page
* @return
*/
@GetMapping("/course")
public PageResult coursesList(String courseName, int pageSize, int page) {
PageResult pageResult = new PageResult();
pageResult.setData(classService.classList(courseName, pageSize, page * pageSize));
pageResult.setTotalCount(classService.classSize(courseName, pageSize, page * pageSize));
log.debug("111111111111111");
return pageResult;
}
/**
* 新建用户信息
*
* @param schoolEntity
* @return
*/
@PostMapping("/course/insert")
public ClassEntity insertClass(@RequestBody ClassEntity classEntity) {
classService.insertClass(classEntity);
//log.debug(schoolEntity.getAmAfterclasstime());
return classEntity;
}
/**
*
*
* 更新用户信息
*
* @param schoolEntity
* @param schoolId
* @return
*/
@PutMapping("/course/{id}")
public ClassEntity updateClass(@RequestBody ClassEntity classEntity, @PathVariable int id) {
if (classEntity.getId() == id) {
classService.updateClass(classEntity);
//log.debug(String.valueOf(schoolId));
log.debug("ddddddddddddd");
}
log.debug(String.valueOf(id));
log.debug("ddddddddddddddddddddddd");
return classEntity;
}
/**
* 删除用户信息
*
* @param groupId
* @return
*/
@DeleteMapping("/course/delete")
public List<String> deleteClasss(@RequestBody List<String> groupId) {
classService.deleteClass(groupId);
return groupId;
}
}
| true |
d152695490ebdd51d21c921df3189d4744bbf5c8 | Java | miniro/leetcode-killer | /src/T560.java | UTF-8 | 885 | 3.125 | 3 | [] | no_license | import java.util.Arrays;
public class T560 {
class Solution {
public int subarraySum(int[] nums, int k) {
int ans = 0;
int[] arr = new int[nums.length + 1];
for(int i = 0; i < nums.length; i ++) {
arr[i + 1] = arr[i] + nums[i];
}
for(int i = 1; i < arr.length; i ++) {
int left = 0;
int right = i - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(arr[i] - arr[mid] == k) {
ans ++;
break;
} else if(arr[i] - arr[mid] > k) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return ans;
}
}
}
| true |
505613fa27d1875a9941862f5a7394648b1a91d4 | Java | miskmyu/smartworksV3 | /src/pro/ucity/sso/manager/ISsoManager.java | UTF-8 | 614 | 1.59375 | 2 | [] | no_license | /*
* $Id$
* created by : yukm
* creation-date : 2012. 10. 22.
* =========================================================
* Copyright (c) 2012 ManinSoft, Inc. All rights reserved.
*/
package pro.ucity.sso.manager;
import java.util.ArrayList;
import ifez.framework.session.UserProgramAuthInfoVO;
import ifez.framework.session.service.UserSessionVO;
public interface ISsoManager {
public UserSessionVO selectUser(UserSessionVO userSessionVO) throws Exception;
public ArrayList<UserProgramAuthInfoVO> retriveUserProgramAuthInfo(UserSessionVO userSessionVO) throws Exception;
}
| true |
8000db888c375d0881553ab6d9d0f2d11cd1cdb0 | Java | kpratik2015/Smart-India-Hackathon | /Non-Working-Codes/SqLite-2-tables/databaseHelper.java | UTF-8 | 3,922 | 2.25 | 2 | [] | no_license | package com.pratikkataria.hackathon;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static com.pratikkataria.hackathon.MyFirebaseMessagingService.NOTIFY_MSG;
/**
* Created by hp on 24-03-2017.
*/
public class databaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "meter.db";
public static final String TABLE_NAME = "meter_table";
InputStream inputStream;
public static int j = 0;
public databaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
inputStream = context.getResources().openRawResource(R.raw.meterdevicereport);
}
@Override
public void onCreate(SQLiteDatabase db) {
//FileReader file = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String tableName = TABLE_NAME;
String createtable = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (DEVICE TEXT, VOLTAGE INTEGER)";
db.execSQL(createtable);
String createNotifyTable = "CREATE TABLE IF NOT EXISTS NOTIFY (ID INTEGER PRIMARY KEY, MESSAGE TEXT)";
Log.e("DataBase", createNotifyTable);
db.execSQL(createNotifyTable);
String columns = "device, voltage";
String str1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
String str2 = ");";
//String columns1 = "ID, MESSAGE";
ContentValues values = new ContentValues();
values.put("MESSAGE", NOTIFY_MSG);
db.insert("NOTIFY",null, values);
//String str3 = "INSERT INTO NOTIFY (" + columns1 + ") values( '"+ NOTIFY_MSG +"' )";
//Log.e("DataBase", str3);
db.beginTransaction();
//db.execSQL(str3);
int i = 0;
try {
while ((line = buffer.readLine()) != null) {
if(i > 0) {
StringBuilder sb = new StringBuilder(str1);
String[] str = line.split(",");
sb.append("'" + str[1] + "',");
sb.append(str[9]);
sb.append(str2);
db.execSQL(sb.toString());
}
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
public void replicaOfOnCreate(){
SQLiteDatabase db = this.getWritableDatabase();
String createNotifyTable = "CREATE TABLE IF NOT EXISTS NOTIFY (ID INTEGER PRIMARY KEY, MESSAGE TEXT)";
Log.e("DataBase", createNotifyTable);
db.execSQL(createNotifyTable);
ContentValues values = new ContentValues();
values.put("MESSAGE", NOTIFY_MSG);
db.insert("NOTIFY",null, values);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS NOTIFY");
// create new tables
onCreate(db);
}
public Cursor showData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
return data;
}
public Cursor showNotificationData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM NOTIFY",null);
return data;
}
}
| true |
9ad8f9b64e1ff15acee3e0b636e2fa8abf4900be | Java | deepeshuniyal/JNDISpringBootTom8 | /src/main/java/com/deepeshuniyal/model/Customer.java | UTF-8 | 1,158 | 2.3125 | 2 | [] | no_license | package com.deepeshuniyal.model;
//import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.GenerationType;
//import javax.persistence.Id;
//import javax.persistence.SequenceGenerator;
//
//@Entity
//public class Customer {
//
// @Id
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="test2_id_seq")
// @SequenceGenerator(name="test2_id_seq", sequenceName="test2_id_seq", allocationSize=1)
// private int id;
// private String custName;
// private String country;
//
// public Customer() {
// }
//
// public Customer(int id, String custName, String country) {
// this.id = id;
// this.custName = custName;
// this.country = country;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getCustName() {
// return custName;
// }
//
// public void setCustName(String custName) {
// this.custName = custName;
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//}
| true |
14de44df7f13a50b632d417f905a05f942585322 | Java | akbartukhtamurotov/algorithms-part-1 | /src/main/java/org/learning/dynamicconnectivity/UFquickUnion.java | UTF-8 | 573 | 2.875 | 3 | [] | no_license | package org.learning.dynamicconnectivity;
public class UFquickUnion {
private int[] id;
public UFquickUnion(int n) {
id = new int[n];
for (int i = 0; i < n; i++) {
id[i] = i;
}
}
public void union(int p, int q) {
int rootOfP = findRoot(p);
int rootOfQ = findRoot(q);
id[rootOfP] = rootOfQ;
}
private int findRoot(int q) {
if (id[q] == q) return q;
return findRoot(id[q]);
}
boolean connected(int p, int q) {
return findRoot(p) == findRoot(q);
}
}
| true |
8703900329c5bded9530fd2c4e15b0aa5490023c | Java | SwarnavaChakraborty/PaymentTransferMicroservice | /src/test/java/com/revolut/dao/PaymentTransferDBTest.java | UTF-8 | 6,066 | 2.28125 | 2 | [] | no_license | package com.revolut.dao;
import static com.revolut.data.TestDataUtil.getPaymentDetailsMock;
import static com.revolut.util.SourceID.AMAZON_PAY_SOURCE_ID;
import static com.revolut.util.SourceID.GOOGLE_PAY_SOURCE_ID;
import static com.revolut.util.SourceName.AMAZON_PAY_SOURCE;
import static com.revolut.util.SourceName.GOOGLE_PAY_SOURCE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.revolut.dto.Payment;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ PaymentTransferDB.class })
public class PaymentTransferDBTest {
@InjectMocks
private PaymentTransferDB paymentTransferDB;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
paymentTransferDB.rePopulateValues();
}
@Test
public void testGetTotalAmountBySource() {
assertNotNull(paymentTransferDB.getTotalAmountBySource(AMAZON_PAY_SOURCE_ID.getIdValue()));
assertNotNull(paymentTransferDB.getTotalAmountBySource(GOOGLE_PAY_SOURCE_ID.getIdValue()));
assertEquals(Integer.valueOf(0), paymentTransferDB.getTotalAmountBySource(3));
assertEquals(Integer.valueOf(0), paymentTransferDB.getTotalAmountBySource(0));
}
@Test
public void testAddAmount() {
Map<String, List<Payment>> afterMap = paymentTransferDB.addAmount(getPaymentDetailsMock());
List<Payment> payments = afterMap.get(AMAZON_PAY_SOURCE.getValue()).stream()
.filter(p -> p.getAmount().equals(getPaymentDetailsMock().getAmount())).collect(Collectors.toList());
assertNotNull(payments);
assertEquals(getPaymentDetailsMock().getAmount(), payments.get(0).getAmount());
}
@Test
public void testWithdrawPayment() {
int initialSize = paymentTransferDB.getAllDetails().get(AMAZON_PAY_SOURCE.getValue()).size();
UUID idToRemove = paymentTransferDB.getAllDetails().get(AMAZON_PAY_SOURCE.getValue()).get(0).getTransactionId();
paymentTransferDB.withdrawPayment(idToRemove);
assertEquals(initialSize - 1, paymentTransferDB.getAllDetails().get(AMAZON_PAY_SOURCE.getValue()).size());
assertEquals(0, paymentTransferDB.getAllDetails().get(AMAZON_PAY_SOURCE.getValue()).stream()
.filter(p -> p.getTransactionId().equals(idToRemove)).count());
}
@Test
public void testTransferAmountFirst() {
int initialFirst = paymentTransferDB.getTotalAmountBySource(AMAZON_PAY_SOURCE_ID.getIdValue());
int initialSecond = paymentTransferDB.getTotalAmountBySource(GOOGLE_PAY_SOURCE_ID.getIdValue());
paymentTransferDB.transferAmount(100);
assertEquals(Integer.valueOf(initialFirst - 100), paymentTransferDB.getTotalAmountBySource(AMAZON_PAY_SOURCE_ID.getIdValue()));
assertEquals(Integer.valueOf(initialSecond + 100), paymentTransferDB.getTotalAmountBySource(GOOGLE_PAY_SOURCE_ID.getIdValue()));
}
@Test
public void testTransferAmountSecond() {
int initialFirst = paymentTransferDB.getTotalAmountBySource(AMAZON_PAY_SOURCE_ID.getIdValue());
int initialSecond = paymentTransferDB.getTotalAmountBySource(GOOGLE_PAY_SOURCE_ID.getIdValue());
paymentTransferDB.transferAmount(1000);
assertEquals(Integer.valueOf(initialFirst - 1000), paymentTransferDB.getTotalAmountBySource(AMAZON_PAY_SOURCE_ID.getIdValue()));
assertEquals(Integer.valueOf(initialSecond + 1000), paymentTransferDB.getTotalAmountBySource(GOOGLE_PAY_SOURCE_ID.getIdValue()));
}
@Test
public void testTransferAmountThird() {
Integer initialFirst = paymentTransferDB.getTotalAmountBySource(AMAZON_PAY_SOURCE_ID.getIdValue());
Integer initialSecond = paymentTransferDB.getTotalAmountBySource(GOOGLE_PAY_SOURCE_ID.getIdValue());
paymentTransferDB.transferAmount(10000);
assertEquals(initialFirst, paymentTransferDB.getTotalAmountBySource(AMAZON_PAY_SOURCE_ID.getIdValue()));
assertEquals(initialSecond, paymentTransferDB.getTotalAmountBySource(GOOGLE_PAY_SOURCE_ID.getIdValue()));
}
@Test
public void testTransferPaymentByTransactionIdFirst() {
List<Payment> amazons = paymentTransferDB.getAllDetails().get(AMAZON_PAY_SOURCE.getValue());
List<Payment> gPay = paymentTransferDB.getAllDetails().get(GOOGLE_PAY_SOURCE.getValue());
UUID idToTransfer = amazons.get(0).getTransactionId();
assertNotEquals(0, amazons.stream().filter(p -> p.getTransactionId().equals(idToTransfer)).count());
assertEquals(0, gPay.stream().filter(p -> p.getTransactionId().equals(idToTransfer)).count());
paymentTransferDB.transferPaymentByTransactionId(idToTransfer);
assertEquals(0, amazons.stream().filter(p -> p.getTransactionId().equals(idToTransfer)).count());
assertEquals(1, gPay.stream().filter(p -> p.getTransactionId().equals(idToTransfer)).count());
}
@Test
public void testTransferPaymentByTransactionIdSecond() {
List<Payment> amazons = paymentTransferDB.getAllDetails().get(AMAZON_PAY_SOURCE.getValue());
List<Payment> gPay = paymentTransferDB.getAllDetails().get(GOOGLE_PAY_SOURCE.getValue());
UUID idToTransfer = UUID.randomUUID();
assertEquals(0, amazons.stream().filter(p -> p.getTransactionId().equals(idToTransfer)).count());
assertEquals(0, gPay.stream().filter(p -> p.getTransactionId().equals(idToTransfer)).count());
paymentTransferDB.transferPaymentByTransactionId(idToTransfer);
assertEquals(0, amazons.stream().filter(p -> p.getTransactionId().equals(idToTransfer)).count());
assertEquals(0, gPay.stream().filter(p -> p.getTransactionId().equals(idToTransfer)).count());
}
@Test
public void testTransferAllAmount() {
assertNotEquals(0, paymentTransferDB.getAllDetails().get(AMAZON_PAY_SOURCE.getValue()).size());
paymentTransferDB.transferAllAmount();
assertEquals(0, paymentTransferDB.getAllDetails().get(AMAZON_PAY_SOURCE.getValue()).size());
}
}
| true |
838eb5d7c821ec7ea624fbe7c63ec368236a1a43 | Java | wooou/WxShare | /app/src/main/java/com/wooou/play/ShareInfo.java | UTF-8 | 1,457 | 2.0625 | 2 | [
"MIT"
] | permissive | package com.wooou.play;
import android.graphics.Bitmap;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
public class ShareInfo {
private String title;
private String description;
private String url;
private Bitmap bitmap;
private int sceneType = SendMessageToWX.Req.WXSceneSession;
public ShareInfo() {
}
public ShareInfo(String title, String description, String url) {
this.title = title;
this.description = description;
this.url = url;
}
public ShareInfo(String title, String description, String url, Bitmap bitmap) {
this.title = title;
this.description = description;
this.url = url;
this.bitmap = bitmap;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public int getSceneType() {
return sceneType;
}
public void setSceneType(int sceneType) {
this.sceneType = sceneType;
}
}
| true |
6f7b916ce1bbb72caa243a2392c4b3b8722868d1 | Java | sukanyasehgal/AriCare | /Code/Aricare/src/com/aricent/controllers/AddDoctor.java | UTF-8 | 3,673 | 2.28125 | 2 | [] | no_license | /***********************************************************************
File Name : AddDoctor.java
Principal Author : GR_TH3_03
Subsystem Name :
Module Name : add doctor
Date of First Release : 10-05-2016
Author : GR_TH3_03
Description : class controlling add Doctor module
Change History
Version : 1.0
Date(DD/MM/YYYY) : 10-05-2016
Modified by : GR_TH3_03
Description of change :
***********************************************************************/
package com.aricent.controllers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.aricent.daofiles.AddDoctorDAO;
import com.aricent.daointerfaces.AddDoctorInterface;
import com.aricent.pojofiles.AddDoctorBean;
/**
* Servlet implementation class AddDoctorServlet
*
* @see AddDoctor
* @see addDoctor#doPost()
* @version 1.0
* @author GR_TH3_03
*/
@WebServlet("/AddDoctor")
public class AddDoctor extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddDoctor() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
* @exception ServletException
* , IOException
* @see AddDoctor
* @version initial version
* @author GR_TH3_03
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// creating object of Logger class
final Logger log = Logger.getLogger(AddDoctor.class);
log.info("add doctor module started");
// creating object of bean class
AddDoctorBean beanObject = new AddDoctorBean();
// setting objects of bean class taking parameters from form
beanObject.setName(request.getParameter("name"));
beanObject.setContactNumber(Long.parseLong(request
.getParameter("phone")));
beanObject.setAddress(request.getParameter("address"));
beanObject.setQualification(request.getParameter("qualification"));
beanObject.setTimingToMeet(request.getParameter("timings"));
beanObject.setSpecialization(request.getParameter("specialization"));
beanObject.setImage(request.getParameter("pic"));
beanObject.setEmail(request.getParameter("email_id"));
// creating object of dao class
AddDoctorInterface addDoctor = new AddDoctorDAO();
// defining variable to check if doctor already exists
boolean existing = addDoctor.checkFordatabase(beanObject);
if (existing) {
log.info("doctor is already present with this contact number");
// setting request attribute and forwarding to Signup.jsp
request.setAttribute("statusTrue", "already present");
request.getRequestDispatcher("addDoctorForm.jsp").forward(request,
response);
} else {
log.info("new doctor has been added");
// calling method to add doctor
addDoctor.addDoctor(beanObject);
// setting request attribute and forwarding to Signup.jsp
request.setAttribute("statusFalse", "added");
request.getRequestDispatcher("addDoctorForm.jsp").forward(request,
response);
}
}
}
| true |
35a72088c36ccb6d3f8176a52d2a8c50084a756d | Java | linsir6/WeChat_java | /com/tencent/mm/plugin/sns/ui/QTextView$a.java | UTF-8 | 3,154 | 2.03125 | 2 | [] | no_license | package com.tencent.mm.plugin.sns.ui;
import android.text.TextPaint;
import java.util.ArrayList;
import java.util.HashMap;
class QTextView$a {
private static HashMap<String, Integer> nQL = new HashMap();
private String aAL = "";
private int nQF = 0;
boolean nQG = false;
ArrayList<int[]> nQH = new ArrayList();
float nQI;
float nQJ;
float nQK;
public final int a(String str, String str2, String str3, int i, int i2, TextPaint textPaint) {
String str4 = str + str2 + str3 + i + i2;
if (str4.equals(this.aAL)) {
return this.nQF;
}
this.aAL = str4;
this.nQH.clear();
this.nQG = false;
this.nQI = 0.0f;
this.nQJ = 0.0f;
this.nQK = 0.0f;
if (i2 == -1) {
this.nQH.add(new int[]{null, str.length()});
this.nQF = (int) (textPaint.measureText(str) + 0.5f);
return this.nQF;
}
if (str2 != null) {
this.nQJ = textPaint.measureText(str2);
}
if (str3 != null) {
this.nQK = textPaint.measureText(str3);
}
int i3 = -1;
float f = 0.0f;
Object obj = 1;
int i4 = 0;
while (i4 < str.length()) {
if (i3 == -1) {
i3 = i4;
}
if (this.nQH.size() == i) {
this.nQG = true;
break;
}
float measureText = textPaint.measureText(str.charAt(i4));
Object obj2 = null;
if (str.charAt(i4) == 10) {
obj2 = 1;
this.nQH.add(new int[]{i3, i4 - 1});
} else if (f + measureText >= ((float) i2)) {
obj2 = 1;
if (str.charAt(i4) == ' ' || obj == null) {
i4--;
this.nQH.add(new int[]{i3, i4});
} else {
while (str.charAt(i4) != ' ') {
i4--;
if (i4 == 0) {
break;
}
}
this.nQH.add(new int[]{i3, i4});
}
}
if (obj2 != null) {
i3 = -1;
f = 0.0f;
if (this.nQH.size() == i - 1) {
i2 = (int) (((float) i2) - (this.nQJ + this.nQK));
obj = null;
}
} else {
f += measureText;
if (i4 == str.length() - 1) {
this.nQH.add(new int[]{i3, i4});
}
}
i4++;
}
if (this.nQG) {
int[] iArr = (int[]) this.nQH.get(this.nQH.size() - 1);
this.nQI = textPaint.measureText(str.substring(iArr[0], iArr[1] + 1));
}
if (this.nQH.size() == 0) {
this.nQF = 0;
return this.nQF;
} else if (this.nQH.size() == 1) {
this.nQF = (int) (textPaint.measureText(str) + 0.5f);
return this.nQF;
} else {
this.nQF = i2;
return this.nQF;
}
}
}
| true |
7a9ab7ed79ae3be86434329d0049d711c7e4c583 | Java | anishgoyal24/JavaJuneWeekEnd | /CodeD/src/Player.java | UTF-8 | 1,622 | 2.890625 | 3 | [] | no_license | import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Player implements GameConstants {
private int x;
private int y;
private int w;
private int h;
private int speed;
private Image image;
private int force ;
private boolean isJumped;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public int getForce() {
return force;
}
public void setForce(int force) {
this.force = force;
}
public boolean isJumped() {
return isJumped;
}
public void setJumped(boolean isJumped) {
this.isJumped = isJumped;
}
public void jump(){
if(!isJumped){
isJumped = true;
force = -15;
y+=force;
}
}
public void fall(){
if(y>=(FLOOR-h)){
isJumped = false;
y = (FLOOR - h);
}
if(y<(FLOOR - h)){
force += GRAVITY;
y+=force;
}
}
public void direction(int dir){
speed = 5;
speed = speed * dir;
}
public void move(){
x+=speed;
}
public Player(){
w = h = 100;
y = FLOOR - h;
x = 100;
image = new ImageIcon(Player.class.getResource(PLAYER_IMAGE)).getImage();
}
public void drawPlayer(Graphics g){
g.drawImage(image, x, y,w,h ,null);
}
}
| true |
b1ad06ae24f770ebb0cb3421281e5cf5aa190dd4 | Java | JanKodowanie/bookingo-backend | /src/main/java/pw/testoprog/bookingo/services/JWTManager.java | UTF-8 | 1,932 | 2.5625 | 3 | [] | no_license | package pw.testoprog.bookingo.services;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.function.Function;
@Service
public class JWTManager {
// we must hide the key in .env!!!
private String SECRET_KEY = "BG.9qNIOIu2IV6AUXTBwG1Eo5erKANGhTAEzqKFplYWB3VsWl3G46RxZGYayAiz";
public String extractEmail(String token) {
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
private String createToken(Map<String, Object> claims, String email) {
return Jwts.builder().setClaims(claims).setSubject(email).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000*60*60*10))
.signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String email = extractEmail(token);
return (email.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
| true |
dffa4f6c31fb12142564504e671f500bf9ff456e | Java | vdurmont/vdmail | /src/main/java/com/vdurmont/vdmail/controller/EmailController.java | UTF-8 | 1,849 | 2.15625 | 2 | [
"MIT"
] | permissive | package com.vdurmont.vdmail.controller;
import com.vdurmont.vdmail.dto.EmailDTO;
import com.vdurmont.vdmail.dto.UserDTO;
import com.vdurmont.vdmail.mapper.EmailMapper;
import com.vdurmont.vdmail.model.Email;
import com.vdurmont.vdmail.model.User;
import com.vdurmont.vdmail.service.EmailService;
import com.vdurmont.vdmail.service.LoginService;
import com.vdurmont.vdmail.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
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 org.springframework.web.bind.annotation.ResponseStatus;
import javax.inject.Inject;
@Controller
@RequestMapping("emails")
public class EmailController {
private static final Logger LOGGER = Logger.getLogger(EmailController.class);
@Inject private EmailMapper emailMapper;
@Inject private EmailService emailService;
@Inject private LoginService loginService;
@Inject private UserService userService;
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public EmailDTO sendEmail(@RequestBody EmailDTO dto) {
LOGGER.trace("Sending email=" + dto);
User user = this.loginService.getRequiredCurrentUser();
User recipient = null;
UserDTO recipientDTO = dto.getRecipient();
if (recipientDTO != null) {
recipient = this.userService.getOrCreate(recipientDTO.getAddress());
}
Email email = this.emailService.send(user, recipient, dto.getSubject(), dto.getContent());
return this.emailMapper.generate(email);
}
}
| true |