blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3cfcac466e45302e0cc7e0d1e979db354d5d601e | 70f7a06017ece67137586e1567726579206d71c7 | /alimama/src/main/java/com/taobao/tao/log/godeye/GodeyeInitializer.java | bbe76477393488a70d342a755436d8afed333a2e | [] | no_license | liepeiming/xposed_chatbot | 5a3842bd07250bafaffa9f468562021cfc38ca25 | 0be08fc3e1a95028f8c074f02ca9714dc3c4dc31 | refs/heads/master | 2022-12-20T16:48:21.747036 | 2020-10-14T02:37:49 | 2020-10-14T02:37:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,550 | java | package com.taobao.tao.log.godeye;
import android.app.Application;
import com.taobao.android.tlog.protocol.Constants;
import com.taobao.android.tlog.protocol.model.GodeyeInfo;
import com.taobao.tao.log.godeye.core.GodEyeAppListener;
import com.taobao.tao.log.godeye.core.GodEyeReponse;
import com.taobao.tao.log.godeye.core.control.Godeye;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
public class GodeyeInitializer {
public GodeyeConfig config;
AtomicBoolean enabling;
private GodeyeInitializer() {
this.enabling = new AtomicBoolean(false);
this.config = null;
}
private static class CreateInstance {
/* access modifiers changed from: private */
public static GodeyeInitializer instance = new GodeyeInitializer();
private CreateInstance() {
}
}
public static synchronized GodeyeInitializer getInstance() {
GodeyeInitializer access$100;
synchronized (GodeyeInitializer.class) {
access$100 = CreateInstance.instance;
}
return access$100;
}
public void init(Application application, GodeyeConfig godeyeConfig) {
if (this.enabling.compareAndSet(false, true)) {
if (godeyeConfig == null) {
godeyeConfig = new GodeyeConfig();
}
this.config = godeyeConfig;
String str = this.config.appVersion;
String str2 = this.config.packageTag;
String str3 = this.config.appId;
Godeye.sharedInstance().utdid = this.config.utdid;
Godeye.sharedInstance().initialize(application, str3, str);
Godeye.sharedInstance().setBuildId(str2);
}
}
public void registGodEyeReponse(String str, GodEyeReponse godEyeReponse) {
if (str != null && godEyeReponse != null) {
Godeye.sharedInstance().godEyeReponses.put(str, godEyeReponse);
}
}
public boolean handleRemoteCommand(GodeyeInfo godeyeInfo) {
return Godeye.sharedInstance().handleRemoteCommand(godeyeInfo);
}
public void registGodEyeAppListener(GodEyeAppListener godEyeAppListener) {
if (godEyeAppListener != null) {
Godeye.sharedInstance().godEyeAppListener = godEyeAppListener;
}
}
public void onAccurateBootFinished(HashMap<String, String> hashMap) {
Godeye.sharedInstance().defaultGodeyeJointPointCenter().invokeCustomEventJointPointHandlersIfExist(Constants.AndroidJointPointKey.EVENT_KEY_APP_STARTED);
}
}
| [
"zhangquan@snqu.com"
] | zhangquan@snqu.com |
561c7d8612b3e1ef9c0c48070309a9bed57fd81c | 5be500d821ff6cb4694bb37314c776ee5004f1b7 | /Idea7.24/src/exer2/CheckAccount.java | 8dec8e5467668130c8360958a83d717492f7551a | [] | no_license | Gujm-2001/GITIDEATest01 | ad0fa5d4c4a6a400277c8c982c8ebc98f84d7ab0 | 370f73d68d78b647a8f3f278ea662032b142e1a6 | refs/heads/main | 2023-07-05T20:51:04.618774 | 2021-08-06T03:22:29 | 2021-08-06T03:22:29 | 389,048,713 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 743 | java | package exer2;
/**
* @author Gujm
* @date 2021/8/2 6:44 下午
*/
public class CheckAccount extends Account {
private double overdraft;
public CheckAccount(int id, double balance, double annualInterestRate, double overdraft) {
super(id, balance, annualInterestRate);
this.overdraft = overdraft;
}
public void withdraw(double amount) {
if (amount < getBalance()) {
super.withdraw(amount);
} else if (amount - getBalance() <= overdraft) {
overdraft -= (amount - getBalance());
setBalance(0.0);
} else{
System.out.println("超过可透支限额");
}
}
public double getOverdraft() {
return overdraft;
}
}
| [
"***@example.com"
] | ***@example.com |
83efe286f1e6ca18f546ad28589cc0ca3848508d | 0329b2aed9d3bd6ec4708d692ced5f4eace7e948 | /src/test/java/test/auctionsniper/SniperSnapshotTest.java | 4d536172ae23ed376dd04c6a95d42f326a39d784 | [
"Apache-2.0"
] | permissive | wetzlar/goos-rh | 244ee98ebceb8231adeda4e54fbf90bb1d1f9598 | 97ae86bbe6d0759c9c449401a75cece05280d0ec | refs/heads/master | 2020-04-25T16:19:34.264604 | 2019-02-27T13:01:59 | 2019-02-27T13:01:59 | 172,907,216 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,407 | java | package test.auctionsniper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import auctionsniper.SniperSnapshot;
import auctionsniper.SniperState;
public class SniperSnapshotTest {
@Test
public void sniperStateEnumEquals() {
SniperState state1 = SniperState.BIDDING;
SniperState state2 = SniperState.BIDDING;
assertEquals(state1.toString(), state2.toString());
assertEquals(state1.hashCode(), state2.hashCode());
assertTrue(state1.equals(state2));
}
@Test
public void equalSniperSnapshotsAreEqual() {
SniperSnapshot snap1 = new SniperSnapshot("item-1", 0, 0, SniperState.JOINING);
SniperSnapshot snap2 = new SniperSnapshot("item-1", 0, 0, SniperState.JOINING);
assertTrue(snap1.equals(snap2));
assertTrue(snap2.equals(snap1));
assertEquals(snap1.hashCode(), snap2.hashCode());
assertEquals(snap1.toString(), snap2.toString());
}
@Test
public void snapshotsWithDifferentItemAreNotEqual() {
SniperSnapshot snap1 = new SniperSnapshot("item-1", 0, 0, SniperState.JOINING);
SniperSnapshot snap2 = new SniperSnapshot("item-2", 0, 0, SniperState.JOINING);
assertFalse(snap1.equals(snap2));
assertFalse(snap2.equals(snap1));
}
@Test
public void snapshotsWithDifferentPriceAreNotEqual() {
SniperSnapshot snap1 = new SniperSnapshot("item-1", 0, 0, SniperState.JOINING);
SniperSnapshot snap2 = new SniperSnapshot("item-1", 50, 0, SniperState.JOINING);
assertFalse(snap1.equals(snap2));
assertFalse(snap2.equals(snap1));
}
@Test
public void snapshotsWithDifferentBidAreNotEqual() {
SniperSnapshot snap1 = new SniperSnapshot("item-1", 0, 0, SniperState.JOINING);
SniperSnapshot snap2 = new SniperSnapshot("item-1", 0, 50, SniperState.JOINING);
assertFalse(snap1.equals(snap2));
assertFalse(snap2.equals(snap1));
}
@Test
public void snapshotsWithDifferentStateAreNotEqual() {
SniperSnapshot snap1 = new SniperSnapshot("item-1", 0, 0, SniperState.JOINING);
SniperSnapshot snap2 = new SniperSnapshot("item-1", 0, 0, SniperState.BIDDING);
assertFalse(snap1.equals(snap2));
assertFalse(snap2.equals(snap1));
}
}
| [
"rhaendel@users.noreply.github.com"
] | rhaendel@users.noreply.github.com |
2be3de45155010ae8954fd97b336cd51881bee4f | 5b0df119590bfcc96cff87eb058eded08bd583e0 | /src/main/java/pe/edu/upc/controller/SalesController.java | 33b91f7ae16d391d31e5c95ebce35a2a05c672a1 | [] | no_license | marcosrm7/FinanzasTF | ac5f585392f7de6be6455d924dd08471173a7754 | 208cc88291c8f54f0b2cc5bcedadd48399f1eb92 | refs/heads/master | 2023-01-20T09:31:59.541930 | 2020-11-24T07:27:56 | 2020-11-24T07:27:56 | 297,845,075 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,150 | java | package pe.edu.upc.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import pe.edu.upc.entity.Client;
import pe.edu.upc.repository.ISellRepository;
@Controller
@RequestMapping("/sales")
public class SalesController {
@Autowired
ISellRepository ventasRepository;
@Autowired
private ClientController clienteCont;
@GetMapping(value = "/")
public String mostrarVentas(Model model) {
model.addAttribute("client", clienteCont.objCliente.get());
model.addAttribute("ventas", ventasRepository.findByUser(clienteCont.objCliente.get().getIdClient()));
// model.addAttribute("ventas", ventasRepository.findAll());
return "sell/listSales";
}
@GetMapping(value = "/all")
public String mostrarVentasall(Model model) {
model.addAttribute("ventas", ventasRepository.findAll());
return "sell/listSalesAll";
}
}
| [
"m2066r@gmail.com"
] | m2066r@gmail.com |
87172d945047d7b5927581cd3391b6896eb10a55 | 18f4d665db21e0aeb22b964b517c7ec4d3f76e6f | /src/main/java/ni/jug/exchangerate/bank/Bank.java | b58913bb2bff5529e07a4264a6bc002ad605e4de | [
"MIT"
] | permissive | jugnicaragua/exchange-rate-client | 4ec071a2cf7abe0f02ad79c819957e3fd541e180 | 6d1b32076bfcfbbb1444a6260e72f5a9f9068842 | refs/heads/master | 2022-06-19T04:15:51.629796 | 2022-06-01T23:35:13 | 2022-06-01T23:35:13 | 164,456,962 | 2 | 2 | MIT | 2021-08-28T08:22:03 | 2019-01-07T16:04:21 | Java | UTF-8 | Java | false | false | 871 | java | package ni.jug.exchangerate.bank;
/**
* @author aalaniz
*/
public final class Bank {
private final String id;
private final String description;
private final String url;
public Bank(String id, String description, String url) {
this.id = id;
this.description = description;
this.url = url;
}
public Bank(BankScraper scraper) {
this(scraper.bank(), scraper.description(), scraper.url());
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
@Override
public String toString() {
return "Bank{" +
"id='" + id + '\'' +
", description='" + description + '\'' +
", url='" + url + '\'' +
'}';
}
}
| [
"arjoalaniz@gmail.com"
] | arjoalaniz@gmail.com |
cd706e24fe3c4195cf734fb3104845f8adde80b3 | e5a53a19d19fa34751a9b3f9a6522625969e07a9 | /src/main/java/com/pruebaJWT/serviceImpl/ClienteServiceImpl.java | c305f2b12d5ec94c594132fa94c6bfad2de73613 | [] | no_license | BreitnerRoldan/pruebaJwt | b652ed5a50d8bb329b837db88a16c49c3c99139c | e1c4858206b7f29113ee25549ae9e4d541ce3403 | refs/heads/master | 2023-03-20T13:34:40.993205 | 2021-03-16T16:51:05 | 2021-03-16T16:51:05 | 348,416,048 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 840 | java | package com.pruebaJWT.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pruebaJWT.entity.Cliente;
import com.pruebaJWT.repository.ClienteRepository;
import com.pruebaJWT.service.ClienteService;
@Service
public class ClienteServiceImpl implements ClienteService {
@Autowired
private ClienteRepository clienteRepository;
@Override
public List<Cliente> findAll() {
return clienteRepository.findAll();
}
@Override
public Cliente Create(Cliente cliente) {
// TODO Auto-generated method stub
return null;
}
@Override
public Cliente update(long id, Cliente cliente) {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleted(long id) {
// TODO Auto-generated method stub
}
}
| [
"bjroldan@hotmail.com"
] | bjroldan@hotmail.com |
c3f3c7abfe24927dc02feae0ce96d698c18d21f4 | 44b18053cdd56f054821e0af93eef1b116053bc9 | /core/cas-server-core-authentication-api/src/test/java/org/apereo/cas/authentication/credential/CredentialTests.java | 637cb12347cf7f19f5426410ba71a3f78cd723c3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | dongyongok/cas | c364f27fe5ff10b779737f9764ea7a0f5623087b | 45139a50fbdf5fe37302d556260395fd73a67007 | refs/heads/master | 2022-09-19T10:31:20.645502 | 2022-09-06T03:43:15 | 2022-09-06T03:43:15 | 231,773,571 | 0 | 0 | Apache-2.0 | 2022-09-19T01:52:27 | 2020-01-04T14:06:27 | Java | UTF-8 | Java | false | false | 1,795 | java | package org.apereo.cas.authentication.credential;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* This is {@link CredentialTests}.
*
* @author Misagh Moayyed
* @since 6.3.0
*/
@Tag("Authentication")
public class CredentialTests {
@Test
public void verifyCred() {
val c1 = getCredential();
assertNotNull(c1.getCredentialClass());
assertTrue(c1.isValid());
}
@Test
public void verifyEquals() {
val c1 = getCredential();
val c2 = getCredential();
assertNotNull(c1.getCredentialClass());
assertTrue(c1.isValid());
assertTrue(Math.abs(c1.hashCode()) > 0);
assertNotEquals(c2, c1);
assertEquals(c1, c1);
}
@Test
public void verifyValid() {
val c = new AbstractCredential() {
private static final long serialVersionUID = -1746359565306558329L;
@Override
public String getId() {
return null;
}
};
val context = mock(ValidationContext.class);
when(context.getMessageContext()).thenReturn(mock(MessageContext.class));
assertDoesNotThrow(() -> c.validate(context));
}
private static AbstractCredential getCredential() {
return new AbstractCredential() {
private static final long serialVersionUID = -1746359565306558329L;
@Override
public String getId() {
return UUID.randomUUID().toString();
}
};
}
}
| [
"mm1844@gmail.com"
] | mm1844@gmail.com |
250d521fa84a1899132b49e31bd6ec8c8d49a8fe | 018eb12e0891be87287f210aad88d4b5a76de044 | /api/src/main/java/anz/api/controllers/exceptions/PreconditionFailedException.java | 2f0b612cd1bd402010879a93a3bf0bb900d06201 | [] | no_license | cluze/anz-homework | a89d9a660ee20cddc03a6ebf4cb7b76c6e7b4278 | 55f410c218d7a60f06a1535deafbf5a745a8e1d7 | refs/heads/master | 2020-09-22T12:26:00.715261 | 2016-08-18T16:03:37 | 2016-08-18T16:03:37 | 66,010,091 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 721 | java | package anz.api.controllers.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.PRECONDITION_FAILED)
public class PreconditionFailedException extends RuntimeException {
private static final long serialVersionUID = 4725566183238968302L;
public PreconditionFailedException() {
}
public PreconditionFailedException(final String message) {
super(message);
}
public PreconditionFailedException(final Throwable throwable) {
super(throwable);
}
public PreconditionFailedException(final String message, final Throwable throwable) {
super(message, throwable);
}
} | [
"cluze@163.com"
] | cluze@163.com |
0f4b12b748161aa9b268197246b33539715f1b1b | 27783b249a336fd383c48ae40b42782eb3394bfa | /ElectronicEquipment/src/Computer.java | 2dbe4c33bc506b234f5391a36a8178730100034e | [] | no_license | mukamir/Courses | 31543f55912bfc54145103c147c37e9c70482875 | 8889392ccc7fed18675fbf713bd6e7e972cfd630 | refs/heads/master | 2021-01-15T16:29:01.113268 | 2015-04-05T03:13:12 | 2015-04-05T03:13:12 | 33,428,753 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,383 | java | /*
*
*/
public class Computer extends ElectronicDevice
{
/*** Class Constants ***/
private final boolean DEFAULT_LAPTOP = true;
private final double DEFAULT_HARD_DRIVE = 500.0; //in GB's
/*** Class Variables ***/
private boolean laptop;
private double hardDrive;
/*** Constructors ***/
public Computer()
{
super();
this.setLaptop( DEFAULT_LAPTOP );
this.setHardDrive( DEFAULT_HARD_DRIVE );
}
public Computer( String manufacturer, String model, double cost, double weight, double power,
boolean laptop, double hardDrive )
{
super( manufacturer, model, cost, weight, power );
this.setLaptop( laptop );
this.setHardDrive( hardDrive );
}
/*** Accessor Methods -- getters ***/
public boolean getLaptop()
{
return this.laptop;
}
public double getHardDrive()
{
return this.hardDrive;
}
@Override
public String toString()
{
return "Computer: \n" + super.toString() +
String.format( " %-7s %8b%n", "Laptop:", this.getLaptop() ) +
String.format( " %-7s %8.2f%n", "HardDrive:", this.getHardDrive() );
}
/*** Mutators/Transformers -- setters ***/
public void setLaptop( boolean laptop)
{
this.laptop = laptop;
}
public void setHardDrive( double hardDrive)
{
this.hardDrive = hardDrive;
}
} | [
"am25524@email.vccs.edu"
] | am25524@email.vccs.edu |
2fb1715ad81baa15da6f61a60f86097c00102562 | f9ab60a878b1a7626ed7162b752f8cc6070b1354 | /src/cow/core/ClientHandler.java | 6aa1b78776a8ef1be1428c2f1a018af066f2ec52 | [] | no_license | worldofbalance/wob-server | de0619c629df10e6ac3495b4e4432e770453eab4 | ed4642df7dcf707f44f0310de9967502ad896df6 | refs/heads/development | 2020-04-06T05:59:41.374118 | 2017-07-17T11:37:42 | 2017-07-17T11:37:42 | 54,063,625 | 4 | 7 | null | 2017-07-17T11:37:42 | 2016-03-16T20:19:32 | Java | UTF-8 | Java | false | false | 2,441 | java | package cow.core;
// Java Imports
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
// Other Imports
import shared.metadata.Constants;
import shared.util.Log;
public class ClientHandler implements Runnable {
// Variables
private final List<GameClient> activeClients = new ArrayList<GameClient>();
private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
private long lastTime;
private float deltaTime;
// Comparators
public static final Comparator<ClientHandler> SizeComparator = new Comparator<ClientHandler>() {
public int compare(ClientHandler o1, ClientHandler o2) {
return o1.size() - o2.size();
}
};
public ClientHandler(GameClient client) {
add(client);
}
public void start() {
lastTime = System.nanoTime();
service.scheduleAtFixedRate(this, 0, Constants.TICK_NANOSECOND, TimeUnit.NANOSECONDS);
}
public void run() {
long now = System.nanoTime();
deltaTime += (now - lastTime) / Constants.TICK_NANOSECOND;
lastTime = now;
if (deltaTime >= 1) {
Iterator<GameClient> it = activeClients.iterator();
while (it.hasNext()) {
GameClient client = it.next();
for (int i = 0; i < 10; i++) {
client.run();
}
if (!client.isAlive()) {
it.remove();
GameServer.getInstance().removeActiveClient(client.getID());
Log.printf("Client %s has ended", client.getID());
}
}
deltaTime--;
}
if (activeClients.isEmpty()) {
service.shutdown();
GameServer.getInstance().removeClientHandler(this);
}
}
public final void add(GameClient client) {
synchronized (activeClients) {
activeClients.add(client);
}
}
public void remove(GameClient client) {
synchronized (activeClients) {
activeClients.remove(client);
}
}
public int size() {
return activeClients.size();
}
public float getDeltaTime() {
return deltaTime;
}
}
| [
"rujoota@gmail.com"
] | rujoota@gmail.com |
56e9e8834e91ed92328bf94cbdaa5e7580ed5e7c | 101512b151731804b1960fa74ceb438beb87e701 | /src/test/java/com/chenhao/sell/SellApplicationTests.java | 62282263b75abdfb0139ba5abb37acbd6bbe064d | [] | no_license | MrPour/SpringbootSellDemo | 00664eea6dc56f09c6697719a06949efaf910a15 | e252b743064164ddfefa21012dd99dd8a8111015 | refs/heads/master | 2020-07-27T02:52:28.661195 | 2019-10-15T15:11:14 | 2019-10-15T15:11:14 | 208,843,927 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 330 | java | package com.chenhao.sell;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SellApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"418598391@qq.com"
] | 418598391@qq.com |
451683e77d964dc63f73220eac9c90317f9e70e4 | db97e102672f3d821c67164c1e38d20bfa58662d | /src/com/chery/wupin/dao/CategoryDao.java | 9452dfebaf799b3af41ef722d4af2299313a615e | [] | no_license | zhouhaihe12369/wupin | d2833ec4e258d86791c207b3c926201619c85fb5 | fd061668e545594d9194331e5a4058f1f008657b | refs/heads/master | 2016-09-10T11:20:37.465568 | 2015-03-23T08:46:11 | 2015-03-23T08:46:11 | 32,719,593 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 2,949 | java | package com.chery.wupin.dao;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.chery.wupin.bean.Category;
import com.chery.wupin.db.SQLHelper;
public class CategoryDao {
private SQLHelper helper = null;
private SQLiteDatabase database = null;
private Cursor cursor = null;
public CategoryDao(Context context){
helper = new SQLHelper(context);
}
//添加物品信息到数据库
public boolean addObj(Category ceg) {
boolean flag = false;
long id = -1;
try {
database = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SQLHelper.CTATOGERY, ceg.getCategory());
values.put(SQLHelper.NAME, ceg.getName());
id = database.insert(SQLHelper.TABLE_CATEGORY, null, values);
flag = (id != -1 ? true : false);
} catch (Exception e) {
} finally {
closeDatabase();
}
return flag;
}
//修改数据库中指定物品信息
public boolean updateInfo(Category ct,String whereClause,String[] whereArgs) {
boolean flag = false;
int count = 0;
try {
database = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SQLHelper.CTATOGERY, ct.getCategory());
count = database.update(SQLHelper.TABLE_CATEGORY, values, whereClause, whereArgs);
flag = (count > 0 ? true : false);
} catch (Exception e) {
} finally {
closeDatabase();
}
return flag;
}
//删除数据库中指定的数据
public boolean deleteInfo(String whereClause, String[] whereArgs) {
boolean flag = false;
int count = 0;
try {
database = helper.getWritableDatabase();
count = database.delete(SQLHelper.TABLE_CATEGORY, whereClause, whereArgs);
flag = (count > 0 ? true : false);
} catch (Exception e) {
} finally {
closeDatabase();
}
return flag;
}
//从数据库中查询所有物品信息
public List<Category> findByWhere(String selection , String[] selectionArgs) {
// TODO Auto-generated method stub
List<Category> record_list = new ArrayList<Category>();
try {
database = helper.getWritableDatabase();
cursor = database.query(SQLHelper.TABLE_CATEGORY, null, selection,selectionArgs, null, null, null, null);
while (cursor.moveToNext()) {
Category rob = new Category();
rob.set_id(cursor.getInt(cursor.getColumnIndexOrThrow(SQLHelper._ID)));
rob.setCategory(cursor.getString(cursor.getColumnIndexOrThrow(SQLHelper.CTATOGERY)));
rob.setName(cursor.getString(cursor.getColumnIndexOrThrow(SQLHelper.NAME)));
record_list.add(rob);
}
} catch (Exception e) {
} finally {
closeDatabase();
}
return record_list;
}
//关闭数据库
private void closeDatabase() {
if (database != null) {
database.close();
}
if (cursor != null) {
cursor.close();
cursor = null;
}
}
}
| [
"790132469@qq.com"
] | 790132469@qq.com |
837e31e8c86ef39fef47fde4be12aefa1a4e1ccf | 71467cd3753cae38ab425d252b6abe92cd570d81 | /src/main/java/com/contract/www/baseconfig/IBaseNativeSqlRepository.java | dc91984d99a65941e28d6283e9313e3971ad97ad | [] | no_license | wffff/contract | ba698669ac9652a31b5f45e5dec8369739e189c1 | 35f3f100ade8b5f7eed901d4665ec68dbb03081b | refs/heads/master | 2020-03-25T04:14:18.716634 | 2018-08-03T06:20:21 | 2018-08-03T06:20:21 | 143,384,681 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 779 | java | package com.contract.www.baseconfig;
import java.util.List;
/**
* Created by Adam.yao on 2017/12/10.
*/
public interface IBaseNativeSqlRepository<T> {
List<T> listByNativeSql(String sql);
List<T> listByNativeSql(String sql, Class<T> type);
/**
* 递归树查询
* @param id 当前id
* @param up 是否向上检索
* @param self 是否包含自已
* @param recursive 是否多层递归
* @param originClass 源类型
* @param targetClass 目标类型
* @param columns 目标字段列表
* @return
*/
@SuppressWarnings("Duplicates")
List<T> listTreeRecursive(Integer id, boolean up, boolean self, boolean recursive, Class<T> originClass, Class<T> targetClass, String... columns);
}
| [
"danny_wang@gomro.cn"
] | danny_wang@gomro.cn |
c9a50557dfff210ba87775c519f4f0da39790dd6 | 97c8abd041ed2f70a83ad14ac8caa7999be2819f | /java/matrix/src/main/java/witch/matrix/equation.java | 190a051ca88b74f95cfd6220cede537738011b79 | [] | no_license | thelittlewitch1/labs-numerical-methods | 931612cd860e6a41a5dc74dd269179e656f4ecb2 | 1eac7090fda2d8cebda4aa4482f6323e88d04ca7 | refs/heads/main | 2023-05-18T11:18:36.619697 | 2021-06-13T21:03:54 | 2021-06-13T21:03:54 | 331,098,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,342 | java | package witch.matrix;
import java.util.ArrayList;
import java.util.Arrays;
abstract class equation
{
ArrayList<ArrayList<Double>> A;
ArrayList<Double> b;
ArrayList<Double> x;
double eps;
int n;
int counter;
boolean isSolved;
public equation ()
{
n = 3; eps = 0.001;
ArrayList<Double> buf1 = new ArrayList<>(Arrays.asList(7.77, 0.27, - 0.29));
ArrayList<Double> buf2 = new ArrayList<>(Arrays.asList(1.15, - 6.22, 1.77));
ArrayList<Double> buf3 = new ArrayList<>(Arrays.asList(1.05, 4.52, 9.544));
A = new ArrayList<>(Arrays.asList(buf1, buf2, buf3));
b = new ArrayList<>(Arrays.asList(1.450, 1.050, - 1.310));
x = new ArrayList<>(); x.ensureCapacity(n);
isSolved = solve();
}
public equation (int _n, ArrayList<ArrayList<Double>> _A, ArrayList<Double> _b, double _eps)
{
n = _n;
A = _A;
b = _b;
eps = _eps;
isSolved = solve();
}
abstract boolean solve();
public ArrayList<ArrayList<Double>> getA ()
{ return A; }
public ArrayList<Double> getB ()
{ return b; }
public ArrayList<Double> getX ()
{ return x; }
public int getCounter ()
{return counter;}
public boolean getIsSolved ()
{return isSolved;}
public void show ()
{
System.out.printf("Result.\nNumber of iterations required to solve the equation: %d\nEquation:\n", counter);
for (int i = 0; i < n; i++)
{
System.out.print("| ");
for (int j = 0; j < n; j++)
{System.out.printf("%5.3f ", A.get(i).get(j));}
System.out.print(" |");
if (i == 0 ) {System.out.print(" * ");}
else {System.out.print(" ");}
System.out.printf ("| %5.3f |", x.get(i));
if (i == 0 ) {System.out.print(" = ");}
else {System.out.print(" ");}
double c = 0;
for (int j = 0; j < n; j++)
{
c = c + A.get(i).get(j)*x.get(j);
}
System.out.printf ("| %5.3f |", c);
if (i == 0 ) {System.out.print(" ~= ");}
else {System.out.print(" ");}
System.out.printf ("| %5.3f |\n", b.get(i));
}
System.out.print("\n\n");
}
}
| [
"50747039+thelittlewitch1@users.noreply.github.com"
] | 50747039+thelittlewitch1@users.noreply.github.com |
4452731c37f2f4d9a45043a5f797025f21924f9d | a73656d462c38f2e07ee7a9b3973f7ae34fb99ac | /mybatis-demo-03/src/main/java/com/chen/mybatis/demo3/pojo/BlogMessageList.java | 87619b1ca30bfa995f98ea9fea3593f87b497bb0 | [] | no_license | 569844962/Mybatis-Learn | b41c4e536e83a14c10018dbf4332e428c0dec95f | 501d4c6aea1a2503be8c8e8954617bf04f21fb5e | refs/heads/master | 2022-06-23T02:44:50.109406 | 2020-03-22T09:36:16 | 2020-03-22T09:36:16 | 248,634,363 | 0 | 0 | null | 2022-06-21T03:01:30 | 2020-03-20T00:36:05 | Java | UTF-8 | Java | false | false | 697 | java | package com.chen.mybatis.demo3.pojo;
import java.util.List;
import java.util.StringJoiner;
/**
* 〈〉
*
* @author chenmingjun
* @create 2020.2.25
* @company
*/
public class BlogMessageList {
private List<BlogMessage> blogMessageList;
public List<BlogMessage> getBlogMessageList() {
return blogMessageList;
}
public void setBlogMessageList(List<BlogMessage> blogMessageList) {
this.blogMessageList = blogMessageList;
}
@Override
public String toString() {
return new StringJoiner(", ", BlogMessageList.class.getSimpleName() + "[", "]")
.add("blogMessageList=" + blogMessageList)
.toString();
}
}
| [
"569844962@qq.com"
] | 569844962@qq.com |
477c3bc3b87f4eeb378de3689f20b2f26ddc8cac | 631c6c40370960cd9fe78c05cc1c25ee9c123114 | /app/src/main/java/com/wanglijun/payhelper/utils/AesUtil.java | 780c25298d30e137cd375977608cda26378ab1e4 | [] | no_license | hujunbiao/PayHelper | 77ad19ca69e5af2958ccca27eb42f4b1bab8d479 | 8c9df2ca173c952666c49ef18db4cd86ce503851 | refs/heads/master | 2020-07-06T18:13:08.318927 | 2019-05-07T09:58:41 | 2019-05-07T09:58:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,324 | java | package com.wanglijun.payhelper.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AesUtil {
private static String sKey = "bdb2515fcb0a3f85";
public static String encrypt(String encData) throws Exception {
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
return parseByte2HexStr(encrypted);// 此处使用BASE64做转码。
}
public static String decrypt(String sSrc) throws Exception {
try {
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = parseHexStr2Byte(sSrc);//先用base64解密
byte[] original = cipher.doFinal(encrypted1);
return new String(original, "utf-8");
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制String转换为byte数组
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
| [
"644920158@qq.com"
] | 644920158@qq.com |
31ac0d2242fc87783d8bb3469cfbc26e94b959af | 888091f7b4c0383690df27e687ed9bf608d9fe4c | /src/Leapyear.java | 1c712e634243bf76a1b2458bbaebedfed4411451 | [] | no_license | smithpauld/JSSChapter5 | 18c9922629e9e1f85621fd23185160454739302a | 8d24b5a86b583af48e171e2f555f3f32357e7f5a | refs/heads/master | 2021-01-22T05:34:09.297140 | 2017-02-28T04:01:01 | 2017-02-28T04:01:01 | 81,679,344 | 0 | 0 | null | 2017-02-28T04:01:02 | 2017-02-11T20:14:12 | Java | UTF-8 | Java | false | false | 935 | java |
/*Chapter 5 programs #1 and #2
* Gregorian Calendar
* The year must be greater than 1582 to determin
* if it is a leap year
*
*/
import java.util.Scanner;
public class Leapyear {
public static void main(String[] args) {
int year;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a year. I will then determine if it is a leap year");
System.out.println("enter 0 to quit the program");
year = scan.nextInt();
while (year != 0) {
if (year >= 1582) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
System.out.println("the year " + year + " is a leap year");
}
else {
System.out.println("The year " + year + " is not a leap year");
}
}
else {
System.out.println("The year entered must be greater than 1582, this is the year"+ "");
System.out.print("the Gregorian Calendar was adopted");
}
year = scan.nextInt();
}
}
}
| [
"iqnsmith@yahoo.com"
] | iqnsmith@yahoo.com |
0fdd51632b8b9515e3696a282158581f5ff8c16e | 80563d747a42e3e5f6f9fd32a3ac9cfa19d2de2b | /core/src/main/java/core/mapper/TaskMapper.java | bb71e78b22a0dc2341eeb9d2b99932538a6f8c9e | [] | no_license | dream-interactive/atlas.resource.service | 002cfc88c78ac226eb2f5058ed3c0c72b7f76126 | 3351f8900c30a1f055e6d924d80ee1f95201c6a3 | refs/heads/main | 2023-06-03T12:30:45.198706 | 2021-06-25T07:46:53 | 2021-06-25T07:46:53 | 292,042,226 | 0 | 0 | null | 2021-06-25T07:02:49 | 2020-09-01T15:54:43 | Java | UTF-8 | Java | false | false | 325 | java | package core.mapper;
import api.dto.TaskDTO;
import core.entity.Task;
import org.mapstruct.InjectionStrategy;
import org.mapstruct.Mapper;
@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface TaskMapper {
Task toEntity(TaskDTO dto);
TaskDTO toDTO(Task entity);
}
| [
"sevriukovmk@gmail.com"
] | sevriukovmk@gmail.com |
60b00fbae52eb2cdcad361fa63a8bbcb83e5f63b | d862d591020632b3d29f6d54d04a60465f282b8c | /src/singleton_pattern/singleton_with_serializable/SingletonSerializable.java | c660c884ec9899a33cbd30f2b01b5a6248e9051a | [] | no_license | zakaria5729/design-patterns-using-Java | 3c58f39e49f096f92dad807e2915833ccd1648c5 | 24f484597c3e6a4275325c39fbbc2076f2447a64 | refs/heads/master | 2020-05-15T19:35:49.849111 | 2019-04-20T22:22:09 | 2019-04-20T22:22:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 825 | java | package singleton_pattern.singleton_with_serializable;
import java.io.Serializable;
public class SingletonSerializable implements Serializable {
private static SingletonSerializable singletonInstance;
private SingletonSerializable() {}
public static SingletonSerializable getSingletonInstance() {
if (singletonInstance == null) {
synchronized (SingletonSerializable.class) {//Thread safety synchronized block
if (singletonInstance == null) { //double checked locking
singletonInstance = new SingletonSerializable();
}
}
}
return singletonInstance;
}
//prevent from serializable interface to create multiple instance
private Object readResolve() {
return getSingletonInstance();
}
}
| [
"zakariahossain143@gmail.com"
] | zakariahossain143@gmail.com |
6767a1e13f59a05e2f971c7d58263feb0acfb24d | 606bad9b622f1dbeadf3a4dcc6861667a3ee9f8b | /src/main/java/ua/in/hnatiuk/gameofthree/util/ResponseWrapper.java | f36ec545bcca27b3325fba832627d43988594cf5 | [] | no_license | yaroslav-hnatiuk/game_of_three | df376e1a0c2a63af29728c65f527e9aff0267be3 | 7411aea0678e4c3cfd0d2e441e260ec92ca09d1b | refs/heads/master | 2020-09-25T07:15:29.329808 | 2019-12-04T20:04:15 | 2019-12-04T20:04:15 | 225,947,608 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,134 | java | package ua.in.hnatiuk.gameofthree.util;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import java.util.Objects;
@Builder
@Getter
public class ResponseWrapper {
@JsonProperty("message")
private String message;
@JsonProperty("initial_value")
private long initialValue;
@JsonProperty("current_value")
private long currentValue;
@JsonProperty("winner")
private UserType winner;
@JsonIgnore
private int status;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ResponseWrapper that = (ResponseWrapper) o;
return initialValue == that.initialValue &&
currentValue == that.currentValue &&
status == that.status &&
message.equals(that.message) &&
winner == that.winner;
}
@Override
public int hashCode() {
return Objects.hash(message, initialValue, currentValue, winner, status);
}
}
| [
"yaroslavforjob@gmail.com"
] | yaroslavforjob@gmail.com |
a07e352325a43f9e11f6ea2712589d98be73616b | 29325d98b49f487c4d231717972cda18189775c6 | /app/src/main/java/com/silence/commonframe/utils/Divider.java | 5cd4c7aa8eebbf2bdcffb85953588c0d5a908df9 | [] | no_license | jim1451/hsh | 2033f488640ba75d6e99b116f86650f9058c71f6 | 046070326974b604b76f1f3dd2a494f228b2d011 | refs/heads/master | 2020-05-09T14:28:38.070716 | 2019-04-13T13:05:00 | 2019-04-13T13:05:00 | 181,195,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,846 | java | package com.silence.commonframe.utils;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.silence.commonframe.R;
public class Divider extends RecyclerView.ItemDecoration {
private Drawable mDividerDrawable;
public Divider(Context context) {
mDividerDrawable = context.getResources().getDrawable(R.mipmap.list_divider);
}
// 如果等于分割线的宽度或高度的话可以不用重写该方法
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1) {
outRect.set(0, 0, 0, 0);
} else {
outRect.set(0, 0, 0, mDividerDrawable.getIntrinsicHeight());
}
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
drawVertical(c, parent);
}
public void drawVertical(Canvas c, RecyclerView parent) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
View child;
RecyclerView.LayoutParams layoutParams;
int top;
int bottom;
int childCount = parent.getChildCount();
for (int i = 0; i < childCount - 1; i++) {
child = parent.getChildAt(i);
layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
top = child.getBottom() + layoutParams.bottomMargin;
bottom = top + mDividerDrawable.getIntrinsicHeight();
mDividerDrawable.setBounds(left, top, right, bottom);
mDividerDrawable.draw(c);
}
}
} | [
"122448024@qq.com"
] | 122448024@qq.com |
4a978b616f1a1b0fd916e637a3e22fec9b3fc412 | 3343050b340a8594d802598cddfd0d8709ccc45a | /src/share/classes/java/awt/GraphicsDevice.java | 819aa49989b16685908df5e14981cf878d764c4a | [
"Apache-2.0"
] | permissive | lcyanxi/jdk8 | be07ce687ca610c9e543bf3c1168be8228c1f2b3 | 4f4c2d72670a30dafaf9bb09b908d4da79119cf6 | refs/heads/master | 2022-05-25T18:11:28.236578 | 2022-05-03T15:28:01 | 2022-05-03T15:28:01 | 228,209,646 | 0 | 0 | Apache-2.0 | 2022-05-03T15:28:03 | 2019-12-15T15:49:24 | Java | UTF-8 | Java | false | false | 24,380 | java | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.image.ColorModel;
import sun.awt.AWTAccessor;
import sun.awt.AppContext;
import sun.awt.SunToolkit;
/**
* The <code>GraphicsDevice</code> class describes the graphics devices
* that might be available in a particular graphics environment. These
* include screen and printer devices. Note that there can be many screens
* and many printers in an instance of {@link GraphicsEnvironment}. Each
* graphics device has one or more {@link GraphicsConfiguration} objects
* associated with it. These objects specify the different configurations
* in which the <code>GraphicsDevice</code> can be used.
* <p>
* In a multi-screen environment, the <code>GraphicsConfiguration</code>
* objects can be used to render components on multiple screens. The
* following code sample demonstrates how to create a <code>JFrame</code>
* object for each <code>GraphicsConfiguration</code> on each screen
* device in the <code>GraphicsEnvironment</code>:
* <pre>{@code
* GraphicsEnvironment ge = GraphicsEnvironment.
* getLocalGraphicsEnvironment();
* GraphicsDevice[] gs = ge.getScreenDevices();
* for (int j = 0; j < gs.length; j++) {
* GraphicsDevice gd = gs[j];
* GraphicsConfiguration[] gc =
* gd.getConfigurations();
* for (int i=0; i < gc.length; i++) {
* JFrame f = new
* JFrame(gs[j].getDefaultConfiguration());
* Canvas c = new Canvas(gc[i]);
* Rectangle gcBounds = gc[i].getBounds();
* int xoffs = gcBounds.x;
* int yoffs = gcBounds.y;
* f.getContentPane().add(c);
* f.setLocation((i*50)+xoffs, (i*60)+yoffs);
* f.show();
* }
* }
* }</pre>
* <p>
* For more information on full-screen exclusive mode API, see the
* <a href="http://docs.oracle.com/javase/tutorial/extra/fullscreen/index.html">
* Full-Screen Exclusive Mode API Tutorial</a>.
*
* @see GraphicsEnvironment
* @see GraphicsConfiguration
*/
public abstract class GraphicsDevice {
private Window fullScreenWindow;
private AppContext fullScreenAppContext; // tracks which AppContext
// created the FS window
// this lock is used for making synchronous changes to the AppContext's
// current full screen window
private final Object fsAppContextLock = new Object();
private Rectangle windowedModeBounds;
/**
* This is an abstract class that cannot be instantiated directly.
* Instances must be obtained from a suitable factory or query method.
* @see GraphicsEnvironment#getScreenDevices
* @see GraphicsEnvironment#getDefaultScreenDevice
* @see GraphicsConfiguration#getDevice
*/
protected GraphicsDevice() {
}
/**
* Device is a raster screen.
*/
public final static int TYPE_RASTER_SCREEN = 0;
/**
* Device is a printer.
*/
public final static int TYPE_PRINTER = 1;
/**
* Device is an image buffer. This buffer can reside in device
* or system memory but it is not physically viewable by the user.
*/
public final static int TYPE_IMAGE_BUFFER = 2;
/**
* Kinds of translucency supported by the underlying system.
*
* @see #isWindowTranslucencySupported
*
* @since 1.7
*/
public static enum WindowTranslucency {
/**
* Represents support in the underlying system for windows each pixel
* of which is guaranteed to be either completely opaque, with
* an alpha value of 1.0, or completely transparent, with an alpha
* value of 0.0.
*/
PERPIXEL_TRANSPARENT,
/**
* Represents support in the underlying system for windows all of
* the pixels of which have the same alpha value between or including
* 0.0 and 1.0.
*/
TRANSLUCENT,
/**
* Represents support in the underlying system for windows that
* contain or might contain pixels with arbitrary alpha values
* between and including 0.0 and 1.0.
*/
PERPIXEL_TRANSLUCENT;
}
/**
* Returns the type of this <code>GraphicsDevice</code>.
* @return the type of this <code>GraphicsDevice</code>, which can
* either be TYPE_RASTER_SCREEN, TYPE_PRINTER or TYPE_IMAGE_BUFFER.
* @see #TYPE_RASTER_SCREEN
* @see #TYPE_PRINTER
* @see #TYPE_IMAGE_BUFFER
*/
public abstract int getType();
/**
* Returns the identification string associated with this
* <code>GraphicsDevice</code>.
* <p>
* A particular program might use more than one
* <code>GraphicsDevice</code> in a <code>GraphicsEnvironment</code>.
* This method returns a <code>String</code> identifying a
* particular <code>GraphicsDevice</code> in the local
* <code>GraphicsEnvironment</code>. Although there is
* no public method to set this <code>String</code>, a programmer can
* use the <code>String</code> for debugging purposes. Vendors of
* the Java™ Runtime Environment can
* format the return value of the <code>String</code>. To determine
* how to interpret the value of the <code>String</code>, contact the
* vendor of your Java Runtime. To find out who the vendor is, from
* your program, call the
* {@link System#getProperty(String) getProperty} method of the
* System class with "java.vendor".
* @return a <code>String</code> that is the identification
* of this <code>GraphicsDevice</code>.
*/
public abstract String getIDstring();
/**
* Returns all of the <code>GraphicsConfiguration</code>
* objects associated with this <code>GraphicsDevice</code>.
* @return an array of <code>GraphicsConfiguration</code>
* objects that are associated with this
* <code>GraphicsDevice</code>.
*/
public abstract GraphicsConfiguration[] getConfigurations();
/**
* Returns the default <code>GraphicsConfiguration</code>
* associated with this <code>GraphicsDevice</code>.
* @return the default <code>GraphicsConfiguration</code>
* of this <code>GraphicsDevice</code>.
*/
public abstract GraphicsConfiguration getDefaultConfiguration();
/**
* Returns the "best" configuration possible that passes the
* criteria defined in the {@link GraphicsConfigTemplate}.
* @param gct the <code>GraphicsConfigTemplate</code> object
* used to obtain a valid <code>GraphicsConfiguration</code>
* @return a <code>GraphicsConfiguration</code> that passes
* the criteria defined in the specified
* <code>GraphicsConfigTemplate</code>.
* @see GraphicsConfigTemplate
*/
public GraphicsConfiguration
getBestConfiguration(GraphicsConfigTemplate gct) {
GraphicsConfiguration[] configs = getConfigurations();
return gct.getBestConfiguration(configs);
}
/**
* Returns <code>true</code> if this <code>GraphicsDevice</code>
* supports full-screen exclusive mode.
* If a SecurityManager is installed, its
* <code>checkPermission</code> method will be called
* with <code>AWTPermission("fullScreenExclusive")</code>.
* <code>isFullScreenSupported</code> returns true only if
* that permission is granted.
* @return whether full-screen exclusive mode is available for
* this graphics device
* @see java.awt.AWTPermission
* @since 1.4
*/
public boolean isFullScreenSupported() {
return false;
}
/**
* Enter full-screen mode, or return to windowed mode. The entered
* full-screen mode may be either exclusive or simulated. Exclusive
* mode is only available if <code>isFullScreenSupported</code>
* returns <code>true</code>.
* <p>
* Exclusive mode implies:
* <ul>
* <li>Windows cannot overlap the full-screen window. All other application
* windows will always appear beneath the full-screen window in the Z-order.
* <li>There can be only one full-screen window on a device at any time,
* so calling this method while there is an existing full-screen Window
* will cause the existing full-screen window to
* return to windowed mode.
* <li>Input method windows are disabled. It is advisable to call
* <code>Component.enableInputMethods(false)</code> to make a component
* a non-client of the input method framework.
* </ul>
* <p>
* The simulated full-screen mode places and resizes the window to the maximum
* possible visible area of the screen. However, the native windowing system
* may modify the requested geometry-related data, so that the {@code Window} object
* is placed and sized in a way that corresponds closely to the desktop settings.
* <p>
* When entering full-screen mode, if the window to be used as a
* full-screen window is not visible, this method will make it visible.
* It will remain visible when returning to windowed mode.
* <p>
* When entering full-screen mode, all the translucency effects are reset for
* the window. Its shape is set to {@code null}, the opacity value is set to
* 1.0f, and the background color alpha is set to 255 (completely opaque).
* These values are not restored when returning to windowed mode.
* <p>
* It is unspecified and platform-dependent how decorated windows operate
* in full-screen mode. For this reason, it is recommended to turn off
* the decorations in a {@code Frame} or {@code Dialog} object by using the
* {@code setUndecorated} method.
* <p>
* When returning to windowed mode from an exclusive full-screen window,
* any display changes made by calling {@code setDisplayMode} are
* automatically restored to their original state.
*
* @param w a window to use as the full-screen window; {@code null}
* if returning to windowed mode. Some platforms expect the
* fullscreen window to be a top-level component (i.e., a {@code Frame});
* therefore it is preferable to use a {@code Frame} here rather than a
* {@code Window}.
*
* @see #isFullScreenSupported
* @see #getFullScreenWindow
* @see #setDisplayMode
* @see Component#enableInputMethods
* @see Component#setVisible
* @see Frame#setUndecorated
* @see Dialog#setUndecorated
*
* @since 1.4
*/
public void setFullScreenWindow(Window w) {
if (w != null) {
if (w.getShape() != null) {
w.setShape(null);
}
if (w.getOpacity() < 1.0f) {
w.setOpacity(1.0f);
}
if (!w.isOpaque()) {
Color bgColor = w.getBackground();
bgColor = new Color(bgColor.getRed(), bgColor.getGreen(),
bgColor.getBlue(), 255);
w.setBackground(bgColor);
}
// Check if this window is in fullscreen mode on another device.
final GraphicsConfiguration gc = w.getGraphicsConfiguration();
if (gc != null && gc.getDevice() != this
&& gc.getDevice().getFullScreenWindow() == w) {
gc.getDevice().setFullScreenWindow(null);
}
}
if (fullScreenWindow != null && windowedModeBounds != null) {
// if the window went into fs mode before it was realized it may
// have (0,0) dimensions
if (windowedModeBounds.width == 0) windowedModeBounds.width = 1;
if (windowedModeBounds.height == 0) windowedModeBounds.height = 1;
fullScreenWindow.setBounds(windowedModeBounds);
}
// Set the full screen window
synchronized (fsAppContextLock) {
// Associate fullscreen window with current AppContext
if (w == null) {
fullScreenAppContext = null;
} else {
fullScreenAppContext = AppContext.getAppContext();
}
fullScreenWindow = w;
}
if (fullScreenWindow != null) {
windowedModeBounds = fullScreenWindow.getBounds();
// Note that we use the graphics configuration of the device,
// not the window's, because we're setting the fs window for
// this device.
final GraphicsConfiguration gc = getDefaultConfiguration();
final Rectangle screenBounds = gc.getBounds();
if (SunToolkit.isDispatchThreadForAppContext(fullScreenWindow)) {
// Update graphics configuration here directly and do not wait
// asynchronous notification from the peer. Note that
// setBounds() will reset a GC, if it was set incorrectly.
fullScreenWindow.setGraphicsConfiguration(gc);
}
fullScreenWindow.setBounds(screenBounds.x, screenBounds.y,
screenBounds.width, screenBounds.height);
fullScreenWindow.setVisible(true);
fullScreenWindow.toFront();
}
}
/**
* Returns the <code>Window</code> object representing the
* full-screen window if the device is in full-screen mode.
*
* @return the full-screen window, or <code>null</code> if the device is
* not in full-screen mode.
* @see #setFullScreenWindow(Window)
* @since 1.4
*/
public Window getFullScreenWindow() {
Window returnWindow = null;
synchronized (fsAppContextLock) {
// Only return a handle to the current fs window if we are in the
// same AppContext that set the fs window
if (fullScreenAppContext == AppContext.getAppContext()) {
returnWindow = fullScreenWindow;
}
}
return returnWindow;
}
/**
* Returns <code>true</code> if this <code>GraphicsDevice</code>
* supports low-level display changes.
* On some platforms low-level display changes may only be allowed in
* full-screen exclusive mode (i.e., if {@link #isFullScreenSupported()}
* returns {@code true} and the application has already entered
* full-screen mode using {@link #setFullScreenWindow}).
* @return whether low-level display changes are supported for this
* graphics device.
* @see #isFullScreenSupported
* @see #setDisplayMode
* @see #setFullScreenWindow
* @since 1.4
*/
public boolean isDisplayChangeSupported() {
return false;
}
/**
* Sets the display mode of this graphics device. This is only allowed
* if {@link #isDisplayChangeSupported()} returns {@code true} and may
* require first entering full-screen exclusive mode using
* {@link #setFullScreenWindow} providing that full-screen exclusive mode is
* supported (i.e., {@link #isFullScreenSupported()} returns
* {@code true}).
* <p>
*
* The display mode must be one of the display modes returned by
* {@link #getDisplayModes()}, with one exception: passing a display mode
* with {@link DisplayMode#REFRESH_RATE_UNKNOWN} refresh rate will result in
* selecting a display mode from the list of available display modes with
* matching width, height and bit depth.
* However, passing a display mode with {@link DisplayMode#BIT_DEPTH_MULTI}
* for bit depth is only allowed if such mode exists in the list returned by
* {@link #getDisplayModes()}.
* <p>
* Example code:
* <pre><code>
* Frame frame;
* DisplayMode newDisplayMode;
* GraphicsDevice gd;
* // create a Frame, select desired DisplayMode from the list of modes
* // returned by gd.getDisplayModes() ...
*
* if (gd.isFullScreenSupported()) {
* gd.setFullScreenWindow(frame);
* } else {
* // proceed in non-full-screen mode
* frame.setSize(...);
* frame.setLocation(...);
* frame.setVisible(true);
* }
*
* if (gd.isDisplayChangeSupported()) {
* gd.setDisplayMode(newDisplayMode);
* }
* </code></pre>
*
* @param dm The new display mode of this graphics device.
* @exception IllegalArgumentException if the <code>DisplayMode</code>
* supplied is <code>null</code>, or is not available in the array returned
* by <code>getDisplayModes</code>
* @exception UnsupportedOperationException if
* <code>isDisplayChangeSupported</code> returns <code>false</code>
* @see #getDisplayMode
* @see #getDisplayModes
* @see #isDisplayChangeSupported
* @since 1.4
*/
public void setDisplayMode(DisplayMode dm) {
throw new UnsupportedOperationException("Cannot change display mode");
}
/**
* Returns the current display mode of this
* <code>GraphicsDevice</code>.
* The returned display mode is allowed to have a refresh rate
* {@link DisplayMode#REFRESH_RATE_UNKNOWN} if it is indeterminate.
* Likewise, the returned display mode is allowed to have a bit depth
* {@link DisplayMode#BIT_DEPTH_MULTI} if it is indeterminate or if multiple
* bit depths are supported.
* @return the current display mode of this graphics device.
* @see #setDisplayMode(DisplayMode)
* @since 1.4
*/
public DisplayMode getDisplayMode() {
GraphicsConfiguration gc = getDefaultConfiguration();
Rectangle r = gc.getBounds();
ColorModel cm = gc.getColorModel();
return new DisplayMode(r.width, r.height, cm.getPixelSize(), 0);
}
/**
* Returns all display modes available for this
* <code>GraphicsDevice</code>.
* The returned display modes are allowed to have a refresh rate
* {@link DisplayMode#REFRESH_RATE_UNKNOWN} if it is indeterminate.
* Likewise, the returned display modes are allowed to have a bit depth
* {@link DisplayMode#BIT_DEPTH_MULTI} if it is indeterminate or if multiple
* bit depths are supported.
* @return all of the display modes available for this graphics device.
* @since 1.4
*/
public DisplayMode[] getDisplayModes() {
return new DisplayMode[] { getDisplayMode() };
}
/**
* This method returns the number of bytes available in
* accelerated memory on this device.
* Some images are created or cached
* in accelerated memory on a first-come,
* first-served basis. On some operating systems,
* this memory is a finite resource. Calling this method
* and scheduling the creation and flushing of images carefully may
* enable applications to make the most efficient use of
* that finite resource.
* <br>
* Note that the number returned is a snapshot of how much
* memory is available; some images may still have problems
* being allocated into that memory. For example, depending
* on operating system, driver, memory configuration, and
* thread situations, the full extent of the size reported
* may not be available for a given image. There are further
* inquiry methods on the {@link ImageCapabilities} object
* associated with a VolatileImage that can be used to determine
* whether a particular VolatileImage has been created in accelerated
* memory.
* @return number of bytes available in accelerated memory.
* A negative return value indicates that the amount of accelerated memory
* on this GraphicsDevice is indeterminate.
* @see java.awt.image.VolatileImage#flush
* @see ImageCapabilities#isAccelerated
* @since 1.4
*/
public int getAvailableAcceleratedMemory() {
return -1;
}
/**
* Returns whether the given level of translucency is supported by
* this graphics device.
*
* @param translucencyKind a kind of translucency support
* @return whether the given translucency kind is supported
*
* @since 1.7
*/
public boolean isWindowTranslucencySupported(WindowTranslucency translucencyKind) {
switch (translucencyKind) {
case PERPIXEL_TRANSPARENT:
return isWindowShapingSupported();
case TRANSLUCENT:
return isWindowOpacitySupported();
case PERPIXEL_TRANSLUCENT:
return isWindowPerpixelTranslucencySupported();
}
return false;
}
/**
* Returns whether the windowing system supports changing the shape
* of top-level windows.
* Note that this method may sometimes return true, but the native
* windowing system may still not support the concept of
* shaping (due to the bugs in the windowing system).
*/
static boolean isWindowShapingSupported() {
Toolkit curToolkit = Toolkit.getDefaultToolkit();
if (!(curToolkit instanceof SunToolkit)) {
return false;
}
return ((SunToolkit)curToolkit).isWindowShapingSupported();
}
/**
* Returns whether the windowing system supports changing the opacity
* value of top-level windows.
* Note that this method may sometimes return true, but the native
* windowing system may still not support the concept of
* translucency (due to the bugs in the windowing system).
*/
static boolean isWindowOpacitySupported() {
Toolkit curToolkit = Toolkit.getDefaultToolkit();
if (!(curToolkit instanceof SunToolkit)) {
return false;
}
return ((SunToolkit)curToolkit).isWindowOpacitySupported();
}
boolean isWindowPerpixelTranslucencySupported() {
/*
* Per-pixel alpha is supported if all the conditions are TRUE:
* 1. The toolkit is a sort of SunToolkit
* 2. The toolkit supports translucency in general
* (isWindowTranslucencySupported())
* 3. There's at least one translucency-capable
* GraphicsConfiguration
*/
Toolkit curToolkit = Toolkit.getDefaultToolkit();
if (!(curToolkit instanceof SunToolkit)) {
return false;
}
if (!((SunToolkit)curToolkit).isWindowTranslucencySupported()) {
return false;
}
// TODO: cache translucency capable GC
return getTranslucencyCapableGC() != null;
}
GraphicsConfiguration getTranslucencyCapableGC() {
// If the default GC supports translucency return true.
// It is important to optimize the verification this way,
// see CR 6661196 for more details.
GraphicsConfiguration defaultGC = getDefaultConfiguration();
if (defaultGC.isTranslucencyCapable()) {
return defaultGC;
}
// ... otherwise iterate through all the GCs.
GraphicsConfiguration[] configs = getConfigurations();
for (int j = 0; j < configs.length; j++) {
if (configs[j].isTranslucencyCapable()) {
return configs[j];
}
}
return null;
}
}
| [
"2757710657@qq.com"
] | 2757710657@qq.com |
670ccb67d29eda4c0bdb872af55148bfd0ec38b6 | 11d9c8851c329e88775ab42a8a5b2a5b0e221a7c | /LaponhcetWeb/src/com/laponhcet/dao/EventParticipantDAO.java | e3cfa802183441ece2db7550d0968df25b60b33a | [] | no_license | rgchan07/laponhcet | f6ebd24d2e353934edc78f46523b33714976b11b | 90e774b2a366492cf2d4f4f6138a0adfcfa896d6 | refs/heads/master | 2020-03-07T18:12:51.163115 | 2018-05-21T03:10:11 | 2018-05-21T03:10:11 | 115,425,237 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,112 | java | package com.laponhcet.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.laponhcet.dto.EventParticipantDTO;
import com.mytechnopal.ActionResponse;
import com.mytechnopal.base.DAOBase;
import com.mytechnopal.base.DTOBase;
public class EventParticipantDAO extends DAOBase {
private static final long serialVersionUID = 1L;
private String qryEventParticipantAdd = "EVENT_PARTICIPANT_ADD";
private String qryEventParticipantDelete = "EVENT_PARTICIPANT_DELETE";
private String qryEventParticipantByUserCode = "EVENT_PARTICIPANT_BY_USER_CODE";
private String qryEventParticipantList = "EVENT_PARTICIPANT_LIST";
@Override
public void executeAdd(DTOBase obj) {
EventParticipantDTO eventParticipant = (EventParticipantDTO) obj;
Connection conn = daoConnectorUtil.getConnection();
List<PreparedStatement> prepStmntList = new ArrayList<PreparedStatement>();
eventParticipant.setBaseDataOnInsert();
add(conn, prepStmntList, eventParticipant);
result.put(ActionResponse.SESSION_ACTION_RESPONSE, executeIUD(conn, prepStmntList,true));
}
public void add(Connection conn, List<PreparedStatement> prepStmntList, Object obj) {
EventParticipantDTO eventParticipant = (EventParticipantDTO) obj;
PreparedStatement prepStmnt = null;
try {
prepStmnt = conn.prepareStatement(getQueryStatement(qryEventParticipantAdd));
prepStmnt.setString(1, eventParticipant.getEventDTO().getCode());
prepStmnt.setString(2, eventParticipant.getUserDTO().getCode());
prepStmnt.setString(3, eventParticipant.getRemarks());
prepStmnt.setString(4, eventParticipant.getAddedBy());
prepStmnt.setTimestamp(5, eventParticipant.getAddedTimestamp());
prepStmnt.setString(6, eventParticipant.getUpdatedBy());
prepStmnt.setTimestamp(7, eventParticipant.getUpdatedTimestamp());
} catch (SQLException e) {
e.printStackTrace();
}
prepStmntList.add(prepStmnt);
}
@Override
public void executeAddList(List<DTOBase> arg0) {
// TODO Auto-generated method stub
}
public EventParticipantDTO getEventParticipantByUserCode(String userCode){
return (EventParticipantDTO) getDTO(qryEventParticipantByUserCode, userCode);
}
@Override
public void executeDelete(DTOBase obj) {
EventParticipantDTO eventParticipant = (EventParticipantDTO) obj;
Connection conn = daoConnectorUtil.getConnection();
List<PreparedStatement> prepStmntList = new ArrayList<PreparedStatement>();
delete(conn, prepStmntList, eventParticipant);
result.put(ActionResponse.SESSION_ACTION_RESPONSE, executeIUD(conn, prepStmntList, true));
}
public void delete(Connection conn, List<PreparedStatement> prepStmntList, Object obj) {
EventParticipantDTO eventParticipant = (EventParticipantDTO) obj;
PreparedStatement prepStmnt = null;
try {
prepStmnt = conn.prepareStatement(getQueryStatement(qryEventParticipantDelete));
prepStmnt.setInt(1, eventParticipant.getId());
} catch (SQLException e) {
e.printStackTrace();
}
prepStmntList.add(prepStmnt);
}
@Override
public void executeDeleteList(List<DTOBase> arg0) {
// TODO Auto-generated method stub
}
@Override
public void executeUpdateList(List<DTOBase> arg0) {
// TODO Auto-generated method stub
}
public List<DTOBase> getEventParticipantList() {
return getDTOList(qryEventParticipantList);
}
@Override
protected DTOBase rsToObj(ResultSet resultSet) {
EventParticipantDTO eventParticipant = new EventParticipantDTO();
eventParticipant.setId((Integer) getDBVal(resultSet, "id"));
eventParticipant.getEventDTO().setCode((String) getDBVal(resultSet, "event_code"));
eventParticipant.getUserDTO().setCode((String) getDBVal(resultSet, "user_code"));
eventParticipant.setRemarks((String) getDBVal(resultSet, "remarks"));
return eventParticipant;
}
@Override
public void executeUpdate(DTOBase arg0) {
// TODO Auto-generated method stub
}
}
| [
"RichardChan@ISD-PF0ZH50A.local"
] | RichardChan@ISD-PF0ZH50A.local |
7d04c7cb0313db41329fb8a34d840b82008f4553 | 1af5de52e596f736c70a8d2b505fcbf406e0d1e4 | /adapter/src/main/java/com/adaptris/core/http/ContentTypeProviderImpl.java | 5b092898e67ff39107e7884b6c26a38f465f6d8d | [
"Apache-2.0"
] | permissive | williambl/interlok | 462970f97b626b6f05d69ae30a43e42d6770dd24 | 3371e63ede75a53878244d8e44ecc00f36545e74 | refs/heads/master | 2020-03-28T06:17:23.056266 | 2018-08-13T13:36:02 | 2018-08-13T13:36:02 | 147,825,107 | 0 | 0 | Apache-2.0 | 2018-09-07T13:10:38 | 2018-09-07T13:10:38 | null | UTF-8 | Java | false | false | 1,498 | java | /*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core.http;
import static org.apache.commons.lang.StringUtils.isBlank;
import javax.mail.internet.ContentType;
import javax.mail.internet.ParseException;
public abstract class ContentTypeProviderImpl implements ContentTypeProvider {
protected String build(String mimeType, String charset) {
StringBuilder buf = new StringBuilder();
buf.append(mimeType);
if (!isBlank(charset) && !hasCharset(mimeType)) {
buf.append("; charset=");
buf.append(charset);
}
return buf.toString();
}
private boolean hasCharset(String mimeType) {
boolean result = false;
try {
ContentType ct = new ContentType(mimeType);
String charset = ct.getParameter("charset");
result = !isBlank(charset);
}
catch (ParseException e) {
// couldn't parse, hasn't got a charset.
result = false;
}
return result;
}
}
| [
"lewin.chan@adaptris.com"
] | lewin.chan@adaptris.com |
6a4408523e622af5c7299ddfc924967a124ee047 | d364c047a1849cc28cfb293ff06ec6bc9171b8e4 | /app/src/main/java/com/bitech/androidsample/module/main/presenter/LoginPresener.java | 857a272cb0b5e04e77659efa219aab94b6ff7375 | [] | no_license | yinzubo/AndroidSample | c77f0f9398155195b6cfb521f8aafe6598ff441a | f611f102cec849ef3770dda156ded6f5f8d8ba76 | refs/heads/master | 2021-01-21T04:55:28.551046 | 2016-07-07T07:26:17 | 2016-07-07T07:26:17 | 55,463,635 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,284 | java | package com.bitech.androidsample.module.main.presenter;
import com.bitech.androidsample.ActivityScope;
import com.bitech.androidsample.base.BasePresenter;
import com.bitech.androidsample.bean.User;
import com.bitech.androidsample.callback.RequestCallback;
import com.bitech.androidsample.http.service.Service;
import com.bitech.androidsample.module.main.model.LoginModel;
import com.bitech.androidsample.module.main.view.ILoginView;
import javax.inject.Inject;
/**
* <p>实现类
* 保存View层的引用,当数据发生改变时,通过引用改变视图
* 保存Model层的引用,当是视图改变时,通过引用改变数据
* <p/>
* 改变视图时,就在IView接口中定义方法
* <p/>
* 实现MVP设计模式
* </p>
* Created on 2016/4/6 16:36.
*
* @author Lucy
*/
@ActivityScope
public class LoginPresener extends BasePresenter<ILoginView, User> {
private LoginModel loginInterceptor;
private Service apiService;//http访问接口
@Inject
public LoginPresener(Service apiService) {
this.apiService=apiService;
loginInterceptor=new LoginModel(apiService);
}
//登录
public void login(String name, String password) {
loginInterceptor.login(name, password, new RequestCallback<User>());
}
}
| [
"yinzb@bitech.cn"
] | yinzb@bitech.cn |
7849dd9e5531674bc565f54f39d71ff2ebb99f1c | 56298db0bb6ca935ef6ee1c09546ddbdb05d6887 | /OrangeSchool/src/main/java/orangeschool/controller/ResultController.java | 4d9927bbc6bf31b7682a238bf1c64879e41300e4 | [] | no_license | BangCao01/Orange-School-Back-End | dbaeff27ff1d072993e4161c3ad3fe04795a5108 | 16ac787d181cdd22724cf0fe83656eb5890368e0 | refs/heads/master | 2022-11-05T08:04:30.241123 | 2020-06-25T16:21:12 | 2020-06-25T16:21:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,005 | java | package orangeschool.controller;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import orangeschool.WebUtil;
import orangeschool.controller.BaseController.ActionMenuCode;
import orangeschool.controller.BaseController.MenuCode;
import orangeschool.form.ResultForm;
import orangeschool.model.Result;
import orangeschool.service.ResultService;
@Controller // This means that this class is a Controller
@RequestMapping(path = "/result") // This
public class ResultController extends BaseController {
@Autowired
private ResultService resultService;
@RequestMapping(value = { "/index" }, method = RequestMethod.GET)
public String showIndexPage(
Model model,
Principal _principal
) {
if (this.checkForbidden(_principal, MenuCode.Result)) {
return "redirect:/home/404";
}
this.setSelectedActionMenu(model, ActionMenuCode.List);
this.setMessageAt(model, MessageCode.Index);
model.addAttribute("results", resultService.findAll());
this.setSelectedMenu(model, MenuCode.Result);
this.setAccessCode(model, _principal);
return "result/index";
}
@RequestMapping(value = { "/index/{customerid}" }, method = RequestMethod.GET)
public String showResultOfCustomerPage(
@PathVariable("customerid") int customerid,
Model model,
Principal _principal
) {
if (this.checkForbidden(_principal, MenuCode.Result)) {
return "redirect:/home/404";
}
this.setSelectedActionMenu(model, ActionMenuCode.List);
this.setMessageAt(model, MessageCode.Index);
model.addAttribute("results", resultService.findByCustomerID(customerid));
this.setSelectedMenu(model, MenuCode.Result);
this.setAccessCode(model, _principal);
return "result/index";
}
@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
public String showDetailPage(
@PathVariable("id") int id,
Model model,
Principal _principal) {
if (this.checkForbidden(_principal, MenuCode.Transaction)) {
return "redirect:/home/404";
}
this.setMessageAt(model, MessageCode.Detail);
model.addAttribute("result", resultService.findByResultID(id));
this.setSelectedMenu(model, MenuCode.Transaction);
this.setAccessCode(model, _principal);
return "result/detail";
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String showDeletePage(@PathVariable("id") int id, Model model,Principal _principal) {
if (this.checkForbidden(_principal, MenuCode.Result)) {
return "redirect:/home/404";
}
try {
resultService.deleteById(id);
} catch (Exception ex) {
}
this.setMessageAt(model, MessageCode.Delete);
return "redirect:/result/index";
}
}
| [
"admin@admins-MacBook.local"
] | admin@admins-MacBook.local |
90488f93688fded0fcd86f62c474d39488f862d1 | 313e133701593fb30ce8804b21f0acfb9c2885a2 | /Android/JCertif-network/src/com/jcertif/reseaujcertif/persistances/Parser.java | d0fb86aed33b4a4b620fc1015805c11a5cfa1163 | [] | no_license | JCERTIFLab/jcertif-network | 4188dd9ff61c51f8870ece2fefdfa4ccdc2031c3 | 027e439c7904688b8143055f71703342ca465708 | refs/heads/master | 2021-01-01T16:00:25.429586 | 2013-07-23T10:34:31 | 2013-07-23T10:34:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 103 | java | package com.jcertif.reseaujcertif.persistances;
public interface Parser {
public Route parse();
}
| [
"firas.gabsi@gmail.com"
] | firas.gabsi@gmail.com |
5b9761a0d39c2c17f4561f24ea28e5f96c634499 | 83d3a015d2b1a4165283512c697b4974b087221a | /sspserver/src/main/java/com/vaolan/sspserver/dao/imp/AdMaterialDaoImpl.java | aedd0953197c46a12303d7a63556b5d775bfa083 | [] | no_license | tsienlu/window_system | 9fe46a78d182496be7ca50248b3de463ee62580b | 84b2fb5cb9ca9e3d0d8d91c12dd343a8d2e0522c | refs/heads/master | 2021-06-09T13:26:07.599490 | 2015-11-17T06:33:50 | 2015-11-17T06:33:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,347 | java | package com.vaolan.sspserver.dao.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.hidata.framework.db.DBManager;
import com.vaolan.sspserver.dao.AdMaterialDao;
import com.vaolan.sspserver.model.AdExtLink;
import com.vaolan.sspserver.model.AdMaterial;
@Repository
public class AdMaterialDaoImpl implements AdMaterialDao {
@Autowired
private DBManager db;
/*
* (non-Javadoc)
*
* @see
* com.vaolan.adtarget.dao.impl.AdMaterialDao#getMaterialByAdId(java.lang
* .String)
*/
@Override
public List<AdMaterial> getMaterialByAdId(String adId) {
String sql = "select m.ad_m_id,m.m_type,m.material_name,m.link_url,m.target_url,l.check_status, m.material_size_value "
+ "from ad_m_link l,ad_material m where l.ad_m_id=m.ad_m_id and l.ad_id=?";
Object[] args = new Object[] { adId };
return db.queryForListObject(sql, args, AdMaterial.class);
}
@Override
public AdExtLink getAdExtLinkByAdId(String adId) {
String sql = "select a.id,a.ad_instance_id,a.throw_url,a.pic_size,a.width,a.height,a.sts,a.sts_date,a.remark "
+ " from ad_ext_link a where a.ad_instance_id=?";
Object[] args = new Object[] { adId };
return db.queryForObject(sql, args, AdExtLink.class);
}
}
| [
"shan3275@gmail.com"
] | shan3275@gmail.com |
e9ca1b6d30c276433604598edfef992b1e175992 | 23b85089d5233eef1da9b0d6ebc3e10e16d24a95 | /src/main/java/com/mycompany/mavenproject1/domain/User.java | db5d3606d354d2c5b741f62dbc089d25adc4875f | [] | no_license | karola15134/NAI | 4deefed7a09a295998e529c405cbcb90a03fd597 | 97fb6b00fda636042759a34e77960abac12aa0d5 | refs/heads/master | 2021-09-04T05:39:30.145065 | 2018-01-16T12:04:25 | 2018-01-16T12:04:25 | 106,269,417 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,640 | java | /*
* 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 com.mycompany.mavenproject1.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO )
private Integer id;
@NotNull
@Size(min=2, max=30)
private String name;
@Size(min=2, max=30)
private String email;
@OneToMany(mappedBy="user" , cascade = CascadeType.ALL)
private Set<Item> items = new HashSet<>();
public User(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<Item> getItems() {
return items;
}
public void setItems(Set<Item> items) {
this.items = items;
}
public void setItem(Item item){
this.items.add(item);
}
} | [
"karolina.sz1993@gmail.com"
] | karolina.sz1993@gmail.com |
503ad21d1164c4f1ca395a1ba562dd9baeef7277 | 19490fcc6f396eeb35a9234da31e7b615abf6d04 | /JDownloader/src/jd/controlling/downloadcontroller/FileIsLockedException.java | e98298f302174262224efc8f882b4fc8a41da8db | [] | no_license | amicom/my-project | ef72026bb91694e74bc2dafd209a1efea9deb285 | 951c67622713fd89448ffe6e0983fe3f934a7faa | refs/heads/master | 2021-01-02T09:15:45.828528 | 2015-09-06T15:57:01 | 2015-09-06T15:57:01 | 41,953,961 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 453 | java | package jd.controlling.downloadcontroller;
public class FileIsLockedException extends Exception {
private Object lockHolder;
public Object getLockHolder() {
return lockHolder;
}
public void setLockHolder(Object lockHolder) {
this.lockHolder = lockHolder;
}
public FileIsLockedException(Object currentHolder) {
super("File is locked by " + currentHolder);
lockHolder = currentHolder;
}
}
| [
"amicom.pro@gmail.com"
] | amicom.pro@gmail.com |
97088fc01a8514feb5ae50a42bbe57b38db53d41 | 21dcce40da68192ae4f5842599740e157f78d200 | /src/test/java/CloneClass.java | 44c7bf86f4fed0ff0681ac1a85d931697e842b66 | [] | no_license | jancal/jan2048 | 98727c418c68dece612c8b5d7add7f1d69632018 | e53a9050e0862b38026316a165a6fbfa79182f25 | refs/heads/master | 2021-01-23T06:26:31.268875 | 2017-06-01T06:32:46 | 2017-06-01T06:32:46 | 93,023,868 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 470 | java | /**
* CloneClass
*
* @author Jancal
* @date 2017/1/19
*/
class CloneClass implements Cloneable {
public int aInt;
public Object clone() {
CloneClass o = null;
try {
o = (CloneClass) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
public static void main(String[] args) {
CloneClass a = new CloneClass();
a.clone();
}
}
| [
"923273363@qq.com"
] | 923273363@qq.com |
30831a5159554c94d1a95c694bcf11adf33c0d88 | 944169ee8a0016af1bee180441fb5cd4129418e1 | /src/main/java/codigomorse/spring/Controller.java | 899adb158953f5d3b51f881aa6c559850d58735e | [] | no_license | patriciasouzass/modulo6-spring02-pratica2 | 04b0a12c4b6a391408602cbf01a89ae5ba42ed23 | 42594654d7f505ed33f817092c62ba7e970c0af7 | refs/heads/master | 2023-07-15T12:59:38.499277 | 2021-09-01T21:49:12 | 2021-09-01T21:49:12 | 402,211,826 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 419 | java | package codigomorse.spring;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@GetMapping("/codigo")
public String codigoMorse(@RequestParam String codigo){
String normal = codigoMorse(codigo);
return normal;
}
}
| [
"patricia.asouza@mercadolivre.com"
] | patricia.asouza@mercadolivre.com |
fc0ffcc182fd3602bd377aeb52c7dab05f50fbad | 1ceaea8ab23830225296c51ff34ebbc025c16ad9 | /Tugas 11 - Kelas Abstrak/Kalkulator/Calculator.java | 1a33086d968815e5afc2886d3f6d48b78fbf1f66 | [] | no_license | ahmad-mukhlish/ProLan-11 | f2066c78a0f07069b54925c94cb74f125cc779a1 | dd652b1e2ee3cefc5ef5bf9985295cce75f7514c | refs/heads/master | 2020-04-04T09:19:51.366408 | 2017-07-22T02:30:16 | 2017-07-22T02:30:16 | 83,439,743 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 641 | java |
public abstract class Calculator {
protected abstract double hasilTambah(double x, double y) ;
protected abstract double hasilKurang(double x, double y) ;
protected abstract double hasilKali(double x, double y) ;
protected abstract double hasilBagi(double x, double y) ;
protected boolean hasilLebihKecilDari(double x, double y) {return true ;}
protected boolean hasilLebihBesarDari(double x, double y) {return true ;}
protected boolean hasilLebihKecilSamaDenganDari(double x, double y) {return true ;}
protected boolean hasilLebihBesarSamaDenganDari(double x, double y) {return true ;}
}
| [
"ahmad_mukhlish_s@yahoo.co.id"
] | ahmad_mukhlish_s@yahoo.co.id |
0d4d77bdfd2c016fe3394e7a3f0dfa84315521c6 | 61de957d6edc90e80e9e891abe4f326f86a8d2ce | /src/main/java/cn/semiwarm/admin/service/GoodsProviderService.java | f669fdfec3c66140e7d8ca79c5fafdacb26d8762 | [] | no_license | mengfei0001/SemiWarmAdmin | 18622751a83bd8cd1a6cb4cab2571577a366de3c | 320404d4ff9237c5165b3cd4ea7411be82bad054 | refs/heads/master | 2020-03-29T04:33:09.330663 | 2017-06-12T13:40:02 | 2017-06-12T13:40:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 355 | java | package cn.semiwarm.admin.service;
import cn.semiwarm.admin.entity.GoodsProvider;
import java.util.List;
/**
* GoodsProviderService
* Created by alibct on 2017/5/10.
*/
public interface GoodsProviderService {
int addGoodsProvider(GoodsProvider goodsProvider) throws Exception;
List<GoodsProvider> getAllGoodsProvider() throws Exception;
}
| [
"semiwarm@163.com"
] | semiwarm@163.com |
a6a1b498ae3b592146c33dfe348736d69fbe0d3b | 1afb8f535b43212e480eef4a6c36e37bf58d32b0 | /src/main/java/creational/singleton/Singleton2.java | 0af084e95f2207bfb7e55bd7aca106fb404643b7 | [] | no_license | yaoOG/design-pattern | e5dbcfe4a69636873b72a022826135ab29986032 | 9186a10337b925f31b273c1aba4c42712dff8b17 | refs/heads/master | 2021-08-16T00:51:33.247771 | 2021-06-21T10:23:39 | 2021-06-21T10:23:39 | 177,540,149 | 0 | 0 | null | 2021-03-31T20:59:25 | 2019-03-25T07:57:09 | Java | UTF-8 | Java | false | false | 855 | java | package creational.singleton;
/**
* @author zhuyao
* @date 2019/03/25
* 懒汉式,线程安全
* 是否 Lazy 初始化:是
* 是否多线程安全:是
* 实现难度:易
* 描述:这种方式具备很好的 lazy loading,能够在多线程中很好的工作,但是,效率很低,99% 情况下不需要同步。
* 优点:第一次调用才初始化,避免内存浪费。
* 缺点:必须加锁 synchronized 才能保证单例,但加锁会影响效率。
* getInstance() 的性能对应用程序不是很关键(该方法使用不太频繁)。
*/
public class Singleton2 {
private static Singleton2 instance;
private Singleton2() {
}
public static synchronized Singleton2 getInstance() {
if (instance == null) {
return new Singleton2();
}
return instance;
}
}
| [
"zhuyaobjtu@yeah.net"
] | zhuyaobjtu@yeah.net |
e465a88ea969e569761d152dd9f3ac470490411c | 878969b5df33715cef38b00f1235818303d5cbd4 | /phoenix-server/server-auth/src/main/java/com/phoenix/service/impl/UserDetailServiceImpl.java | 1d6074b58effba22fb7a8902519655bbde2d673d | [] | no_license | phoniex-fly/phoniex-cloud | d9bbf2ab7fa38d99c77dfea932d79916e10d2389 | 4113b3fedad519bac340a0fce69fdd6dc18d6e63 | refs/heads/master | 2023-06-23T17:46:56.889000 | 2021-07-27T02:26:23 | 2021-07-27T02:26:23 | 381,259,899 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,458 | java | package com.phoenix.service.impl;
import com.phoenix.common.AuthConstant;
import com.phoenix.feign.AuthUserFeign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private AuthUserFeign authUserFeign;
/**
* header中存储登录类型,根据登录类型确定认证逻辑
*
* @param username
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//获取请求头中的登录类型
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String loginType = attributes.getRequest().getHeader(AuthConstant.LOGIN_TYPE);
if (StringUtils.isEmpty(loginType)) {
return null;
}
return authUserFeign.loadUserByUsername(username, loginType);
}
}
| [
"shixiaoyan@sinosoft.com.cn"
] | shixiaoyan@sinosoft.com.cn |
4981914e11d7be7b40687a93ac2024de9da0991e | b0830ae2071d13aa78cdc19e64226316f1418306 | /src/com/hrrock/view/StudentView.java | d42860bfa54fc85fcf779857ad6e434df63257f9 | [
"MIT"
] | permissive | hiteshgarg002/Student-Attendance-System | 6cb2481ab51b8c98d6d39e494433c4ea614d90fd | f90168f57a08318b4b2b661fa56a5b6a8343b6bf | refs/heads/master | 2020-04-06T08:44:35.960946 | 2019-04-09T04:48:46 | 2019-04-09T04:48:46 | 157,314,588 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,131 | java | package com.hrrock.view;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class StudentView
*/
@WebServlet("/StudentView")
public class StudentView extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public StudentView() {
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
PrintWriter out=response.getWriter();
out.println("<script src=assets/jquery-2.2.1.min.js></script>");
out.println("<script src=assets/statecity.js></script>");
out.println("<html>");
out.println("<form action='StudentSubmit' method='post' enctype='multipart/form-data'>");
out.println("<table>");
out.println("<caption><b><i>Student Register</i></b></caption>");
out.println("<tr>");
out.println("<td><b><i>Student Name:</i></b></td>");
out.println("<td><input type='text' name='sname'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Father Name:</i></b></td>");
out.println("<td><input type='text' name='fname'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Date Of Birth:</i></b></td>");
out.println("<td><input type='date' name='dob'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Gender:</i></b></td>");
out.println("<td><input value=male type='radio' name='gender'>Male  <input value=female type='radio' name='gender'>Female</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Address:</i></b></td>");
out.println("<td><textarea rows='3' cols='30' name='sadd'></textarea></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>State:</i></b></td>");
out.println("<td><select name='sstate' id='sstate'><option>-State-</option></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>City:</i></b></td>");
out.println("<td><select name='scity' id='scity'`><option>-City-</option></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Email:</i></b></td>");
out.println("<td><input type='email' name='semail'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Mobile No:</i></b></td>");
out.println("<td><input type='number' name='snumber'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Year of Admission:</i></b></td>");
out.println("<td><input type='number' name='syearofadmission'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Enrollment No:</i></b></td>");
out.println("<td><input type='text' name='senrollmentno'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Photo:</i></b></td>");
out.println("<td><input type='file' name='sphoto'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td><b><i>Password:</i></b></td>");
out.println("<td><input type='text' name='spassword'></td>");
out.println("</tr>");
out.println("</table>");
out.println("<br><br><input type='submit'> <input type='reset'>");
out.println("</form></html>");
out.flush();
}
}
| [
"hiteshgarg02@gmail.com"
] | hiteshgarg02@gmail.com |
e5b0cdbb80fd0836665f623c15033afad48f8de4 | 21a4bad70714b3bd8879653d8fd55d39725aa339 | /src/com/pibic/Aplication.java | 9eca7b7b74728b5e6037ae555320ddb4084016ac | [] | no_license | fantinatto/pibic2015_2016 | f94cc21dc362f8766597744690c0e70c9b7d7005 | 97377caa1cd6e3ca2bb8efd8f5cb08935895a306 | refs/heads/master | 2021-01-10T12:10:20.772886 | 2015-10-30T19:22:36 | 2015-10-30T19:22:36 | 44,965,955 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 766 | java | package com.pibic;
import javax.swing.SwingUtilities;
import com.pibic.controller.Controller;
import com.pibic.model.Model;
import com.pibic.view.MainFrame;
public class Aplication {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
runApp();
}
});
}
// model interface
public static void runApp() {
// cria os diretórios para organização agrupamentos e resultados
Model model = new Model();
// cria a Frame Inicial
MainFrame view = new MainFrame(model);
// controller leastener to view
Controller controller = new Controller(view, model);
// objeto passado implementa uma interface
view.setDirListener(controller);
}
}
| [
"vinicius.fantinatto@gmail.com"
] | vinicius.fantinatto@gmail.com |
22ce697211f5c3c095ced47dbccc00017cf8599d | 8a2a9959bbbf43fcaa58cc872756e16ae93a5035 | /src/main/java/com/linguancheng/gdeiassistant/Controller/ChargeRequest/ChargeRequestController.java | d4b3cc65a98c05eb084f436e1e760980452b31d2 | [
"MIT"
] | permissive | guofengma/GdeiAssistant | 5fbf0e7a5ea51d85cfd406cd243206f0d831856f | 61576d724ab7541a332d8f85035fcf7e4bcc2006 | refs/heads/master | 2020-04-22T19:58:08.056742 | 2019-02-06T18:48:54 | 2019-02-06T18:48:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,397 | java | package com.linguancheng.gdeiassistant.Controller.ChargeRequest;
import com.linguancheng.gdeiassistant.Annotation.ReplayAttacksProtection;
import com.linguancheng.gdeiassistant.Annotation.RequestLogPersistence;
import com.linguancheng.gdeiassistant.Annotation.RequireSecurity;
import com.linguancheng.gdeiassistant.Annotation.RestAuthentication;
import com.linguancheng.gdeiassistant.Pojo.Charge.ChargeRequest;
import com.linguancheng.gdeiassistant.Pojo.Entity.Charge;
import com.linguancheng.gdeiassistant.Pojo.Entity.RequestSecurity;
import com.linguancheng.gdeiassistant.Pojo.Entity.RequestValidation;
import com.linguancheng.gdeiassistant.Pojo.Entity.User;
import com.linguancheng.gdeiassistant.Pojo.Result.DataJsonResult;
import com.linguancheng.gdeiassistant.Service.Charge.ChargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@RestController
public class ChargeRequestController {
@Autowired
private ChargeService chargeService;
@RequestMapping(value = "/rest/charge", method = RequestMethod.POST)
@RestAuthentication
@RequestLogPersistence
@ReplayAttacksProtection
@RequireSecurity
public DataJsonResult ChargeRequest(HttpServletRequest request
, @RequestParam("token") String token
, @Validated @NotNull @Min(1) @Max(500) Integer amount
, @Validated ChargeRequest requestParams
, @Validated RequestValidation requestValidation
, @Validated RequestSecurity requestSecurity) throws Exception {
User user = (User) request.getAttribute("user");
Charge charge = chargeService.ChargeRequest(request.getSession().getId()
, user.getUsername(), user.getPassword(), amount);
//保存充值日志记录
chargeService.SaveChargeLog(user.getUsername(), amount);
//返回充值结果
return new DataJsonResult<>(true, charge);
}
} | [
"zwlddx0815@gmail.com"
] | zwlddx0815@gmail.com |
13601b5b8a1bd2b292e7c0e872e6ac6eaf9ee04c | b7fb06bf8dcd329b8ef3acf511060bf4de63ccf8 | /app/src/main/java/com/key/doltool/activity/setting/MessagePostActivity.java | 3b00634d88d16870fa302308cad750583ecf9956 | [] | no_license | zzxxasp/DolTool | 6c9de3d93c4519fed3a9cac07f1e108d71b55447 | 88610f4e7bfa484d05c16a2cb8f252b3d082bece | refs/heads/master | 2021-06-11T01:44:47.939687 | 2021-02-18T01:59:18 | 2021-02-18T01:59:18 | 37,501,154 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,342 | java | package com.key.doltool.activity.setting;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.key.doltool.R;
import com.key.doltool.activity.BaseActivity;
import com.key.doltool.app.util.behavior.LoginBehavior;
import com.key.doltool.view.Toast;
import com.key.doltool.view.flat.FlatButton;
import butterknife.BindView;
import cn.leancloud.AVException;
import cn.leancloud.AVObject;
import cn.leancloud.callback.SaveCallback;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
public class MessagePostActivity extends BaseActivity{
@BindView(R.id.content) EditText content;
@BindView(R.id.btn) FlatButton btn;
//控制提交状态
private boolean over=false;
@Override
public int getContentViewId() {
return R.layout.system_message_layout;
}
@Override
protected void initAllMembersView(Bundle savedInstanceState) {
initToolBar(null);
setListener();
}
private void setListener(){
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!over){
over=true;
postMessage(content.getText().toString().trim());
}
}
});
}
private boolean check(){
if(content.getText().toString().trim().equals("")){
//信息不为空
Toast.makeText(getApplicationContext(), "信息不能为空", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void clear(){
content.setText("");
}
//发信息给作者
private void postMessage(String content){
if(check()){
LoginBehavior loginBehavior=new LoginBehavior();
String name=loginBehavior.getUserName();
if(name==null){
name="游客";
}
AVObject message=new AVObject("CommonWord");
message.put("username",name);
message.put("word", content);
message.saveInBackground().subscribe(new Observer<AVObject>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(AVObject avObject) {
Toast.makeText(getApplicationContext(),"发送成功",Toast.LENGTH_LONG).show();
clear();
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"发送失败",Toast.LENGTH_LONG).show();
}
@Override
public void onComplete() {
}
});
}else{
over=false;
}
}
}
| [
"zzxxasp@163.com"
] | zzxxasp@163.com |
a0680255d0ed9a95802e5d09eb7669f9256d262a | 737d563d75514f02ddb199ffacdb7c35c5982293 | /app/src/main/java/info/sumantv/flow/userflow/UserActivitys/LoginActivity/LoginData.java | 6b5a8de9039e9b55a61b20cd02b5a983c1302dae | [] | no_license | ShivaCherupally/SumanTvApp | 7611db8babe70a808bd43edfb55c3b8a5ebb112f | 2e161595dda6a121d6ef84fcbe4571a9affcbc81 | refs/heads/master | 2022-04-20T21:37:19.389659 | 2020-04-11T07:16:21 | 2020-04-11T07:16:21 | 254,797,328 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,232 | java | package info.sumantv.flow.userflow.UserActivitys.LoginActivity;
import com.google.gson.annotations.SerializedName;
/**
* Created by PROXIM on 2/5/2018.
*/
public class LoginData {
@SerializedName("email")
private String email;
@SerializedName("password")
private String password;
@SerializedName("role")
private String role;
@SerializedName("message")
private String message;
@SerializedName("success")
private int success;
@SerializedName("lastLoginLocation")
private String loginlocation;
@SerializedName("deviceToken")
private String deviceToken;
@SerializedName("timezone")
private String timezone;
@SerializedName("error")
private String error;
@SerializedName("osType")
private String osType;
@SerializedName("secureNewLogin")
Boolean secureNewLogin;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public LoginData(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getLoginlocation() {
return loginlocation;
}
public void setLoginlocation(String loginlocation) {
this.loginlocation = loginlocation;
}
public String getDeviceToken() {
return deviceToken;
}
public void setDeviceToken(String deviceToken) {
this.deviceToken = deviceToken;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getOsType() {
return osType;
}
public void setOsType(String osType) {
this.osType = osType;
}
public Boolean getSecureNewLogin() {
return secureNewLogin;
}
public void setSecureNewLogin(Boolean secureNewLogin) {
this.secureNewLogin = secureNewLogin;
}
public LoginData(String email, String password, String loginlocation, String deviceToken, String timezone, String osType,Boolean secureNewLogin) {
this.email = email;
this.password = password;
this.loginlocation = loginlocation;
this.deviceToken = deviceToken;
this.timezone = timezone;
this.osType = osType;
this.secureNewLogin = secureNewLogin;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public LoginData(String email, String password, String loginlocation) {
this.email = email;
this.password = password;
this.loginlocation = loginlocation;
}
public int getSuccess() {
return success;
}
public void setSuccess(int success) {
this.success = success;
}
}
| [
"shivaprasad@indoztechsol.com"
] | shivaprasad@indoztechsol.com |
c136695a0ae0a958446720cc6b71e0220b6cc5bc | 12fd925f5df8c33bb0a60b08ff9ddb25c9b229e7 | /src/com/diegoliveira/interdisciplinar4/DAO/ClienteDAO.java | 76950c518ea60577bac054e6b628019e8ba3cd4e | [] | no_license | Srinoy/Hotel-Reservation-J2EE-JSP | eee8b04b61ccf93c6af53b7ae580acc6f80b4540 | 7f7866eafbcc0ac6066526e5fb5e53b59fa00680 | refs/heads/master | 2021-01-18T01:41:27.710397 | 2014-07-24T20:19:13 | 2014-07-24T20:19:13 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 8,228 | java | package com.diegoliveira.interdisciplinar4.DAO;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.diegoliveira.interdisciplinar4.DO.ClienteDO;
public class ClienteDAO extends AbstractDAO {
private static final String SALVA_SQL = "INSERT INTO cliente "
+ "(nomeCliente, rgCliente, enderecoCliente, bairroCliente, "
+ "cidadeCliente, estadoCliente, CEPCliente, nascimentoCliente, "
+ "telefoneResidencial, telefoneComercial, telefoneCelular) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
private static final String REMOVEBYID_SQL = "DELETE FROM cliente "
+ "WHERE codCliente = ?";
private static final String PROCURABYNOME_SQL = "SELECT codCliente, nomeCliente, "
+ "rgCliente, enderecoCliente, bairroCliente, cidadeCliente, estadoCliente, "
+ "CEPCliente, nascimentoCliente, telefoneResidencial, telefoneComercial, "
+ "telefoneCelular FROM cliente WHERE nomeCliente LIKE ?";
private static final String PROCURABYID_SQL = "SELECT codCliente, nomeCliente, "
+ "rgCliente, enderecoCliente, bairroCliente, cidadeCliente, estadoCliente, "
+ "CEPCliente, nascimentoCliente, telefoneResidencial, telefoneComercial, "
+ "telefoneCelular FROM cliente WHERE codCliente = ?";
private static final String ATUALIZA_SQL = "UPDATE cliente "
+ "SET nomeCliente=?, rgCliente=?, enderecoCliente=?, bairroCliente=?, cidadeCliente=?, "
+ "estadoCliente=?, CEPCliente=?, nascimentoCliente=?, telefoneResidencial=?, "
+ "telefoneComercial=?, telefoneCelular=? WHERE codCliente = ?";
private static final String GETLISTA_SQL = "SELECT codCliente, nomeCliente, "
+ "rgCliente, enderecoCliente, bairroCliente, cidadeCliente, estadoCliente, "
+ "CEPCliente, nascimentoCliente, telefoneResidencial, telefoneComercial, "
+ "telefoneCelular FROM cliente ORDER BY nomeCliente";
private static final String GETLISTAPAGINADA_SQL = "SELECT codCliente, nomeCliente, "
+ "rgCliente, enderecoCliente, bairroCliente, cidadeCliente, estadoCliente, "
+ "CEPCliente, nascimentoCliente, telefoneResidencial, telefoneComercial, "
+ "telefoneCelular FROM cliente ORDER BY nomeCliente LIMIT ?,?";
public void salva(ClienteDO cliente) throws SQLException {
PreparedStatement stmt = this.getConnection().prepareStatement(
SALVA_SQL);
stmt.setString(1, cliente.getNomeCliente());
stmt.setString(2, cliente.getRgCliente());
stmt.setString(3, cliente.getEnderecoCliente());
stmt.setString(4, cliente.getBairroCliente());
stmt.setString(5, cliente.getCidadeCliente());
stmt.setString(6, cliente.getEstadoCliente());
stmt.setString(7, cliente.getCEPCliente());
stmt.setDate(8, new Date(cliente.getNascimentoCliente().getTime()));
stmt.setString(9, cliente.getTelefoneResidencial());
stmt.setString(10, cliente.getTelefoneComercial());
stmt.setString(11, cliente.getTelefoneCelular());
stmt.execute();
stmt.close();
}
public void atualiza(ClienteDO cliente) throws SQLException {
if (cliente.getCodCliente() < 0) {
// TODO Reportar erro
return;
}
PreparedStatement stmt = this.getConnection().prepareStatement(
ATUALIZA_SQL);
stmt.setString(1, cliente.getNomeCliente());
stmt.setString(2, cliente.getRgCliente());
stmt.setString(3, cliente.getEnderecoCliente());
stmt.setString(4, cliente.getBairroCliente());
stmt.setString(5, cliente.getCidadeCliente());
stmt.setString(6, cliente.getEstadoCliente());
stmt.setString(7, cliente.getCEPCliente());
stmt.setDate(8, new Date(cliente.getNascimentoCliente().getTime()));
stmt.setString(9, cliente.getTelefoneResidencial());
stmt.setString(10, cliente.getTelefoneComercial());
stmt.setString(11, cliente.getTelefoneCelular());
stmt.setLong(12, cliente.getCodCliente());
stmt.execute();
stmt.close();
}
public void remove(ClienteDO cliente) throws SQLException {
removeById(cliente.getCodCliente());
}
public void removeById(int id) throws SQLException {
if (id < 0)
return;
PreparedStatement stmt = this.getConnection().prepareStatement(
REMOVEBYID_SQL);
stmt.setLong(1, id);
stmt.execute();
stmt.close();
}
public List<ClienteDO> procura(ClienteDO cliente) throws SQLException {
if (cliente != null) {
if (cliente.getCodCliente() >= 0) {
List<ClienteDO> lista = new ArrayList<ClienteDO>();
lista.add(procuraById(cliente.getCodCliente()));
return lista;
}
if (cliente.getNomeCliente() != null
&& cliente.getNomeCliente() != "")
return procuraByNome(cliente.getNomeCliente());
}
return null;
}
public ClienteDO procuraById(int id) throws SQLException {
if (id < 0)
return null;
PreparedStatement stmt = this.getConnection().prepareStatement(
PROCURABYID_SQL);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
ClienteDO cliente = null;
if (rs.next()) {
cliente = criaCliente(rs);
}
rs.close();
stmt.close();
return cliente;
}
public List<ClienteDO> procuraByNome(String nomeCliente)
throws SQLException {
PreparedStatement stmt = this.getConnection().prepareStatement(
PROCURABYNOME_SQL);
stmt.setString(1, "%" + nomeCliente + "%");
ResultSet rs = stmt.executeQuery();
List<ClienteDO> lista = new ArrayList<ClienteDO>();
while (rs.next()) {
ClienteDO cliente = criaCliente(rs);
lista.add(cliente);
}
rs.close();
stmt.close();
return lista;
}
public List<ClienteDO> getLista() throws SQLException {
PreparedStatement stmt = this.getConnection().prepareStatement(
GETLISTA_SQL);
ResultSet rs = stmt.executeQuery();
List<ClienteDO> lista = new ArrayList<ClienteDO>();
while (rs.next()) {
ClienteDO cliente = criaCliente(rs);
lista.add(cliente);
}
rs.close();
stmt.close();
return lista;
}
public List<ClienteDO> getListaPaginada(int inicio, int quantidade)
throws SQLException {
PreparedStatement stmt = this.getConnection().prepareStatement(
GETLISTAPAGINADA_SQL);
stmt.setInt(1, inicio);
stmt.setInt(2, quantidade);
ResultSet rs = stmt.executeQuery();
List<ClienteDO> lista = new ArrayList<ClienteDO>();
while (rs.next()) {
ClienteDO cliente = criaCliente(rs);
lista.add(cliente);
}
rs.close();
stmt.close();
return lista;
}
public int getLastID() throws SQLException {
return getLastID("cliente");
}
public int count() throws SQLException {
return count("cliente");
}
private ClienteDO criaCliente(ResultSet rs) throws SQLException {
ClienteDO cliente = new ClienteDO();
cliente.setNomeCliente(rs.getString("nomeCliente"));
cliente.setRgCliente(rs.getString("rgCliente"));
cliente.setEnderecoCliente(rs.getString("enderecoCliente"));
cliente.setBairroCliente(rs.getString("bairroCliente"));
cliente.setCidadeCliente(rs.getString("cidadeCliente"));
cliente.setEstadoCliente(rs.getString("estadoCliente"));
cliente.setCEPCliente(rs.getString("CEPCliente"));
cliente.setNascimentoCliente(rs.getDate("nascimentoCliente"));
cliente.setTelefoneResidencial(rs.getString("telefoneResidencial"));
cliente.setTelefoneComercial(rs.getString("telefoneComercial"));
cliente.setTelefoneCelular(rs.getString("telefoneCelular"));
cliente.setCodCliente(rs.getInt("codCliente"));
return cliente;
}
public ArrayList<String> getEstados(){
ArrayList<String> estados = new ArrayList<String>();
estados.add("Acre");
estados.add("Alagoas");
estados.add("Amapá");
estados.add("Amazonas");
estados.add("Bahia");
estados.add("Ceará");
estados.add("Distrito Federal");
estados.add("Goiás");
estados.add("Espírito Santo");
estados.add("Maranhão");
estados.add("Mato Grosso");
estados.add("Mato Grosso do Sul");
estados.add("Minas Gerais");
estados.add("Pará");
estados.add("Paraiba");
estados.add("Paraná");
estados.add("Pernambuco");
estados.add("Piauí");
estados.add("Rio de Janeiro");
estados.add("Rio Grande do Norte");
estados.add("Rio Grande do Sul");
estados.add("Rondônia");
estados.add("Rorâima");
estados.add("São Paulo");
estados.add("Santa Catarina");
estados.add("Sergipe");
estados.add("Tocantins");
return estados;
}
} | [
"potapczuk@gmail.com"
] | potapczuk@gmail.com |
cea7bd4a04a0e2d5b64a61f8b27efc6ae9089a5e | c32a3050856da1bdabe4c768d6a3f68a754cc833 | /src/main/java/net/bfcode/bfhcf/utils/JavaUtil.java | 1b941d55cf28cfe11073cf2b6c122116cd10ed16 | [] | no_license | NETWOR2/HCFactions-fork-Veil | bcc75c3cd1f8722c7435459475707e579f063f5c | 19f0e9ba5eae2467c55e00c16802904f67a2ade5 | refs/heads/master | 2023-01-10T23:37:03.076460 | 2020-11-13T03:33:55 | 2020-11-13T03:33:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,741 | java | package net.bfcode.bfhcf.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import net.minecraft.util.org.apache.commons.lang3.StringUtils;
public class JavaUtil {
private static CharMatcher CHAR_MATCHER_ASCII;
private static Pattern UUID_PATTERN;
private static int DEFAULT_NUMBER_FORMAT_DECIMAL_PLACES = 5;
static {
CHAR_MATCHER_ASCII = CharMatcher.inRange('0', '9').or(CharMatcher.inRange('a', 'z')).or(CharMatcher.inRange('A', 'Z')).or(CharMatcher.WHITESPACE).precomputed();
UUID_PATTERN = Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[34][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}");
}
public static Integer tryParseInt(String string) {
try {
return Integer.parseInt(string);
}
catch (IllegalArgumentException ex) {
return null;
}
}
public static Double tryParseDouble(String string) {
try {
return Double.parseDouble(string);
}
catch (IllegalArgumentException ex) {
return null;
}
}
public static boolean isUUID(String string) {
return JavaUtil.UUID_PATTERN.matcher(string).find();
}
public static boolean isAlphanumeric(String string) {
return JavaUtil.CHAR_MATCHER_ASCII.matchesAllOf((CharSequence)string);
}
public static boolean containsIgnoreCase(Iterable<? extends String> elements, String string) {
for (String element : elements) {
if (StringUtils.containsIgnoreCase(element, string)) {
return true;
}
}
return false;
}
public static String format(Number number) {
return format(number, DEFAULT_NUMBER_FORMAT_DECIMAL_PLACES);
}
public static String format(Number number, int decimalPlaces) {
return format(number, decimalPlaces, RoundingMode.HALF_DOWN);
}
public static String format(Number number, int decimalPlaces, RoundingMode roundingMode) {
Preconditions.checkNotNull(number, "The number cannot be null");
return new BigDecimal(number.toString()).setScale(decimalPlaces, roundingMode).stripTrailingZeros().toPlainString();
}
public static String andJoin(Collection<String> collection, boolean delimiterBeforeAnd) {
return andJoin(collection, delimiterBeforeAnd, ", ");
}
public static String andJoin(Collection<String> collection, boolean delimiterBeforeAnd, String delimiter) {
if (collection == null || collection.isEmpty()) {
return "";
}
List<String> contents = new ArrayList<String>(collection);
String last = contents.remove(contents.size() - 1);
StringBuilder builder = new StringBuilder(Joiner.on(delimiter).join(contents));
if (delimiterBeforeAnd) {
builder.append(delimiter);
}
return builder.append(" and ").append(last).toString();
}
public static long parse(String input) {
if (input == null || input.isEmpty()) {
return -1L;
}
long result = 0L;
StringBuilder number = new StringBuilder();
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
number.append(c);
}
else {
String str;
if (Character.isLetter(c) && !(str = number.toString()).isEmpty()) {
result += convert(Integer.parseInt(str), c);
number = new StringBuilder();
}
}
}
return result;
}
private static long convert(int value, char unit) {
switch (unit) {
case 'y': {
return value * TimeUnit.DAYS.toMillis(365L);
}
case 'M': {
return value * TimeUnit.DAYS.toMillis(30L);
}
case 'd': {
return value * TimeUnit.DAYS.toMillis(1L);
}
case 'h': {
return value * TimeUnit.HOURS.toMillis(1L);
}
case 'm': {
return value * TimeUnit.MINUTES.toMillis(1L);
}
case 's': {
return value * TimeUnit.SECONDS.toMillis(1L);
}
default: {
return -1L;
}
}
}
}
| [
"33809410+TulioTriste@users.noreply.github.com"
] | 33809410+TulioTriste@users.noreply.github.com |
b1d8fccebca827791b0a913ee24149cefe2ed0d0 | 513167cfe5dcbc18d72dc9c30d7cfe8ac6759377 | /src/main/java/com/smartapp/nlp/NLPSentencePredictor.java | 59c50d3a03037e235d811c79b01a41dcd8bea538 | [] | no_license | afiqmuzaffar/ChatProcessor | a08ba867789ee038dfe40f0a219d76b63ebf29bb | 8b81ee364c255a111dfaf17685ac3a58770a6cec | refs/heads/master | 2021-09-07T02:52:00.011449 | 2018-02-16T06:34:53 | 2018-02-16T06:34:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,907 | java | package com.smartapp.nlp;
import org.deeplearning4j.models.paragraphvectors.ParagraphVectors;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.deeplearning4j.models.word2vec.wordstore.inmemory.AbstractCache;
import org.deeplearning4j.text.documentiterator.LabelsSource;
import org.deeplearning4j.text.sentenceiterator.BasicLineIterator;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.tokenization.tokenizer.preprocessor.CommonPreprocessor;
import org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.smartapp.nlp.action.BaseAction;
import com.smartapp.nlp.utils.NLPActionMapper;
import com.smartapp.nlp.utils.NLPMatchLevel;
import com.smartapp.nlp.utils.NLPResponseObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* @author Prabal Ghura
*/
public class NLPSentencePredictor {
public static final String ACTIONMODEL = "actionmodel";
public static final String filePath = ACTIONMODEL + File.separator + "raw_sentences.txt";
private static final Logger log = LoggerFactory.getLogger(NLPSentencePredictor.class);
private ParagraphVectors vec;
public NLPSentencePredictor() {
File jointTrainingFile = new File(filePath);
InputStream targetStream = null;
try {
targetStream = new FileInputStream(jointTrainingFile);
} catch (FileNotFoundException e) {
log.error("File not found");
}
SentenceIterator iter = new BasicLineIterator(targetStream);
AbstractCache<VocabWord> cache = new AbstractCache<>();
TokenizerFactory t = new DefaultTokenizerFactory();
t.setTokenPreProcessor(new CommonPreprocessor());
LabelsSource source = new LabelsSource("DOC_");
this.vec = new ParagraphVectors.Builder()
.minWordFrequency(1)
.iterations(5)
.seed(5)
.epochs(1)
.layerSize(100)
.learningRate(0.025)
.labelsSource(source)
.windowSize(5)
.iterate(iter)
.trainWordVectors(false)
.vocabCache(cache)
.tokenizerFactory(t)
.sampling(0)
.build();
this.vec.fit();
}
@SuppressWarnings("deprecation")
public List<NLPResponseObject> response(String rawText) {
List<BaseAction> actionList = NLPActionMapper.actionList();
List<NLPResponseObject> responseList = new ArrayList<NLPResponseObject>();
for (BaseAction action : actionList)
{
double maxSimilarity = 0.0;
int maxDoc = action.getFirstDocNo();
for(int i = action.getFirstDocNo(); i <= action.getLastDocNo(); i++)
{
double similarity = this.vec.similarityToLabel(rawText, "DOC_"+i);
if(similarity>maxSimilarity)
{
maxSimilarity = similarity;
maxDoc = i;
}
}
NLPMatchLevel level = NLPMatchLevel.NONE;
maxSimilarity*=100;
if(maxSimilarity>action.getActionLevel())
level = NLPMatchLevel.ACTION;
else if(maxSimilarity>action.getConfirmLevel())
level = NLPMatchLevel.CONFIRM;
else if(maxSimilarity>action.getWarnLevel())
level = NLPMatchLevel.WARN;
if(level != NLPMatchLevel.NONE)
{
String bestMatch = getLine(maxDoc);
NLPResponseObject response = new NLPResponseObject(action.getType(), level, rawText, bestMatch);
responseList.add(response);
}
}
return responseList;
}
private String getLine(int lineNo) {
String line = null;
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
line = lines.skip(lineNo).findFirst().get();
} catch (IOException e) {
log.error("Error line not found");
}
return line;
}
}
| [
"prabalghura@yahoo.com"
] | prabalghura@yahoo.com |
1509db6400a16619447cd0d2c869f97cadc74057 | e75be673baeeddee986ece49ef6e1c718a8e7a5d | /submissions/blizzard/Corpus/eclipse.jdt.ui/4041.java | 709b28f88a588a1fd0a925ab5687245537010e3b | [
"MIT"
] | permissive | zhendong2050/fse18 | edbea132be9122b57e272a20c20fae2bb949e63e | f0f016140489961c9e3c2e837577f698c2d4cf44 | refs/heads/master | 2020-12-21T11:31:53.800358 | 2018-07-23T10:10:57 | 2018-07-23T10:10:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 248 | java | //9, 35, 9, 59
package p;
import java.util.List;
import java.util.ArrayList;
class A {
private static final ArrayList<Integer> ITEMS = new ArrayList<Integer>();
void m() {
List<? extends Number> l = ITEMS;
}
}
| [
"tim.menzies@gmail.com"
] | tim.menzies@gmail.com |
5d0106a881b779156c298c1e88eb35b848a084a0 | d81fd75783d56945382c1382b5f7b6004fe5c309 | /vendor/bonitasoft/bonita-runtime/5.7.2/bonita-server/src/main/java/org/ow2/bonita/definition/activity/ConnectorExecutor.java | 00cc90aa00eedf602245ef432ac60261fdc7e3f7 | [] | no_license | sirpentagon/bpm-infufsm | 51fc76013d60e109550aab1998ca3b44ba7e5bb0 | bbcff4ef2d7b4383b41ed37a1e7387c5bbefc6dd | refs/heads/master | 2021-01-25T13:11:48.217742 | 2014-04-28T17:06:02 | 2014-04-28T17:06:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 45,658 | java | /**
* Copyright (C) 2006 Bull S. A. S.
* Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois
* This library is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation
* version 2.1 of the License.
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301, USA.
*
* Modified by Matthieu Chaffotte - BonitaSoft S.A.
**/
package org.ow2.bonita.definition.activity;
import groovy.lang.Binding;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ow2.bonita.connector.core.Connector;
import org.ow2.bonita.connector.core.Filter;
import org.ow2.bonita.connector.core.MultiInstantiatorInstantiator;
import org.ow2.bonita.connector.core.MultiInstantiatorJoinChecker;
import org.ow2.bonita.connector.core.MultipleInstancesInstantiator;
import org.ow2.bonita.connector.core.MultipleInstancesJoinChecker;
import org.ow2.bonita.connector.core.PerformerAssignFilter;
import org.ow2.bonita.connector.core.ProcessConnector;
import org.ow2.bonita.connector.core.RoleResolver;
import org.ow2.bonita.connector.core.desc.Getter;
import org.ow2.bonita.connector.core.desc.Setter;
import org.ow2.bonita.definition.Hook;
import org.ow2.bonita.definition.MultiInstantiator;
import org.ow2.bonita.definition.MultiInstantiatorDescriptor;
import org.ow2.bonita.definition.PerformerAssign;
import org.ow2.bonita.definition.RoleMapper;
import org.ow2.bonita.definition.TxHook;
import org.ow2.bonita.facade.APIAccessor;
import org.ow2.bonita.facade.QueryDefinitionAPI;
import org.ow2.bonita.facade.QueryRuntimeAPI;
import org.ow2.bonita.facade.RuntimeAPI;
import org.ow2.bonita.facade.def.element.ConnectorDefinition;
import org.ow2.bonita.facade.def.element.HookDefinition;
import org.ow2.bonita.facade.def.element.HookDefinition.Event;
import org.ow2.bonita.facade.def.element.MultiInstantiationDefinition;
import org.ow2.bonita.facade.def.majorElement.ActivityDefinition;
import org.ow2.bonita.facade.def.majorElement.DataFieldDefinition;
import org.ow2.bonita.facade.def.majorElement.ProcessDefinition;
import org.ow2.bonita.facade.exception.ActivityNotFoundException;
import org.ow2.bonita.facade.exception.BonitaWrapperException;
import org.ow2.bonita.facade.exception.HookInvocationException;
import org.ow2.bonita.facade.exception.InstanceNotFoundException;
import org.ow2.bonita.facade.impl.StandardAPIAccessorImpl;
import org.ow2.bonita.facade.impl.StandardQueryAPIAccessorImpl;
import org.ow2.bonita.facade.runtime.ActivityInstance;
import org.ow2.bonita.facade.runtime.ActivityState;
import org.ow2.bonita.facade.runtime.ProcessInstance;
import org.ow2.bonita.facade.runtime.TaskInstance;
import org.ow2.bonita.facade.runtime.impl.InternalActivityInstance;
import org.ow2.bonita.facade.runtime.impl.InternalProcessInstance;
import org.ow2.bonita.facade.uuid.ActivityDefinitionUUID;
import org.ow2.bonita.facade.uuid.ActivityInstanceUUID;
import org.ow2.bonita.facade.uuid.ProcessDefinitionUUID;
import org.ow2.bonita.facade.uuid.ProcessInstanceUUID;
import org.ow2.bonita.light.LightProcessDefinition.ProcessType;
import org.ow2.bonita.light.LightProcessInstance;
import org.ow2.bonita.runtime.event.OutgoingEventInstance;
import org.ow2.bonita.runtime.model.Execution;
import org.ow2.bonita.services.Recorder;
import org.ow2.bonita.util.AccessorUtil;
import org.ow2.bonita.util.BonitaConstants;
import org.ow2.bonita.util.BonitaException;
import org.ow2.bonita.util.BonitaRuntimeException;
import org.ow2.bonita.util.EnvTool;
import org.ow2.bonita.util.ExceptionManager;
import org.ow2.bonita.util.GroovyBindingBuilder;
import org.ow2.bonita.util.GroovyException;
import org.ow2.bonita.util.GroovyExpression;
import org.ow2.bonita.util.GroovyUtil;
import org.ow2.bonita.util.Misc;
import org.ow2.bonita.util.TransientData;
public final class ConnectorExecutor {
private static final Logger LOG = Logger.getLogger(ConnectorExecutor.class.getName());
private ConnectorExecutor() {
}
private static Binding getBinding(final Map<String, Object> extraParameters, final ProcessDefinitionUUID processUUID,
final ActivityInstanceUUID activityInstanceUUID, final ProcessInstanceUUID instanceUUID,
final boolean useCurrentVariableValue) throws ActivityNotFoundException, GroovyException,
InstanceNotFoundException {
boolean useActivityScope = false;
boolean useInitValues = false;
if (instanceUUID != null) {
useInitValues = !useCurrentVariableValue;
} else if (activityInstanceUUID != null) {
useActivityScope = !useCurrentVariableValue;
}
final Map<String, Object> allVariables = GroovyBindingBuilder.getContext(extraParameters, processUUID,
activityInstanceUUID, instanceUUID, useActivityScope, useInitValues);
Binding binding = null;
try {
binding = GroovyBindingBuilder.getSimpleBinding(allVariables, processUUID, instanceUUID, activityInstanceUUID);
} catch (final Exception e) {
throw new BonitaRuntimeException(e);
}
return binding;
}
public static void executeConnector(final TxHook connector, final Map<String, Object[]> connectorParameters,
final ProcessInstanceUUID instanceUUID, final ActivityInstance activityInst,
final Map<String, Object> extraParameters) throws Exception {
final ProcessInstance instance = EnvTool.getJournalQueriers().getProcessInstance(instanceUUID);
final ProcessDefinitionUUID processUUID = instance.getProcessDefinitionUUID();
ActivityInstanceUUID activityInstanceUUID = null;
if (activityInst != null) {
activityInstanceUUID = activityInst.getUUID();
}
Map<String, Object[]> inputs = new HashMap<String, Object[]>();
if (connectorParameters != null) {
inputs = getInputs(connectorParameters);
}
final APIAccessor accessor = new StandardAPIAccessorImpl();
if (connector instanceof ProcessConnector) {
((ProcessConnector) connector).setApiAccessor(accessor);
((ProcessConnector) connector).setProcessDefinitionUUID(processUUID);
((ProcessConnector) connector).setProcessInstanceUUID(instanceUUID);
if (activityInst != null) {
((ProcessConnector) connector).setActivityInstanceUUID(activityInstanceUUID);
}
}
final ClassLoader baseClassLoader = Thread.currentThread().getContextClassLoader();
try {
final ClassLoader processClassLoader = EnvTool.getClassDataLoader().getProcessClassLoader(processUUID);
Thread.currentThread().setContextClassLoader(processClassLoader);
final Binding binding = getBinding(extraParameters, processUUID, activityInstanceUUID, instanceUUID, true);
if (!inputs.isEmpty()) {
if (activityInst != null) {
setParameters(binding, inputs, connector, activityInst.getUUID(), null, null, extraParameters, true);
} else {
setParameters(binding, inputs, connector, null, instanceUUID, null, extraParameters, true);
}
}
connector.execute(accessor, activityInst);
if (connectorParameters != null) {
final Map<String, Object[]> outputs = getOuputs(connectorParameters);
if (activityInst != null) {
setProcessOrActivityVariables(binding, outputs, connector, activityInstanceUUID, instanceUUID);
} else {
setProcessOrActivityVariables(binding, outputs, connector, null, instanceUUID);
}
}
} finally {
Thread.currentThread().setContextClassLoader(baseClassLoader);
}
}
public static Map<String, Object> executeConnector(final TxHook connector,
final Map<String, Object[]> connectorParameters, final ProcessDefinitionUUID processDefinitionUUID,
final Map<String, Object> extraParameters) throws Exception {
Map<String, Object[]> inputs = new HashMap<String, Object[]>();
if (connectorParameters != null) {
inputs = getInputs(connectorParameters);
}
final APIAccessor accessor = new StandardAPIAccessorImpl();
if (connector instanceof ProcessConnector) {
((ProcessConnector) connector).setApiAccessor(accessor);
((ProcessConnector) connector).setProcessDefinitionUUID(processDefinitionUUID);
}
final ClassLoader baseClassLoader = Thread.currentThread().getContextClassLoader();
Map<String, Object> newVariableValues = new HashMap<String, Object>();
try {
final ClassLoader processClassLoader = EnvTool.getClassDataLoader().getProcessClassLoader(processDefinitionUUID);
Thread.currentThread().setContextClassLoader(processClassLoader);
if (!inputs.isEmpty()) {
final Binding binding = getBinding(extraParameters, processDefinitionUUID, null, null, true);
setParameters(binding, inputs, connector, null, null, processDefinitionUUID, extraParameters, true);
}
connector.execute(accessor, null);
if (connectorParameters != null) {
final Map<String, Object[]> outputs = getOuputs(connectorParameters);
newVariableValues = getProcessVariables(outputs, connector, processDefinitionUUID);
}
} finally {
Thread.currentThread().setContextClassLoader(baseClassLoader);
}
return newVariableValues;
}
private static Map<String, Object> getGetterValues(final Connector connector) {
final List<Getter> getters = connector.getGetters();
final Map<String, Object> values = new HashMap<String, Object>();
if (getters != null) {
for (final Getter getter : getters) {
try {
final String getterName = Connector.getGetterName(getter.getName());
final Method m = connector.getClass().getMethod(getterName, new Class[0]);
final Object variableValue = m.invoke(connector, new Object[0]);
values.put(getter.getName(), variableValue);
} catch (final Exception e) {
throw new BonitaRuntimeException(e.getMessage(), e);
}
}
}
return values;
}
@SuppressWarnings("deprecation")
private static void setProcessOrActivityVariables(final Binding binding, final Map<String, Object[]> outputs,
final Object connector, final ActivityInstanceUUID activityInstanceUUID, final ProcessInstanceUUID instanceUUID)
throws BonitaException {
if (connector instanceof Connector) {
final Map<String, Object> values = getGetterValues((Connector) connector);
if (values != null) {
for (final Map.Entry<String, Object> value : values.entrySet()) {
binding.setVariable(value.getKey(), value.getValue());
}
}
if (outputs.size() > 0) {
final StandardAPIAccessorImpl accessor = new StandardAPIAccessorImpl();
final RuntimeAPI runtime = accessor.getRuntimeAPI();
for (final Entry<String, Object[]> output : outputs.entrySet()) {
final String expression = (String) output.getValue()[0];
final String variableName = output.getKey();
Object variableValue;
try {
variableValue = GroovyUtil.evaluate(expression, binding);
} catch (final Exception e) {
throw new BonitaRuntimeException(e);
}
String dataTypeClassName = null;
try {
dataTypeClassName = getDataTypeClassName(variableName, instanceUUID, activityInstanceUUID);
} catch (final BonitaRuntimeException e) {
final ProcessDefinition process = accessor.getQueryDefinitionAPI().getProcess(
instanceUUID.getProcessDefinitionUUID());
if (ProcessType.EVENT_SUB_PROCESS == process.getType()) {
final QueryRuntimeAPI queryRuntimeAPI = accessor.getQueryRuntimeAPI();
final LightProcessInstance processInstance = queryRuntimeAPI.getLightProcessInstance(instanceUUID);
dataTypeClassName = getDataTypeClassName(variableName, processInstance.getParentInstanceUUID(), null);
}
}
final Object newValue = convertIfPossible(variableValue, dataTypeClassName);
if (activityInstanceUUID != null) {
runtime.setVariable(activityInstanceUUID, variableName, newValue);
} else {
runtime.setProcessInstanceVariable(instanceUUID, variableName, newValue);
}
}
}
}
}
private static Map<String, Object> getProcessVariables(final Map<String, Object[]> outputs, final Object connector,
final ProcessDefinitionUUID processDefinitionUUID) throws BonitaException {
final Map<String, Object> newVariableValues = new HashMap<String, Object>();
if (connector instanceof Connector) {
final Map<String, Object> values = getGetterValues((Connector) connector);
for (final Entry<String, Object[]> output : outputs.entrySet()) {
final String expression = (String) output.getValue()[0];
final String variableName = output.getKey();
final Object variableValue = GroovyUtil.evaluate(expression, values, processDefinitionUUID, false);
final Object newValue = convertIfPossible(variableValue,
getDataTypeClassName(variableName, processDefinitionUUID));
newVariableValues.put(variableName, newValue);
}
}
return newVariableValues;
}
private static String getDataTypeClassName(String variableName, final ProcessInstanceUUID instanceUUID,
final ActivityInstanceUUID activityUUID) {
if (isXPathVariableReference(variableName)) {
return String.class.getName();
}
variableName = Misc.getVariableName(variableName);
final StandardQueryAPIAccessorImpl accessor = new StandardQueryAPIAccessorImpl();
final QueryDefinitionAPI queryDefinitionAPI = accessor.getQueryDefinitionAPI(AccessorUtil.QUERYLIST_JOURNAL_KEY);
if (activityUUID != null) {
try {
final ActivityInstance activity = EnvTool.getJournalQueriers().getActivityInstance(activityUUID);
return getActivityDataTypeClassName(queryDefinitionAPI, activity.getActivityDefinitionUUID(), variableName);
} catch (final Exception e) {
final ProcessInstance instance = EnvTool.getJournalQueriers().getProcessInstance(instanceUUID);
return getProcessDataTypeClassName(queryDefinitionAPI, instance.getProcessDefinitionUUID(), variableName);
}
} else {
final ProcessInstance instance = EnvTool.getJournalQueriers().getProcessInstance(instanceUUID);
return getProcessDataTypeClassName(queryDefinitionAPI, instance.getProcessDefinitionUUID(), variableName);
}
}
private static String getActivityDataTypeClassName(final QueryDefinitionAPI queryDefinitionAPI,
final ActivityDefinitionUUID activityDefinitionUUID, final String variableName) {
try {
final DataFieldDefinition data = queryDefinitionAPI.getActivityDataField(activityDefinitionUUID, variableName);
return data.getDataTypeClassName();
} catch (final Exception e) {
throw new BonitaRuntimeException(e.getMessage(), e);
}
}
private static String getProcessDataTypeClassName(final QueryDefinitionAPI queryDefinitionAPI,
final ProcessDefinitionUUID processDefinitionUUID, final String variableName) {
try {
final DataFieldDefinition data = queryDefinitionAPI.getProcessDataField(processDefinitionUUID, variableName);
return data.getDataTypeClassName();
} catch (final Exception e) {
throw new BonitaRuntimeException(e.getMessage(), e);
}
}
private static String getDataTypeClassName(String variableName, final ProcessDefinitionUUID processDefinitionUUID) {
if (isXPathVariableReference(variableName)) {
return String.class.getName();
}
variableName = Misc.getVariableName(variableName);
final StandardQueryAPIAccessorImpl accessor = new StandardQueryAPIAccessorImpl();
final QueryDefinitionAPI queryDefinitionAPI = accessor.getQueryDefinitionAPI(AccessorUtil.QUERYLIST_JOURNAL_KEY);
try {
final DataFieldDefinition data = queryDefinitionAPI.getProcessDataField(processDefinitionUUID, variableName);
return data.getDataTypeClassName();
} catch (final Exception a) {
throw new BonitaRuntimeException(a.getMessage(), a);
}
}
private static boolean isXPathVariableReference(final String variableName) {
return variableName.contains(BonitaConstants.XPATH_VAR_SEPARATOR);
}
private static Map<String, Object[]> getOuputs(final Map<String, Object[]> connectorParameters) {
final Map<String, Object[]> outputs = new HashMap<String, Object[]>();
for (final Entry<String, Object[]> parameter : connectorParameters.entrySet()) {
final String methodName = parameter.getKey();
if (!Misc.isSetter(methodName)) {
outputs.put(methodName, parameter.getValue());
}
}
return outputs;
}
private static Map<String, Object[]> getInputs(final Map<String, Object[]> connectorParameters) {
final Map<String, Object[]> inputs = new HashMap<String, Object[]>();
for (final Entry<String, Object[]> parameter : connectorParameters.entrySet()) {
final String methodName = parameter.getKey();
if (Misc.isSetter(methodName)) {
inputs.put(methodName, parameter.getValue());
}
}
return inputs;
}
private static Setter getSetter(final List<Setter> inputs, final String parameterName) {
if (inputs != null) {
for (final Setter setter : inputs) {
if (setter.getSetterName().equals(parameterName)) {
return setter;
}
}
}
return null;
}
private static Object convertIfPossible(final Object variableValue, final String dataTypeClassName) {
try {
return Misc.convertIfPossible("", variableValue, dataTypeClassName);
} catch (final Exception e) {
return variableValue;
}
}
private static void setParameters(final Binding binding, final Map<String, Object[]> parameters,
final Object connector, final ActivityInstanceUUID activityInstanceUUID,
final ProcessInstanceUUID processInstanceUUID, final ProcessDefinitionUUID processDefinitionUUID,
final Map<String, Object> extraParameters, final boolean useCurrentVariableValue) throws BonitaException {
if (parameters != null) {
for (final Entry<String, Object[]> parameter : parameters.entrySet()) {
final String methodName = parameter.getKey();
final Object[] methodParameters = evaluateParametersWithGroovy(binding, parameter.getValue(), connector);
Setter setter = null;
if (connector instanceof Connector) {
final List<Setter> setters = ((Connector) connector).getSetters();
if (setters != null) {
setter = getSetter(setters, methodName);
if (setter != null) {
final Object[] setterParameters = setter.getParameters();
for (int i = 0; i < setterParameters.length; i++) {
final Object setterParameter = setterParameters[i];
final Class<?> setterParameterClass = setterParameter.getClass();
if (setterParameterClass != null && methodParameters[i] != null
&& !setterParameterClass.equals(methodParameters[i].getClass())) {
final Class<?> methodParameterClass = methodParameters[i].getClass();
if (methodParameterClass.equals(BigDecimal.class) || methodParameterClass.equals(BigInteger.class)) {
methodParameters[i] = convertIfPossible(methodParameters[i].toString(),
setterParameterClass.getName());
} else if (methodParameterClass.equals(String.class)) {
methodParameters[i] = convertIfPossible(methodParameters[i], setterParameterClass.getName());
}
}
}
}
}
}
Object[] setterParameters = null;
if (setter != null) {
setterParameters = setter.getParameters();
}
final Class<?>[] parameterClasses = new Class[methodParameters.length];
for (int i = 0; i < parameterClasses.length; i++) {
if (methodParameters[i] == null) {
parameterClasses[i] = setterParameters[i].getClass();
} else {
parameterClasses[i] = methodParameters[i].getClass();
}
}
try {
final Method m = Connector.getMethod(connector.getClass(), methodName, parameterClasses);
if (m == null) {
final StringBuilder parambuilder = new StringBuilder();
if (parameterClasses != null) {
parambuilder.append("[");
for (int i = 0; i < parameterClasses.length; i++) {
final Class<?> class1 = parameterClasses[i];
parambuilder.append(class1);
parambuilder.append("=");
final Object parameterValue = methodParameters[i];
if (parameterValue == null) {
parambuilder.append("null");
} else {
parambuilder.append(parameterValue);
}
parambuilder.append(",");
}
parambuilder.insert(parambuilder.length() - 1, "").append("]");
}
throw new BonitaRuntimeException("Unable to find a method with name: " + methodName + " and parameters: "
+ parambuilder.toString() + " in connector: " + connector.getClass());
}
m.invoke(connector, methodParameters);
} catch (final Exception e) {
throw new BonitaRuntimeException(e.getMessage(), e);
}
}
}
}
@SuppressWarnings("unchecked")
private static Object[] evaluateParametersWithGroovy(final Binding binding, final Object[] parameters,
final Object connector) {
final Object[] methodParameters = parameters;
for (int i = 0; i < parameters.length; i++) {
final Object methodParameter = methodParameters[i];
if (methodParameter instanceof List<?>) {
final List<Object> temp = (List<Object>) methodParameter;
for (int j = 0; j < temp.size(); j++) {
final Object tempRow = temp.get(j);
if (tempRow instanceof List<?>) {
final List<Object> row = (List<Object>) tempRow;
for (int k = 0; k < row.size(); k++) {
row.set(k, getEvaluatedExpression(binding, row.get(k), connector));
}
temp.set(j, row);
} else {
temp.set(j, getEvaluatedExpression(binding, temp.get(j), connector));
}
}
methodParameters[i] = temp;
} else {
methodParameters[i] = getEvaluatedExpression(binding, methodParameter, connector);
}
}
return methodParameters;
}
private static Object getEvaluatedExpression(final Binding binding, final Object parameterMethod,
final Object connector) {
if (parameterMethod instanceof String) {
final String expression = (String) parameterMethod;
if (GroovyExpression.isGroovyExpression(expression)) {
try {
return GroovyUtil.evaluate(expression, binding);
} catch (final Exception e) {
final StringBuilder stb = new StringBuilder("Error while executing connector: '");
stb.append(connector.getClass().getName());
stb.append("'. ");
throw new BonitaRuntimeException(stb.toString(), e);
}
}
}
return parameterMethod;
}
private static void executeConnector(final Execution execution, final String activityName,
final ConnectorDefinition connector, final Map<String, Object> parameters) {
if (connector != null) {
final InternalProcessInstance instance = execution.getInstance();
final ProcessInstanceUUID instanceUUID = instance.getUUID();
final ActivityInstanceUUID activityInstanceUUID = execution.getActivityInstanceUUID();
final ProcessDefinitionUUID processUUID = instance.getProcessDefinitionUUID();
final boolean throwException = connector.isThrowingException();
try {
final Object hookInstance = EnvTool.getClassDataLoader().getInstance(Hook.class,
instance.getProcessDefinitionUUID(), connector);
if (LOG.isLoggable(Level.FINE)) {
if (activityInstanceUUID != null) {
LOG.fine("Starting connector (instance=" + instanceUUID + ", process=" + processUUID + ", activityId="
+ activityName + ") : " + connector);
} else {
LOG.fine("Starting connector (instance=" + instanceUUID + ", process=" + processUUID + ") : " + connector);
}
}
if (activityInstanceUUID == null) {
executeConnector((TxHook) hookInstance, connector.getParameters(), instanceUUID, null, parameters);
} else {
final ActivityInstance activityInst = EnvTool.getJournalQueriers().getActivityInstance(activityInstanceUUID);
if (hookInstance instanceof Hook) {
final Hook hook = (Hook) hookInstance;
hook.execute(new StandardQueryAPIAccessorImpl(), activityInst);
} else if (hookInstance instanceof TxHook) {
final TxHook txHook = (TxHook) hookInstance;
executeConnector(txHook, connector.getParameters(), instanceUUID, activityInst, parameters);
} else {
final String message = ExceptionManager.getInstance().getFullMessage("bsi_HEI_2", Hook.class.getName(),
TxHook.class.getName());
throw new BonitaRuntimeException(message);
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Finished connector (instance=" + instanceUUID + ", process=" + processUUID + ", activityId="
+ activityName + ") : " + connector);
}
}
} catch (final Exception e) {
String message = "null";
if (e != null) {
message = e.getMessage();
}
if (LOG.isLoggable(Level.SEVERE)) {
LOG.severe("Exception caught while executing connector (instance=" + instanceUUID + ", process="
+ processUUID + ", activityId=" + activityName + ") : " + connector.getClassName() + " - Exception : "
+ message + " " + Misc.getStackTraceFrom(e));
}
final String errorCode = connector.getErrorCode();
if (errorCode != null) {
if (LOG.isLoggable(Level.SEVERE)) {
LOG.severe("This exception raised an error event with code: " + errorCode);
}
final ActivityDefinition activityDefinition = execution.getNode();
String eventName = ActivityUtil.getErrorEventName(activityDefinition, errorCode);
final Recorder recorder = EnvTool.getRecorder();
if (eventName != null) {
recorder.recordBodyAborted(execution.getActivityInstance());
TransientData.removeTransientData(execution.getActivityInstanceUUID());
final OutgoingEventInstance outgoing = new OutgoingEventInstance(eventName, execution
.getProcessDefinition().getName(), activityName, null, instanceUUID, activityInstanceUUID, -1);
EnvTool.getEventService().fire(outgoing);
} else {
final ActivityDefinition eventSubProcessActivity = ActivityUtil.getMatchingErrorEvenSubProcessActivity(
execution, errorCode);
if (eventSubProcessActivity != null) {
final String targetActivityName = eventSubProcessActivity.getName();
final ProcessDefinition targetProcess = EnvTool.getJournalQueriers().getProcess(
eventSubProcessActivity.getProcessDefinitionUUID());
final String targetProcessName = targetProcess.getName();
final OutgoingEventInstance outgoing = new OutgoingEventInstance(ActivityUtil.getErrorEventName(
eventSubProcessActivity, errorCode), targetProcessName, targetActivityName, null, null, null, -1);
EnvTool.getEventService().fire(outgoing);
execution.abort();
recorder.recordInstanceAborted(instance.getUUID(), EnvTool.getUserId());
} else {
final ActivityInstanceUUID parentActivityUUID = instance.getParentActivityUUID();
if (parentActivityUUID != null) {
recorder.recordBodyAborted(execution.getActivityInstance());
final ActivityInstance parentActivity = EnvTool.getJournalQueriers().getActivityInstance(
parentActivityUUID);
final ActivityDefinition parentActivityDefinition = EnvTool.getJournalQueriers().getActivity(
parentActivity.getActivityDefinitionUUID());
eventName = ActivityUtil.getErrorEventName(parentActivityDefinition, errorCode);
final String parentActivityName = parentActivityDefinition.getName();
final ProcessInstanceUUID parentInstanceUUID = parentActivity.getProcessInstanceUUID();
final ProcessDefinition parentDefinition = EnvTool.getJournalQueriers().getProcess(
parentActivity.getProcessDefinitionUUID());
final String parentProcessName = parentDefinition.getName();
final OutgoingEventInstance outgoing = new OutgoingEventInstance(eventName, parentProcessName,
parentActivityName, null, parentInstanceUUID, parentActivityUUID, -1);
EnvTool.getEventService().fire(outgoing);
final Set<Execution> executions = EnvTool.getJournal().getExecutions(instanceUUID);
executions.iterator().next().abort();
} else {
final InternalActivityInstance activityInstance = execution.getActivityInstance();
if (activityInstance != null) {
recorder.recordActivityFailed(activityInstance);
} else { // if don't find activity instance abort it
execution.abort();
recorder.recordInstanceAborted(instanceUUID, BonitaConstants.SYSTEM_USER);
instance.finish();
}
}
}
}
} else if (throwException) {
throw new BonitaWrapperException(new HookInvocationException("bsi_HEI_3", connector.getClassName()
+ " because " + message, e));
} else if (LOG.isLoggable(Level.SEVERE)) {
LOG.severe("This exception was ignored in order to continue the process execution");
}
}
}
}
public static void executeConnectors(final ActivityDefinition activityDef, final Execution execution,
final Event event, final Map<String, Object> parameters) {
final List<HookDefinition> hooks = activityDef.getConnectors();
if (hooks != null) {
for (final HookDefinition hook : hooks) {
if (hook.getEvent() != null && hook.getEvent().equals(event)) {
if (!ActivityState.ABORTED.equals(execution.getActivityInstance().getState())) {
executeConnector(execution, activityDef.getName(), hook, parameters);
}
}
}
}
}
public static void executeConnector(final Execution execution, final String activityName,
final ConnectorDefinition connector) {
executeConnector(execution, activityName, connector, null);
}
public static void executeConnectors(final Execution execution, final Event event) {
final InternalProcessInstance instance = execution.getInstance();
final ProcessDefinitionUUID processUUID = instance.getProcessDefinitionUUID();
final ProcessDefinition definition = EnvTool.getJournalQueriers().getProcess(processUUID);
final List<HookDefinition> connectors = definition.getConnectors();
if (connectors != null) {
for (final HookDefinition connector : connectors) {
if (connector.getEvent() != null && event.equals(connector.getEvent())) {
executeConnector(execution, null, connector);
}
}
}
}
private static Map<String, Object[]> formatParameters(final Map<String, Object[]> parameters) {
final Map<String, Object[]> formattedParameters = new HashMap<String, Object[]>();
if (parameters != null) {
for (final Entry<String, Object[]> parameter : parameters.entrySet()) {
String parameterName = parameter.getKey();
if (!parameterName.startsWith("set")) {
final StringBuilder builder = new StringBuilder("set");
builder.append(String.valueOf(parameterName.charAt(0)).toUpperCase());
builder.append(parameterName.substring(1));
parameterName = builder.toString();
}
formattedParameters.put(parameterName, parameter.getValue());
}
}
return formattedParameters;
}
public static Map<String, Object> executeConnector(final Connector connector, final Map<String, Object[]> parameters)
throws Exception {
final Binding binding = getBinding(null, null, null, null, true);
setParameters(binding, formatParameters(parameters), connector, null, null, null, null, true);
connector.execute();
return getGetterValues(connector);
}
public static Map<String, Object> executeConnector(final Connector connector,
final ProcessDefinitionUUID processUUID, final ProcessInstanceUUID instanceUUID,
final ActivityInstanceUUID activityInstanceUUID, final Map<String, Object[]> parameters,
final Map<String, Object> extraParameters, final boolean useCurrentVariableValue) throws Exception {
final Map<String, Object[]> inputs = formatParameters(parameters);
if (connector instanceof ProcessConnector) {
((ProcessConnector) connector).setApiAccessor(new StandardAPIAccessorImpl());
((ProcessConnector) connector).setActivityInstanceUUID(activityInstanceUUID);
((ProcessConnector) connector).setProcessInstanceUUID(instanceUUID);
((ProcessConnector) connector).setProcessDefinitionUUID(processUUID);
}
final Binding binding = getBinding(extraParameters, processUUID, activityInstanceUUID, instanceUUID,
useCurrentVariableValue);
setParameters(binding, inputs, connector, activityInstanceUUID, instanceUUID, processUUID, extraParameters,
useCurrentVariableValue);
connector.execute();
return getGetterValues(connector);
}
public static Set<String> executeFilter(final Filter filter, Map<String, Object[]> parameters,
final Set<String> members) throws Exception {
Misc.checkArgsNotNull(members);
if (parameters == null) {
parameters = new HashMap<String, Object[]>();
}
filter.setMembers(members);
filter.setApiAccessor(new StandardAPIAccessorImpl());
final Binding binding = getBinding(null, null, null, null, true);
setParameters(binding, formatParameters(parameters), filter, null, null, null, null, true);
filter.execute();
return filter.getCandidates();
}
public static Set<String> executeRoleResolver(final RoleResolver resolver, final Map<String, Object[]> parameters)
throws Exception {
final Binding binding = getBinding(null, null, null, null, true);
setParameters(binding, formatParameters(parameters), resolver, null, null, null, null, true);
return resolver.searchMembers(null, null, "test");
}
public static void executeConnectors(final ActivityDefinition activityDef, final Execution execution,
final Event event) {
executeConnectors(activityDef, execution, event, null);
}
public static MultiInstantiatorDescriptor executeMultiInstantiator(final Execution execution,
final String activityId, final MultiInstantiator actInstantiator, final Map<String, Object[]> parameters)
throws Exception {
final ProcessInstanceUUID instanceUUID = execution.getInstance().getUUID();
if (parameters != null) {
final Map<String, Object[]> inputs = getInputs(parameters);
final Binding binding = getBinding(null, null, null, instanceUUID, true);
setParameters(binding, inputs, actInstantiator, null, instanceUUID, null, null, true);
}
return actInstantiator.execute(new StandardQueryAPIAccessorImpl(), instanceUUID, activityId,
execution.getIterationId());
}
public static Set<String> executeRoleMapper(final RoleMapper roleMapper, final TaskInstance task,
final String roleId, final Map<String, Object[]> parameters) throws Exception {
final ProcessInstanceUUID processInstanceUUID = task.getProcessInstanceUUID();
if (parameters != null) {
final Map<String, Object[]> inputs = getInputs(parameters);
final ActivityInstanceUUID activityInstanceUUID = task.getUUID();
final Binding binding = getBinding(null, null, activityInstanceUUID, processInstanceUUID, true);
setParameters(binding, inputs, roleMapper, activityInstanceUUID, processInstanceUUID, null, null, true);
}
return roleMapper.searchMembers(new StandardQueryAPIAccessorImpl(), processInstanceUUID, roleId);
}
public static Set<String> executeFilter(final Filter filter, final PerformerAssign performerAssign,
final ActivityInstance activityInstance, final Set<String> candidates, final Map<String, Object[]> parameters)
throws Exception {
final ClassLoader baseClassLoader = Thread.currentThread().getContextClassLoader();
try {
final ClassLoader processClassLoader = EnvTool.getClassDataLoader().getProcessClassLoader(
activityInstance.getProcessDefinitionUUID());
Thread.currentThread().setContextClassLoader(processClassLoader);
Map<String, Object[]> inputs = new HashMap<String, Object[]>();
if (filter instanceof PerformerAssignFilter) {
((PerformerAssignFilter) filter).setPerformerAssign(performerAssign);
if (parameters != null) {
final Binding binding = getBinding(null, null, activityInstance.getUUID(), null, true);
setParameters(binding, parameters, performerAssign, activityInstance.getUUID(), null, null, null, true);
}
((PerformerAssignFilter) filter).setClassName(performerAssign.getClass().getName());
} else if (parameters != null) {
inputs = getInputs(parameters);
}
filter.setActivityInstanceUUID(activityInstance.getUUID());
filter.setApiAccessor(new StandardAPIAccessorImpl());
filter.setMembers(candidates);
filter.setProcessDefinitionUUID(activityInstance.getProcessDefinitionUUID());
filter.setProcessInstanceUUID(activityInstance.getProcessInstanceUUID());
if (!inputs.isEmpty()) {
final Binding binding = getBinding(null, null, activityInstance.getUUID(), null, true);
setParameters(binding, inputs, filter, activityInstance.getUUID(), null, null, null, true);
}
filter.execute();
return filter.getCandidates();
} finally {
Thread.currentThread().setContextClassLoader(baseClassLoader);
}
}
public static List<Map<String, Object>> executeMultipleInstancesInstantiatior(
final MultiInstantiationDefinition instantiator, final ProcessInstanceUUID instanceUUID,
final String activityName, final String iterationId) throws Exception {
final ProcessInstance instance = EnvTool.getJournalQueriers().getProcessInstance(instanceUUID);
final ProcessDefinitionUUID definitionUUID = instance.getProcessDefinitionUUID();
final ClassLoader baseClassLoader = Thread.currentThread().getContextClassLoader();
try {
final ClassLoader processClassLoader = EnvTool.getClassDataLoader().getProcessClassLoader(definitionUUID);
Thread.currentThread().setContextClassLoader(processClassLoader);
final MultipleInstancesInstantiator activityinstantiator = EnvTool.getClassDataLoader().getInstance(
MultipleInstancesInstantiator.class, definitionUUID, instantiator);
final Map<String, Object[]> parameters = instantiator.getParameters();
Map<String, Object[]> inputs = new HashMap<String, Object[]>();
if (parameters != null) {
inputs = getInputs(parameters);
}
activityinstantiator.setActivityInstanceUUID(null);
activityinstantiator.setActivityName(activityName);
activityinstantiator.setApiAccessor(new StandardAPIAccessorImpl());
activityinstantiator.setIterationId(iterationId);
activityinstantiator.setProcessDefinitionUUID(definitionUUID);
activityinstantiator.setProcessInstanceUUID(instanceUUID);
final Binding binding = getBinding(null, null, null, instanceUUID, true);
setParameters(binding, inputs, activityinstantiator, null, instanceUUID, null, null, true);
if (activityinstantiator.getClass().getName().equals(MultiInstantiatorInstantiator.class.getName())) {
final String className = ((MultiInstantiatorInstantiator) activityinstantiator).getClassName();
final org.ow2.bonita.connector.core.MultiInstantiator multiInstantiator = (org.ow2.bonita.connector.core.MultiInstantiator) EnvTool
.getClassDataLoader().getInstance(definitionUUID, className);
final Map<String, Object[]> temp = ((MultiInstantiatorInstantiator) activityinstantiator)
.getInstantiatorParameters();
if (temp != null) {
((MultiInstantiatorInstantiator) activityinstantiator).setActivityName(activityName);
((MultiInstantiatorInstantiator) activityinstantiator).setIterationId(iterationId);
((MultiInstantiatorInstantiator) activityinstantiator).setProcessInstanceUUID(instanceUUID);
setParameters(binding, temp, multiInstantiator, null, instanceUUID, null, null, true);
}
((MultiInstantiatorInstantiator) activityinstantiator).setInstantiator(multiInstantiator);
}
activityinstantiator.execute();
return activityinstantiator.getActivitiesContext();
} finally {
Thread.currentThread().setContextClassLoader(baseClassLoader);
}
}
public static boolean executeMultipleInstancesJoinChecker(final MultiInstantiationDefinition joinChecker,
final ActivityInstanceUUID activityUUID) throws Exception {
final ActivityInstance activity = EnvTool.getJournalQueriers().getActivityInstance(activityUUID);
final ProcessInstanceUUID instanceUUID = activity.getProcessInstanceUUID();
final ProcessDefinitionUUID definitionUUID = activity.getProcessDefinitionUUID();
final ClassLoader baseClassLoader = Thread.currentThread().getContextClassLoader();
try {
final ClassLoader processClassLoader = EnvTool.getClassDataLoader().getProcessClassLoader(definitionUUID);
Thread.currentThread().setContextClassLoader(processClassLoader);
final MultipleInstancesJoinChecker checker = EnvTool.getClassDataLoader().getInstance(
MultipleInstancesJoinChecker.class, definitionUUID, joinChecker);
final Map<String, Object[]> parameters = joinChecker.getParameters();
Map<String, Object[]> inputs = new HashMap<String, Object[]>();
if (parameters != null) {
inputs = getInputs(parameters);
}
checker.setActivityInstanceUUID(activityUUID);
checker.setActivityName(activity.getActivityName());
checker.setApiAccessor(new StandardAPIAccessorImpl());
checker.setIterationId(activity.getIterationId());
checker.setProcessDefinitionUUID(definitionUUID);
checker.setProcessInstanceUUID(instanceUUID);
final Binding binding = getBinding(null, null, null, instanceUUID, true);
setParameters(binding, inputs, checker, null, instanceUUID, null, null, true);
if (checker.getClass().getName().equals(MultiInstantiatorJoinChecker.class.getName())) {
final String className = ((MultiInstantiatorJoinChecker) checker).getClassName();
final org.ow2.bonita.connector.core.MultiInstantiator multiInstantiator = (org.ow2.bonita.connector.core.MultiInstantiator) EnvTool
.getClassDataLoader().getInstance(definitionUUID, className);
final Map<String, Object[]> temp = ((MultiInstantiatorJoinChecker) checker).getInstantiatorParameters();
if (temp != null) {
multiInstantiator.setActivityId(activity.getActivityName());
multiInstantiator.setIterationId(activity.getIterationId());
multiInstantiator.setProcessInstanceUUID(instanceUUID);
setParameters(binding, temp, multiInstantiator, null, instanceUUID, null, null, true);
}
((MultiInstantiatorJoinChecker) checker).setInstantiator(multiInstantiator);
}
checker.execute();
return checker.isJoinable();
} catch (final Exception e) {
final StringBuilder builder = new StringBuilder(
"An Exception occurs during join checking of mutliple instances activity: '");
builder.append(activity.getActivityName()).append("' of instance: ").append(instanceUUID).append(" of process: ")
.append(definitionUUID).append(".\r\n Exception : ").append(e.getMessage());
throw new BonitaRuntimeException(builder.toString());
} finally {
Thread.currentThread().setContextClassLoader(baseClassLoader);
}
}
}
| [
"andrea@inf.ufsm.br"
] | andrea@inf.ufsm.br |
013c9a146cdd9aad0825207c07b9bb87e6481b35 | 72bec122de8dc937f433283a985312b7fa4c59d6 | /CameraNdco/ncameralib/src/main/java/com/ndco/ncameralib/camera/UIExtensin.java | 5df718e5b0412764cfec975bc1bb48f0b1c54cbd | [] | no_license | edokonan/android-zuk-camera-demo | f7613c7e88859e8dffe802cefcac9ca55462212a | 29caea51ad53a9977494ab2ab2b650d57ecb1a87 | refs/heads/master | 2021-01-21T13:18:01.066052 | 2017-06-13T15:27:41 | 2017-06-13T15:27:41 | 91,809,535 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,311 | java | package com.ndco.ncameralib.camera;
import android.hardware.Camera;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by zuk
*/
public class UIExtensin {
//计算长宽比(例 1920/1080)
static public float getRate(int width, int height) {
float r ;
if (width>height){
r = (float)width / (float) height;
}else{
r = (float)height / (float) width;
}
int x = (int) (r * 100);
return (float)x/(float)100;
}
//根据相同比例选择最大的size
// static public Camera.Size getMaxSizeByScreenSize(int width, int height, List<Camera.Size> sizeList){
// float r = getRate(width,height);
// for (Camera.Size size : sizeList){
// float rate = getRate(size.width,size.height);
// if (Math.abs(r - rate) <= 0.2) {
// return size;
// }
// }
// return sizeList.get(0);
// }
//根据相同比例选择最大的size
static public Camera.Size getMaxSizeByRate(float r, List<Camera.Size> sizeList){
Collections.sort(sizeList, new Comparator<Camera.Size>() {
@Override
public int compare(Camera.Size o1, Camera.Size o2) {
if (o1.width > o2.width) {
return -1;
} else if (o1.width == o2.width) {
return 0;
} else {
return 1;
}
}
});
for (Camera.Size size : sizeList){
float rate = getRate(size.width,size.height);
if (Math.abs(r - rate) <= 0.2) {
return size;
}
}
return sizeList.get(0);
}
static public String getSurfaceViewSize(int width, int height) {
if (equalRate(width, height, 1.33f)) {
return "4:3";
} else {
return "16:9";
}
}
static public boolean equalRate(int width, int height, float rate) {
float r = (float)width /(float) height;
if (Math.abs(r - rate) <= 0.2) {
return true;
} else {
return false;
}
}
}
| [
"zhukui83@gmail.com"
] | zhukui83@gmail.com |
29d71b513362887b70321a173cda699d340fd76b | e3cd1b37922ee079769bd01412efb448ffdcb545 | /Sir/src/SalesManagement/pojo/ProductSales.java | beac7deb857ece7ade90aabe17fe9a7d7204605d | [] | no_license | Shuvoneel/Swing | a65139da934148e9dcebf3d7f039f6fd541b355b | 97e77c791baeab04bfca09a93467ccfa2ffbcbf4 | refs/heads/master | 2020-04-22T15:34:06.053737 | 2019-07-01T03:10:05 | 2019-07-01T03:10:05 | 170,481,535 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,439 | java | package SalesManagement.pojo;
import java.sql.Date;
public class ProductSales {
private int id;
private String productName;
private String productCode;
private int qty;
private double unitPrice;
private double totalPrice;
private Date salesDate;
private Product product;
public ProductSales() {
}
public ProductSales(int id) {
this.id = id;
}
public ProductSales(String productName, String productCode, int qty, double unitPrice, double totalPrice, Date salesDate, Product product) {
this.productName = productName;
this.productCode = productCode;
this.qty = qty;
this.unitPrice = unitPrice;
this.totalPrice = totalPrice;
this.salesDate = salesDate;
this.product = product;
}
public ProductSales(int id, String productName, String productCode, int qty, double unitPrice, double totalPrice, Date salesDate, Product product) {
this.id = id;
this.productName = productName;
this.productCode = productCode;
this.qty = qty;
this.unitPrice = unitPrice;
this.totalPrice = totalPrice;
this.salesDate = salesDate;
this.product = product;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public Date getSalesDate() {
return salesDate;
}
public void setSalesDate(Date salesDate) {
this.salesDate = salesDate;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
| [
"mhshuvo29@gmail.com"
] | mhshuvo29@gmail.com |
a966883ed1315e53c931346e016ccd0745724fdc | a0ba7c339b29c33098f5e657e7745c96b4c10da5 | /src/java/xxxt/bilogin/db/entities/RolDuyuru.java | 59941a6555dd0d6e0e77cb2ce91f5cc60562bbab | [] | no_license | kutayakyol/BiLoginAdminWebApp | dd5c9f430cdca2f64eb902a8db48b592982622eb | 9014e097fd6349f776b637a3182182a0e7fb04fe | refs/heads/master | 2021-01-12T04:08:53.471881 | 2017-01-13T13:55:33 | 2017-01-13T13:55:33 | 77,512,228 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,241 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package xxxt.bilogin.db.entities;
import java.math.BigDecimal;
import java.util.Date;
/**
*
* @author admin
*/
public class RolDuyuru {
private Long id;
private BigDecimal rolId;
private String messageBody;
private Date effectiveStartDate;
private Date effectiveEndDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BigDecimal getRolId() {
return rolId;
}
public void setRolId(BigDecimal rolId) {
this.rolId = rolId;
}
public String getMessageBody() {
return messageBody;
}
public void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public Date getEffectiveStartDate() {
return effectiveStartDate;
}
public void setEffectiveStartDate(Date effectiveStartDate) {
this.effectiveStartDate = effectiveStartDate;
}
public Date getEffectiveEndDate() {
return effectiveEndDate;
}
public void setEffectiveEndDate(Date effectiveEndDate) {
this.effectiveEndDate = effectiveEndDate;
}
}
| [
"kutay.akyol@etiya.com"
] | kutay.akyol@etiya.com |
252e955eccbf5e7b68265072d69584dd090b65b7 | f7907b642cc4913a622fcb80e2fd988950352cb2 | /src/main/java/lmxpages/Productselection.java | 74d839d9904ebf6050dcf294ffa2b94d02d90a7e | [] | no_license | yokga03/LMX-live | fb69f7359b56bcbf9e7cd09d6b1e81c9c1b564c3 | 82bbb69f9baf7de5a13623011114c5207fca06bf | refs/heads/main | 2023-02-14T21:47:21.247681 | 2020-12-30T08:06:57 | 2020-12-30T08:06:57 | 325,685,109 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 716 | java | package lmxpages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import wdMethods.ProjectMethods;
public class Productselection extends ProjectMethods{
public Productselection() {
PageFactory.initElements(driver, this);
}
//click Registry
@FindBy(xpath="//p[text()='Manage your inventory and accounts']")
WebElement Registry;
public Productselection clickRegistry() {
click(Registry);
return this;
}
//click Continue
@FindBy(name="button")
WebElement Continue;
public Dashboard clickContinue() throws InterruptedException {
Thread.sleep(2000);
click(Continue);
return new Dashboard();
}
}
| [
"yokga6881@gmail.com"
] | yokga6881@gmail.com |
28ffaafc2293799120200bd27946963f707b64c5 | d8e58013e4cc18e4c914116982cb40a91052504b | /texttospeech/app/src/main/java/com/example/texttospeech/MainActivity.java | 781beb1cf4f02ee0133435ccdaa5f876748dc9ce | [] | no_license | vishwaskamath/Android-Mini-Lab | b7ce94715a856f4be6d5995c662d8c443446f2f8 | 36138886a44baecc8ace7f28b92d74616510e025 | refs/heads/main | 2023-05-25T10:43:15.195411 | 2021-06-07T05:40:29 | 2021-06-07T05:40:29 | 368,565,981 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,419 | java | package com.example.texttospeech;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText txtSpeak;
Button btnSpeak;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeak=(EditText)findViewById(R.id.editText);
btnSpeak=(Button)findViewById(R.id.btn_speak);
btnSpeak.setOnClickListener(this);
textToSpeech=new TextToSpeech(getBaseContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status!=TextToSpeech.ERROR)
{
Toast.makeText(getBaseContext(),"Success", Toast.LENGTH_LONG).show();
}
}
});
textToSpeech.setLanguage(Locale.UK);
}
public void onClick(View v)
{
String text=txtSpeak.getText().toString();
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null);
}
} | [
"vishwaskamath58@gmail.com"
] | vishwaskamath58@gmail.com |
72addba9833e1b38a16a58c9b1b448a3aef6e2e8 | 161556e1707129323b157dd12e0773770cc2b180 | /tests/objectbox-java-test/src/test/java/io/objectbox/query/AbstractQueryTest.java | 518c6ad74f2eba0edb78c0dc13970b8d17493c5b | [
"Apache-2.0"
] | permissive | joele123/objectbox-java | 2325756bfa3014f59948381b5f20dd817f978556 | d20e1af43cec284f9272605a90803e0e8aa97e3a | refs/heads/master | 2020-04-15T10:52:36.339609 | 2018-12-29T21:40:38 | 2018-12-29T21:40:38 | 164,602,292 | 1 | 0 | Apache-2.0 | 2019-01-08T08:33:40 | 2019-01-08T08:33:40 | null | UTF-8 | Java | false | false | 1,792 | java | /*
* Copyright 2018 ObjectBox Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.objectbox.query;
import io.objectbox.*;
import org.junit.Before;
import java.util.ArrayList;
import java.util.List;
public class AbstractQueryTest extends AbstractObjectBoxTest {
protected Box<TestEntity> box;
@Override
protected BoxStoreBuilder createBoxStoreBuilder(boolean withIndex) {
return super.createBoxStoreBuilder(withIndex).debugFlags(DebugFlags.LOG_QUERY_PARAMETERS);
}
@Before
public void setUpBox() {
box = getTestEntityBox();
}
/**
* Puts 10 TestEntity starting at nr 2000 using {@link AbstractObjectBoxTest#createTestEntity(String, int)}.
*/
List<TestEntity> putTestEntitiesScalars() {
return putTestEntities(10, null, 2000);
}
List<TestEntity> putTestEntitiesStrings() {
List<TestEntity> entities = new ArrayList<>();
entities.add(createTestEntity("banana", 1));
entities.add(createTestEntity("apple", 2));
entities.add(createTestEntity("bar", 3));
entities.add(createTestEntity("banana milk shake", 4));
entities.add(createTestEntity("foo bar", 5));
box.put(entities);
return entities;
}
}
| [
"opensource+team@greenrobot"
] | opensource+team@greenrobot |
8d461a097d3a0b7eb0b17f9319702145eef2fe50 | 168e640d3372b0fcadf60a5991ce967b6c33308d | /zafeplacesdk/src/main/java/com/zafeplace/sdk/stellarsdk/sdk/xdr/Int64.java | 9083d4033753648e68c724312ea56d18f40108a7 | [] | no_license | IdeaSoft-Blockchain/Zafeplace-AndroidSDK | a401ea4e7d570e694d6c1a508136487283bc19e1 | a0e9f40fb5ede1c0f97c75450b6a0b86074f43a1 | refs/heads/master | 2020-03-21T20:22:57.373974 | 2018-06-28T10:30:53 | 2018-06-28T10:30:53 | 139,003,516 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 845 | java | // Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
package com.zafeplace.sdk.stellarsdk.sdk.xdr;
import java.io.IOException;
// === xdr source ============================================================
// typedef hyper int64;
// ===========================================================================
public class Int64 {
private Long int64;
public Long getInt64() {
return this.int64;
}
public void setInt64(Long value) {
this.int64 = value;
}
public static void encode(XdrDataOutputStream stream, Int64 encodedInt64) throws IOException {
stream.writeLong(encodedInt64.int64);
}
public static Int64 decode(XdrDataInputStream stream) throws IOException {
Int64 decodedInt64 = new Int64();
decodedInt64.int64 = stream.readLong();
return decodedInt64;
}
}
| [
"gstogniev@gmail.com"
] | gstogniev@gmail.com |
c7b283728a31aaeb5cb804d8eb4cc18ff16da1c2 | 55cd7239d3391a28769ec38ff4e1bae57dd7b8f1 | /src/main/java/com/mcbouncer/commands/GlobalNoteCommand.java | 034770cbcff87a2c7d4696e40f7a9b4ea0d1a961 | [] | no_license | MCBouncer/MCBouncer-API | d5d402f2a530e3c52d2947e6987db799b2d6dd24 | 2167b407b9de05a4acdbe5b32f712e0afa6bf7b5 | refs/heads/master | 2021-01-21T14:12:32.074477 | 2016-03-02T01:20:53 | 2016-03-02T01:20:53 | 4,693,952 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,778 | java | /*
* MCBouncer-API
* Copyright 2012-2014 Deaygo Jarkko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mcbouncer.commands;
import com.mcbouncer.*;
import com.mcbouncer.api.MCBouncerCommandSender;
import com.mcbouncer.api.MCBouncerCommand;
import com.mcbouncer.api.MCBouncerImplementation;
import com.mcbouncer.api.MCBouncerPlayer;
import com.mcbouncer.exceptions.APIException;
import java.util.HashMap;
public class GlobalNoteCommand extends MCBouncerCommand {
private MCBouncerImplementation impl;
public GlobalNoteCommand(MCBouncerImplementation plugin) {
super("addglobalnote", Perm.COMMAND_GLOBALNOTE, "addgnote");
this.impl = plugin;
}
@Override
public boolean onCommand(MCBouncerCommandSender sender, String[] args) {
if (args.length < 2) {
return false;
}
String user = args[0];
String note = Util.join(args, " ", 1);
HashMap<String, String> messageParams = new HashMap<>();
messageParams.put("username", user);
MCBouncerPlayer p;
if (sender instanceof MCBouncerPlayer) {
p = (MCBouncerPlayer) sender;
} else if (sender.getName().equalsIgnoreCase("console")) {
p = ConsolePlayer.getInstance();
} else {
return false;
}
try {
int note_id = impl.getMCBouncerPlugin().addNote(user, note, p, true);
messageParams.put("note_id", String.valueOf(note_id));
Util.messageSender(impl, sender, Config.MESSAGE_NOTE_ADD_SUCCESS, messageParams);
boolean broadcastMessage = this.impl.getMCBouncerPlugin().getConfig().getBoolean(Config.BROADCAST_NOTE_MESSAGES);
Perm perm = null;
if (!broadcastMessage) {
perm = Perm.MESSAGE_ADD_NOTE;
}
messageParams.put("note", note);
messageParams.put("issuer", p.getName());
Util.broadcastMessage(impl, perm, Config.MESSAGE_NOTE_BROADCAST, messageParams);
}
catch (APIException e) {
messageParams.put("error_msg", e.getMessage());
Util.messageSender(impl, sender, Config.MESSAGE_NOTE_ADD_FAILURE, messageParams);
}
return true;
}
}
| [
"deaygo@thezomg.com"
] | deaygo@thezomg.com |
3ca6b6620c5df63695e4db744eca32cd7e6b0b0b | a80e56f814f874cfd29a47364603044e24f957be | /src/main/java/smt/pack/phytology/world/ActBoss.java | 827154ecdce16f24e986b6a22ef8bb60e210c17b | [] | no_license | timaxa007/SMT | 55cc815a8c354bc155da660e26fce5fd224aabb2 | 4fb54c1d65df1b25395ebe7d4221d93f895e658c | refs/heads/master | 2020-04-02T01:32:58.168246 | 2018-07-28T19:11:16 | 2018-07-28T19:11:16 | 27,762,065 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 229 | java | package smt.pack.phytology.world;
import net.minecraft.util.AxisAlignedBB;
public class ActBoss {
static AxisAlignedBB boundingBox = null;
public static void setBoundingBox(AxisAlignedBB aabb) {
boundingBox = aabb;
}
}
| [
"timaxa007@gmail.com"
] | timaxa007@gmail.com |
694ec72d4f3d972b2c10c39ea79aed5862a847e9 | 709a0b3207cc357e71569b5b98133d7220e924a8 | /java/xmlreader/src/main/java/be/bosa/dt/best/xmlreader/BestReader.java | d671b7ce564c4bf469495649b1966a7537d75cd6 | [
"BSD-2-Clause"
] | permissive | Fedict/best-tools | 5879e0e2d448d6fbc2e1eb53abf578e9fe74bc70 | 3966d65d07e9a8ce0ef340ff6b67b1e30684644c | refs/heads/master | 2023-04-14T08:00:08.795636 | 2023-04-06T11:45:30 | 2023-04-06T11:47:27 | 146,793,993 | 3 | 0 | BSD-2-Clause | 2023-04-06T11:48:21 | 2018-08-30T19:01:56 | Java | UTF-8 | Java | false | false | 2,043 | java | /*
* Copyright (c) 2018, FPS BOSA DG DT
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package be.bosa.dt.best.xmlreader;
import be.bosa.dt.best.dao.BestRegion;
import be.bosa.dt.best.dao.BestType;
import java.nio.file.Path;
import java.util.stream.Stream;
/**
* BeST XML file reader interface
*
* @author Bart Hanssens
*
* @param <T>
*/
public interface BestReader<T> {
/**
* Process the input file and return a stream of BeSt objects.
* Each of the three regions has several types of objects.
*
* @param region region
* @param type type
* @param indir input directory
* @return a stream of BeSt objects
*/
public Stream<T> read(BestRegion region, BestType type, Path indir);
}
| [
"bart.hanssens@bosa.fgov.be"
] | bart.hanssens@bosa.fgov.be |
eab9d6ac334050c271095b5616623e47afc9e579 | 4b75b2c4a36e905711bc8f7048f5b98d2bfff228 | /TP4/tp4/Date.java | b931c2f4b980718d1adb206d00ccd77f94d63b5a | [] | no_license | FrancoisT97/java-tps-hebdomadaires-AutomeEdwin | c099747470fe64e4d8326466db8c61d507031792 | 6d8b35d1dd8baa77445c203aeb23ab6113ce72f3 | refs/heads/master | 2020-11-27T12:02:28.753546 | 2019-12-02T21:34:10 | 2019-12-02T21:34:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 694 | java | /**
*
*/
package tp4;
/**
* Cette classe modélise une date de manière simplifiée.
* @author Virginie Van den Schrieck
*
*/
public class Date {
//variables d'instance
int jour;
int mois;
int année;
/**
* La méthode main permet de tester la classe date en créant un objet
* au départ des arguments de la ligne de commande. Trois arguments sont attendus, sous forme d'entiers :
* Le jour, le mois et l'année.
* @param args les arguments de la ligne de commande
*/
public static void main(String [] args) {
Date d = new Date();
d.jour = Integer.parseInt(args[0]);
d.mois = Integer.parseInt(args[1]);
d.année = Integer.parseInt(args[2]);
}
}
| [
"automeedwin@gmail.com"
] | automeedwin@gmail.com |
4595b1f833fdae34474ae5ce4b9838ef72882925 | d93fddae76ea0e53312701a0d1b7230f0c7d7ae4 | /src/main/java/com/ardo/common/tools/PropertiesUtil.java | 5477cbb7292fb8255b07b7dc1f9b3f81d727b59b | [] | no_license | ardopass/trapp | c7058f01bd4702e51bf24d5018e08f699992a39d | b4c819ff1d2f328cbb0b82aa511ef1624d67eb62 | refs/heads/master | 2020-05-02T03:39:31.707284 | 2019-04-03T12:07:30 | 2019-04-03T12:07:30 | 177,733,682 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,858 | java | /*
* 文 件 名: PropertyUtil.java
* 版 权: Huawei Technologies Co., Ltd. Copyright YYYY-YYYY, All rights reserved
* 描 述: <描述>
* 修 改 人: c00221720
* 修改时间: 2013-7-25
* 跟踪单号: <跟踪单号>
* 修改单号: <修改单号>
* 修改内容: <修改内容>
*/
package com.ardo.common.tools;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* <一句话功能简述>
* <功能详细描述>
*
* @author c00221720
* @version [版本号, 2013-7-25]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class PropertiesUtil
{
private static Properties pro = new Properties();
static
{
pro = loadProperties("baseConfig.properties");
}
/**
* 获取对应key的值
*
* @param key
* @return
*/
public static String getValue(String key)
{
return pro.getProperty(key);
}
/**
* 获取对应key的值
*
* @param key
* @param defaultValue 默认值
* @return
*/
public static String getValue(String key, String defaultValue)
{
return pro.getProperty(key, defaultValue);
}
/**
* 加载配置文件
* <功能详细描述>
* @param path
* @return
* @see [类、类#方法、类#成员]
*/
public static Properties loadProperties(String path)
{
InputStream in = null;
Properties p = new Properties();
try
{
/************方法一:该加载修改配置文件后需要重启服务*****************/
//加载配置文件到文件流
in = PropertiesUtil.class.getClassLoader().getResourceAsStream(path);
p.load(in);
/************方法二:该加载修改配置文件后不需要重启服务*****************/
// Properties prop = new Properties();
// String rootpath = PropertiesUtil.class.getClassLoader().getResource(path).getPath();
// System.out.println("0000000000000000000000000===================$$$$$$$rootpath==="+rootpath);
// InputStream is = new FileInputStream(rootpath);
// prop.load(is);
}
catch (IOException e)
{
e.printStackTrace();
}
//处理异常
finally
{
if (null != in)
{
try
{
//关闭文件流
in.close();
in = null;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return p;
}
}
| [
"36293655+ardopass@users.noreply.github.com"
] | 36293655+ardopass@users.noreply.github.com |
66729c28e2ce3f2109eb46186853919f8be68b9e | 8f4a0d7fec789c036362bc35560a375ba8710f83 | /mana-grpc-server/src/main/java/com/czj/nettyserver/NettyServer.java | ccfc342f3fab452e98eed3eda68bb8b891a5adb0 | [] | no_license | Jie1214/managerProject | 5c9e80ad89493c793eabc93dfbbc96ed506b0191 | dd7267b3f6a9d83327744357c97e1aff5ac37be9 | refs/heads/master | 2022-11-30T07:31:08.944358 | 2020-02-27T06:40:50 | 2020-02-27T06:40:50 | 173,074,225 | 0 | 0 | null | 2022-11-16T07:21:32 | 2019-02-28T08:39:46 | Java | UTF-8 | Java | false | false | 3,901 | java | package com.czj.nettyserver;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Created by Jie on 2019/4/18.
*
* @AUTHOR JIE
* @date 2019/4/18
*/
@Component
public class NettyServer {
private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
private ChannelFuture channelFuture;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
@Value("${rpcServer.ioThreadNum}")
private int ioThreadNum = 5;
//内核为此套接口排队的最大连接个数,对于给定的监听套接口,内核要维护两个队列,未链接队列和已连接队列大小总和最大值
@Value("${rpcServer.backlog}")
private int backlog = 1024;
@Value("${rpcServer.port}")
private int port = 20011;
/**
* 启动
*/
public void nettyStart() {
logger.info("Begin To Start RPC Server...");
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup(ioThreadNum);
logger.info("NettyRPC server listening on port " + port + " and ready for connections...");
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup);
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.localAddress(8091);
serverBootstrap.option(ChannelOption.SO_BACKLOG, backlog);
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline()
//心跳检测
//超过15分钟未收到客户端消息则自动断开客户端连接
.addLast("idleStateHandler", new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS))
.addLast();
}
});
try {
// 异步地绑定服务器;调用sync方法阻塞等待直到绑定完成
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
// 获取Channel的CloseFuture,并且阻塞当前线程直到它完成
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 优雅的关闭EventLoopGroup,释放所有的资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
/**
* 销毁前滞空对象信息
*/
public void stop() {
logger.info("Destroy Derver Resources");
if (null == channelFuture.channel()) {
logger.error("server channel is null");
}
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
channelFuture.channel().closeFuture().syncUninterruptibly();
bossGroup = null;
workerGroup = null;
channelFuture = null;
}
public int getPort() {
return port;
}
}
| [
"caozhengjie@youbanganda.com"
] | caozhengjie@youbanganda.com |
23939ae56adfc7d45b39ca5b08f9eb276fba01f3 | bfd2c3fd9ca43ad87d9c962568ad755513dee999 | /Lab5/app/src/main/java/hr/mobile/apps/course/lab5/screen/home/HomeActivity.java | d252423787bc14444bd1a727931b94c86aefd4b1 | [] | no_license | maziesmith/MobileAppsCourse | 7fe101c64c46d00553bc1c9ace68658c9c3daf26 | abff842ec882f4a25958b9c01c22a52066c9f55c | refs/heads/master | 2020-12-17T09:35:08.628208 | 2019-06-06T13:23:18 | 2019-06-06T13:23:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,721 | java | package hr.mobile.apps.course.lab5.screen.home;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import hr.mobile.apps.course.lab5.R;
import hr.mobile.apps.course.lab5.model.Book;
import hr.mobile.apps.course.lab5.repository.BookRepository;
import hr.mobile.apps.course.lab5.screen.bookdetails.BookDetailsActivity;
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
BookRepository bookRepository = new BookRepository();
setupRecyclerView(bookRepository.getBooks());
}
/**
* Private methods
*/
private void setupRecyclerView(List<Book> books) {
RecyclerView bookRecyclerView = findViewById(R.id.bookRecyclerView);
// Use a LinearLayoutManager and set it to the RecyclerView
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
bookRecyclerView.setLayoutManager(layoutManager);
// Create a new instance of your custom RecyclerViewAdapter and set it to the RecyclerView
RecyclerView.Adapter adapter = new BookRecyclerViewAdapter(books, (view, position, book) -> openBookDetails(book));
bookRecyclerView.setAdapter(adapter);
}
private void openBookDetails(Book book) {
Intent intent = new Intent(this, BookDetailsActivity.class);
intent.putExtra(BookDetailsActivity.BOOK_ID, book);
startActivity(intent);
}
}
| [
"dominik.koscica@gmail.com"
] | dominik.koscica@gmail.com |
4d4cf66e09ed7ad4d1c72d98964206760d3f3bde | 79332bb7d2f9ddfb31cb6e953008b36cd1ef51ed | /esprit.pfe/esprit.pfe-ejb/src/main/java/esprit/pfe/esprit/pfe/persistence/Etudiant.java | f943ca722b8d32fe5a17af319788a9ce21558780 | [] | no_license | Abderrahmen1395/PI-JSF | e52b5b4d4c575dc44c256c3bad1e57c1f4b39e4b | f21397e003c5f8878efaaefa7c13020dcc81952f | refs/heads/master | 2020-05-20T00:49:04.922735 | 2019-05-07T01:25:13 | 2019-05-07T01:25:13 | 185,295,410 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,839 | java | package esprit.pfe.esprit.pfe.persistence;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Etudiant implements Serializable{
private static final long serialVersionUID = 1L;
private int idEtudiant;
private String nomEtudiant;
private String prenomEtudiant;
private String ecoleEtudiant;
private String emailEtudiant;
private String passwordEtudiant;
private String userNameEtudiant;
private int classenum;
public int getClassenum() {
return classenum;
}
public void setClassenum(int classenum) {
this.classenum = classenum;
}
public String getOptionstudent() {
return optionstudent;
}
public void setOptionstudent(String optionstudent) {
this.optionstudent = optionstudent;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
private String optionstudent;
private boolean creditPedagogiqueEtudiant;
private boolean creditFinaciereEtudiant;
private int autorisationEtudiant;
private int enregistrement;
public int getEnregistrement() {
return enregistrement;
}
public void setEnregistrement(int enregistrement) {
this.enregistrement = enregistrement;
}
private int annulation;
private String msg;
//fiche,encadr,rapporteur fk !!!!!!!!!!!!!!!!!!!!!!
//*********************************************************
//**********************
private FichePfe fiche;
@OneToOne(mappedBy = "etudiant", cascade = CascadeType.REMOVE)
public FichePfe getFiche() {
return fiche;
}
public void setFiche(FichePfe fiche) {
this.fiche = fiche;
}
//****************
private Convention con;
@OneToOne(mappedBy = "etudiant", cascade = CascadeType.REMOVE)
public Convention getCon() {
return con;
}
public void setCon(Convention con) {
this.con =con;
}
//********************
public void setIdEtudiant(int idEtudiant) {
this.idEtudiant = idEtudiant;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
public int getIdEtudiant() {
return idEtudiant;
}
public String getNomEtudiant() {
return nomEtudiant;
}
public void setNomEtudiant(String nomEtudiant) {
this.nomEtudiant = nomEtudiant;
}
public String getPrenomEtudiant() {
return prenomEtudiant;
}
public void setPrenomEtudiant(String prenomEtudiant) {
this.prenomEtudiant = prenomEtudiant;
}
public String getEcoleEtudiant() {
return ecoleEtudiant;
}
public void setEcoleEtudiant(String ecoleEtudiant) {
this.ecoleEtudiant = ecoleEtudiant;
}
public String getEmailEtudiant() {
return emailEtudiant;
}
public void setEmailEtudiant(String emailEtudiant) {
this.emailEtudiant = emailEtudiant;
}
public String getPasswordEtudiant() {
return passwordEtudiant;
}
public void setPasswordEtudiant(String passwordEtudiant) {
this.passwordEtudiant = passwordEtudiant;
}
public String getUserNameEtudiant() {
return userNameEtudiant;
}
public void setUserNameEtudiant(String userNameEtudiant) {
this.userNameEtudiant = userNameEtudiant;
}
public boolean isCreditPedagogiqueEtudiant() {
return creditPedagogiqueEtudiant;
}
public void setCreditPedagogiqueEtudiant(boolean creditPedagogiqueEtudiant) {
this.creditPedagogiqueEtudiant = creditPedagogiqueEtudiant;
}
public boolean isCreditFinaciereEtudiant() {
return creditFinaciereEtudiant;
}
public void setCreditFinaciereEtudiant(boolean creditFinaciereEtudiant) {
this.creditFinaciereEtudiant = creditFinaciereEtudiant;
}
public int getAutorisationEtudiant() {
return autorisationEtudiant;
}
public void setAutorisationEtudiant(int autorisationEtudiant) {
this.autorisationEtudiant = autorisationEtudiant;
}
public Etudiant(int idEtudiant, String nomEtudiant, String prenomEtudiant, String ecoleEtudiant,
String emailEtudiant, String passwordEtudiant, String userNameEtudiant, int classenum,
String optionstudent, boolean creditPedagogiqueEtudiant, boolean creditFinaciereEtudiant) {
super();
this.idEtudiant = idEtudiant;
this.nomEtudiant = nomEtudiant;
this.prenomEtudiant = prenomEtudiant;
this.ecoleEtudiant = ecoleEtudiant;
this.emailEtudiant = emailEtudiant;
this.passwordEtudiant = passwordEtudiant;
this.userNameEtudiant = userNameEtudiant;
this.classenum = classenum;
this.optionstudent = optionstudent;
this.creditPedagogiqueEtudiant = creditPedagogiqueEtudiant;
this.creditFinaciereEtudiant = creditFinaciereEtudiant;
}
public Etudiant(int idEtudiant, String nomEtudiant, String prenomEtudiant, String ecoleEtudiant,
String emailEtudiant, String passwordEtudiant, String userNameEtudiant) {
super();
this.idEtudiant = idEtudiant;
this.nomEtudiant = nomEtudiant;
this.prenomEtudiant = prenomEtudiant;
this.ecoleEtudiant = ecoleEtudiant;
this.emailEtudiant = emailEtudiant;
this.passwordEtudiant = passwordEtudiant;
this.userNameEtudiant = userNameEtudiant;
}
@Override
public String toString() {
return "Etudiant [idEtudiant=" + idEtudiant + ", nomEtudiant=" + nomEtudiant + ", prenomEtudiant="
+ prenomEtudiant + ", ecoleEtudiant=" + ecoleEtudiant + ", emailEtudiant=" + emailEtudiant
+ ", passwordEtudiant=" + passwordEtudiant + ", userNameEtudiant=" + userNameEtudiant
+ ", classeEtudiant=" + classenum + ", optionEtudiant=" + optionstudent
+ ", creditPedagogiqueEtudiant=" + creditPedagogiqueEtudiant + ", creditFinaciereEtudiant="
+ creditFinaciereEtudiant + "]";
}
public Etudiant() {
super();
}
public Etudiant(int idEtudiant, String nomEtudiant, String prenomEtudiant, String ecoleEtudiant,
String emailEtudiant, String passwordEtudiant, String userNameEtudiant, int classenum,
String optionstudent, boolean creditPedagogiqueEtudiant, boolean creditFinaciereEtudiant,
int autorisationEtudiant, Employe employesEnc, Employe employesRappor) {
super();
this.idEtudiant = idEtudiant;
this.nomEtudiant = nomEtudiant;
this.prenomEtudiant = prenomEtudiant;
this.ecoleEtudiant = ecoleEtudiant;
this.emailEtudiant = emailEtudiant;
this.passwordEtudiant = passwordEtudiant;
this.userNameEtudiant = userNameEtudiant;
this.classenum = classenum;
this.optionstudent = optionstudent;
this.creditPedagogiqueEtudiant = creditPedagogiqueEtudiant;
this.creditFinaciereEtudiant = creditFinaciereEtudiant;
this.autorisationEtudiant = autorisationEtudiant;
}
public Etudiant(String nomEtudiant, String prenomEtudiant, String emailEtudiant, String userNameEtudiant,
boolean creditPedagogiqueEtudiant, boolean creditFinaciereEtudiant, int autorisationEtudiant) {
super();
this.nomEtudiant = nomEtudiant;
this.prenomEtudiant = prenomEtudiant;
this.emailEtudiant = emailEtudiant;
this.userNameEtudiant = userNameEtudiant;
this.creditPedagogiqueEtudiant = creditPedagogiqueEtudiant;
this.creditFinaciereEtudiant = creditFinaciereEtudiant;
this.autorisationEtudiant = autorisationEtudiant;
}
public Etudiant(String nomEtudiant, String prenomEtudiant, String ecoleEtudiant, String emailEtudiant,
String userNameEtudiant, boolean creditPedagogiqueEtudiant, boolean creditFinaciereEtudiant,int autorisationEtudiant,
String optionstudent, int classenum) {
super();
this.nomEtudiant = nomEtudiant;
this.prenomEtudiant = prenomEtudiant;
this.ecoleEtudiant = ecoleEtudiant;
this.emailEtudiant = emailEtudiant;
this.userNameEtudiant = userNameEtudiant;
this.creditPedagogiqueEtudiant = creditPedagogiqueEtudiant;
this.creditFinaciereEtudiant = creditFinaciereEtudiant;
this.autorisationEtudiant = autorisationEtudiant;
this.optionstudent = optionstudent;
this.classenum = classenum;
}
public int getAnnulation() {
return annulation;
}
public void setAnnulation(int annulation) {
this.annulation = annulation;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
| [
"LENOVO@192.168.1.106"
] | LENOVO@192.168.1.106 |
cc00833d2ffeb8d0487b361e1af22b2aa5c0b87b | cae5e8e14d5839a36d422c2b988048b8157c307f | /src/main/java/edu/ktlab/evex/util/WordUtil.java | 2539ff4cc86c5d72ee4087cc6dd57f8f55c3d83f | [] | no_license | lupanh/BIOTriggerDetection | cddf97003a232a40acebc1e311888044710e4933 | c617ca98083ef48718cd47e07323f7090cab1b16 | refs/heads/master | 2016-09-05T19:51:00.238418 | 2013-12-01T23:47:39 | 2013-12-01T23:47:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 814 | java | /*******************************************************************************
* Copyright (c) 2013 Mai-Vu Tran.
******************************************************************************/
package edu.ktlab.evex.util;
import org.tartarus.snowball.ext.EnglishStemmer;
import edu.stanford.nlp.util.StringUtils;
public class WordUtil {
public static String wordFeatures(String word) {
if (StringUtils.isPunct(word))
return "PUNCT";
if (StringUtils.isNumeric(word))
return "NUM";
if (StringUtils.isAcronym(word))
return "ALLCAP";
if (StringUtils.isCapitalized(word))
return "CAPT";
return null;
}
public static String stemmerFeature(String token) {
EnglishStemmer stemmer = new EnglishStemmer();
stemmer.setCurrent(token);
stemmer.stem();
return stemmer.getCurrent();
}
}
| [
"lupanh@yahoo.com"
] | lupanh@yahoo.com |
889b6f559cf2433ea83ac8a0769fd16513b4acd9 | aa6ff521d76e331c5eab3030329723d7a5d52b2e | /p4/p4main.java | 4144ae6bbbaec2826ba146b7a40446b789a6cfed | [] | no_license | gyg2104/projecteuler | d35b5a6db0c0997a67be3d547cd65888bf1aa3c7 | 748ca64c11f787021521837c49caf78546fd2c1d | refs/heads/master | 2020-04-08T08:34:22.918515 | 2014-01-08T12:35:46 | 2014-01-08T12:35:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 235 | java | package p4;
public class p4main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
p4calculate mycalc=new p4calculate();
System.out.println(mycalc.findLargestPal());
}
}
| [
"gyg2104@columbia.edu"
] | gyg2104@columbia.edu |
05abbb2a7181005bb1dd3b49eb5ae26760845179 | d3e075ff40a0ce562bc48b818f300ab9965a1798 | /day10-code/src/cn/itcast/day11/demo04/Demo01Multi.java | 3c3e9e267ed28b6ab755b06bfe7d8ba4a7d3f65d | [] | no_license | 18482138228/basic-code | b5099193d233bb3547a1f884256f44fa3d284bd4 | e072f0e393aa90b3b6a46b611a76f6248dd341ca | refs/heads/master | 2022-12-22T09:07:53.368179 | 2020-09-29T06:38:06 | 2020-09-29T06:38:06 | 293,012,624 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 183 | java | package cn.itcast.day11.demo04;
public class Demo01Multi {
public static void main(String[] args) {
Fu fu = new Zi();
fu.method();
fu.methodFu();
}
}
| [
"549297913@qq.com"
] | 549297913@qq.com |
bd7da23f8cdb0082c2cbabece5d22ba93862b3f9 | 5e3cfc138ca45746cbd8ed1fc8eccaa59cd0840b | /Homeless/Android/Homeless_com.positivelymade.homeless_source_from_JADX/com/google/android/gms/ads/internal/client/ac.java | dc1e9f66af3e31f9fc339f1971570f25e2487d9f | [] | no_license | ycourteau/PedagogiqueProjets | 18011979f797bacd5f6b87bd6e6866ebc83752f9 | 7704cf3e431f34b408f874d908132af9aa498c7b | refs/heads/master | 2021-06-27T21:30:17.028954 | 2019-05-08T17:26:29 | 2019-05-08T17:26:29 | 110,717,560 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,091 | java | package com.google.android.gms.ads.internal.client;
import android.content.Context;
import com.google.android.gms.ads.C0427a;
import com.google.android.gms.ads.internal.util.client.C0691b;
import com.google.android.gms.ads.p022a.C0456a;
import com.google.android.gms.ads.p022a.C0458c;
import com.google.android.gms.ads.p022a.C0460e;
import com.google.android.gms.ads.purchase.C0694b;
import com.google.android.gms.ads.purchase.C0696d;
import com.google.android.gms.p028c.bk;
import com.google.android.gms.p028c.dh;
import com.google.android.gms.p028c.et;
import com.google.android.gms.p028c.ex;
public class ac {
private final dh f1419a;
private final Context f1420b;
private final C0520j f1421c;
private C0427a f1422d;
private C0428a f1423e;
private C0490u f1424f;
private String f1425g;
private String f1426h;
private C0456a f1427i;
private C0696d f1428j;
private C0694b f1429k;
private C0460e f1430l;
private C0458c f1431m;
public ac(Context context) {
this(context, C0520j.m2389a(), null);
}
public ac(Context context, C0520j c0520j, C0460e c0460e) {
this.f1419a = new dh();
this.f1420b = context;
this.f1421c = c0520j;
this.f1430l = c0460e;
}
private void m2345b(String str) {
if (this.f1425g == null) {
m2346c(str);
}
this.f1424f = C0526n.m2402b().m2384b(this.f1420b, new AdSizeParcel(), this.f1425g, this.f1419a);
if (this.f1422d != null) {
this.f1424f.mo342a(new C0516f(this.f1422d));
}
if (this.f1423e != null) {
this.f1424f.mo341a(new C0513e(this.f1423e));
}
if (this.f1427i != null) {
this.f1424f.mo343a(new C0524l(this.f1427i));
}
if (this.f1429k != null) {
this.f1424f.mo346a(new et(this.f1429k));
}
if (this.f1428j != null) {
this.f1424f.mo347a(new ex(this.f1428j), this.f1426h);
}
if (this.f1431m != null) {
this.f1424f.mo345a(new bk(this.f1431m));
}
}
private void m2346c(String str) {
if (this.f1424f == null) {
throw new IllegalStateException("The ad unit ID must be set on InterstitialAd before " + str + " is called.");
}
}
public void m2347a(C0427a c0427a) {
try {
this.f1422d = c0427a;
if (this.f1424f != null) {
this.f1424f.mo342a(c0427a != null ? new C0516f(c0427a) : null);
}
} catch (Throwable e) {
C0691b.m3102d("Failed to set the AdListener.", e);
}
}
public void m2348a(C0428a c0428a) {
try {
this.f1423e = c0428a;
if (this.f1424f != null) {
this.f1424f.mo341a(c0428a != null ? new C0513e(c0428a) : null);
}
} catch (Throwable e) {
C0691b.m3102d("Failed to set the AdClickListener.", e);
}
}
public void m2349a(aa aaVar) {
try {
if (this.f1424f == null) {
m2345b("loadAd");
}
if (this.f1424f.mo352a(this.f1421c.m2390a(this.f1420b, aaVar))) {
this.f1419a.m4228a(aaVar.m2316j());
}
} catch (Throwable e) {
C0691b.m3102d("Failed to load ad.", e);
}
}
public void m2350a(String str) {
if (this.f1425g != null) {
throw new IllegalStateException("The ad unit ID can only be set once on InterstitialAd.");
}
this.f1425g = str;
}
public boolean m2351a() {
boolean z = false;
try {
if (this.f1424f != null) {
z = this.f1424f.mo355c();
}
} catch (Throwable e) {
C0691b.m3102d("Failed to check if ad is ready.", e);
}
return z;
}
public void m2352b() {
try {
m2346c("show");
this.f1424f.mo371g();
} catch (Throwable e) {
C0691b.m3102d("Failed to show interstitial.", e);
}
}
}
| [
"ycourteau@collegeshawinigan.qc.ca"
] | ycourteau@collegeshawinigan.qc.ca |
3834666fe721de85c18e8d42a104141b72d6e03b | fff3302fe8193d13360f12e5b13d376ef76cf4d6 | /AppLock/com/google/android/gms/common/util/C2582g.java | 478227ba9d6a0fd40147565d0820d111ba90dd8e | [] | no_license | shaolin-example-com-my-shopify-com/KidWatcher | 2912950b7ca4773c3d29005b9d231ad6035b4912 | f67a81b757043159ea358b7f9e4b16fd6be0e0c0 | refs/heads/master | 2022-04-25T17:19:28.800922 | 2020-04-30T02:53:20 | 2020-04-30T02:53:20 | 260,098,439 | 0 | 0 | null | 2020-04-30T02:51:49 | 2020-04-30T02:51:48 | null | UTF-8 | Java | false | false | 492 | java | package com.google.android.gms.common.util;
import android.os.SystemClock;
public class C2582g implements C2580e {
private static C2582g f7558a = new C2582g();
private C2582g() {
}
public static C2580e m8288d() {
return f7558a;
}
public long mo3360a() {
return System.currentTimeMillis();
}
public long mo3361b() {
return SystemClock.elapsedRealtime();
}
public long mo3362c() {
return System.nanoTime();
}
}
| [
"Nist@netcompany.com"
] | Nist@netcompany.com |
ea27e3815c8690c76d054ea926c81e048651bc46 | e3852bab739ffb7cf8ebc897602cde37d172fe8e | /src/main/java/com/modelplayground/server/utils/StringUtils.java | 43aa0594c27986ee08b59c2d9d56a10f66396093 | [] | no_license | modelplayground/server | 810327426e87511c10eb27fbcacdb9955582e7ee | 8377638ab2e0bb6ae0e017b91b523b3abd0a0b12 | refs/heads/master | 2020-09-13T23:20:10.239088 | 2019-11-28T04:09:20 | 2019-11-28T04:09:20 | 222,936,386 | 0 | 0 | null | 2019-11-25T17:58:30 | 2019-11-20T12:50:10 | Java | UTF-8 | Java | false | false | 3,364 | java | package com.modelplayground.server.utils;
import static java.lang.Math.ceil;
public class StringUtils {
public static String getLexographicMiddleString(String s1,String s2) {
StringBuilder res = new StringBuilder();
if(s1.compareTo(s2)>0) return null;
while (s1.length() < s2.length()) {
s1 += 'a';
}
while (s2.length() < s1.length()) {
s2 += 'a';
}
boolean consChars = false;
int i=0;
while(i<s1.length()){
if( (char)('a'+(s1.charAt(i)+1-'a')%26) == s2.charAt(i) ){
res.append(s1.charAt(i));
consChars = true;
}else if(consChars){
int count = (int)ceil((double)('z'-s1.charAt(i)+s2.charAt(i)-'a')/2);
int charCount = (s1.charAt(i) - 'a') + count;
if(charCount>=26){
res.setCharAt(i-1,(char)(res.charAt(i-1)+1));
}
res.append((char)('a'+charCount%26));
return res.toString();
}else if(s1.charAt(i)==s2.charAt(i)){
res.append(s1.charAt(i));
}else{
if(s1.charAt(i) < s2.charAt(i)){
int count = (int)ceil((double) (s2.charAt(i)-s1.charAt(i)-1)/2);
res.append((char)(s1.charAt(i)+count));
return res.toString();
}else{
return null;
}
}
++i;
}
res.append('m');
return res.toString();
}
public static String increment(String s1,int val) {
StringBuilder str = new StringBuilder(s1);
int i=s1.length()-1;
while(val>0){
long count = val%26;
if('z'-str.charAt(i)>=count){
str.setCharAt(i,(char)(str.charAt(i)+count) );
}else{
if(i-1>=0){
str.setCharAt(i-1,(char)(str.charAt(i-1)+1));
count -= 'z'-str.charAt(i);
str.setCharAt(i,(char)('a'+count-1));
}else{
return null;
}
}
i--;
val/=26;
}
return str.toString();
}
public static String decrement(String s1,int val) {
StringBuilder str = new StringBuilder(s1);
int i=s1.length()-1;
while(val>0){
long count = val%26;
if(str.charAt(i)-'a'>=count){
str.setCharAt(i,(char)(str.charAt(i)-count) );
}else{
if(i-1>=0){
str.setCharAt(i-1,(char)(str.charAt(i-1)-1));
count -= str.charAt(i)-'a';
str.setCharAt(i,(char)('z'-count+1));
}else{
return null;
}
}
i--;
val/=26;
}
return str.toString();
}
public static Integer calculateSpace(String s1,String s2){
int ans = 0;
int mul = 1;
int idx = s1.length()-1;
while(idx>0){
int val1= 'z'-s1.charAt(idx);
int val2= s2.charAt(idx)-'a';
ans+= (val1+val2)*mul;
mul*=26;
idx--;
}
ans+=(s2.charAt(idx)-s1.charAt(idx))*mul;
return ans;
}
}
| [
"modelplayground@gmail.com"
] | modelplayground@gmail.com |
340a2aa3f11901814755ffe6a2b4a075a20dd11e | 6b4d7ebc9ca1dfb90368199ebc044cb0fac48489 | /old client/android/app/src/main/java/com/mychatty/MainApplication.java | c59531142520016bbf64a2fd1ecbe656624b0b51 | [] | no_license | nemanjam/my-chatty | 378f21a0554f5e6f5d398aedf8518343ccc5fc1c | c70ff3138c44505b64edbc96073ec2a644c54d0f | refs/heads/master | 2023-01-10T05:44:57.012337 | 2019-09-13T17:23:14 | 2019-09-13T17:23:14 | 206,859,630 | 0 | 0 | null | 2023-01-04T09:57:01 | 2019-09-06T19:18:14 | JavaScript | UTF-8 | Java | false | false | 1,361 | java | package com.mychatty;
import android.app.Application;
import android.util.Log;
import com.facebook.react.PackageList;
import com.facebook.hermes.reactexecutor.HermesExecutorFactory;
import com.facebook.react.bridge.JavaScriptExecutorFactory;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
| [
"nemanja.mitic.elfak@hotmail.com"
] | nemanja.mitic.elfak@hotmail.com |
92075381f40ba3822b9b69cb6b1823d09739e596 | 521a84d7db50771080dda0a2247cb335da97312b | /src/main/java/rationals/Rational.java | c0d838d33c0f09b287d83484264d9cc4cc79a242 | [] | no_license | brunodibello/Hermit_143456_metamodelado | 59d7eb80f7653c3b09fca87cfe5fc7718a26fe16 | c310f4a8fa9a7f427464672e46d36cc37673f460 | refs/heads/master | 2023-05-29T04:14:53.782465 | 2021-02-26T02:23:44 | 2021-06-13T23:23:19 | 184,952,085 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 916 | java | package rationals;
import java.util.Set;
public interface Rational {
public State addState(boolean var1, boolean var2);
public Set<Object> alphabet();
public Set<State> states();
public Set<State> initials();
public Set<State> terminals();
public Set<State> accessibleStates();
public Set<State> coAccessibleStates();
public Set<State> accessibleAndCoAccessibleStates();
public Set<Transition> delta();
public Set<Transition> delta(State var1, Object var2);
public Set<Transition> delta(State var1);
public Set<Transition> deltaFrom(State var1, State var2);
public Set<Transition> deltaMinusOne(State var1, Object var2);
public boolean addTransition(Transition var1);
public boolean validTransition(Transition var1);
public boolean addTransition(Transition var1, String var2);
public Set<Transition> deltaMinusOne(State var1);
}
| [
"brunodibello@hotmail.com"
] | brunodibello@hotmail.com |
d363db00a86bc4d2fb7745d57afd7208e084e720 | 5768648601c8055c96101d4f2c06ce8b2147b7ff | /DynamicProgramming/152.maximum-product-subarray.java | 7b7288becd5928708f7baf5e434ef7aa698bcde5 | [] | no_license | DreamBlack/leetcode | 8fe317cc80a05e53e1c82f10fa4091020dd2e8bf | f3723df5dbd25b1f4b6faf785f94692fbf792699 | refs/heads/master | 2021-05-13T12:54:27.968346 | 2020-02-22T08:06:48 | 2020-02-22T08:06:48 | 116,615,303 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,817 | java | /*
* @lc app=leetcode id=152 lang=java
*
* [152] Maximum Product Subarray
*
* https://leetcode.com/problems/maximum-product-subarray/description/
*
* algorithms
* Medium (29.97%)
* Likes: 2741
* Dislikes: 120
* Total Accepted: 259.8K
* Total Submissions: 855.2K
* Testcase Example: '[2,3,-2,4]'
*
* Given an integer array nums, find the contiguous subarray within an array
* (containing at least one number) which has the largest product.
*
* Example 1:
*
*
* Input: [2,3,-2,4]
* Output: 6
* Explanation: [2,3] has the largest product 6.
*
*
* Example 2:
*
*
* Input: [-2,0,-1]
* Output: 0
* Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
*
* 解题思路:
* 本题的拦路虎在于连续,思考的时候将很多时间放在了如何处理连续的问题上
* 其实换个角度看对于每个数组无非是二者选择,1是继续累积,2重头开始
*
* 1、本来打算从dfs的角度考虑,后来发现每个分支都要计算多次,遂放弃
*
* 2、dp
* 后来从最长公共子串得到启发,在已知前i-1个数包含第i-1个数的max product
* 已知的情况下求第i个的max product,
* 考虑到前i-1个数的积为正,而第i个数为负的时候,以第i个数为结尾的子数组可能
* 会超过i-1个数为积的子数组,或者个数小于i-1为积的子数组。
* 所以将数组reverse了一遍,取两者结果的最大值。
* 居然通过了,而且速度还挺快
*
* 3、标准解法
*
* tips:
* java对于int[]没有reverse函数,但是对于arraylist有reverse函数。
*/
// @lc code=start
class Solution {
public int maxProduct(int[] nums) {
if (nums.length == 0)
return 0;
int ret = nums[0];
// minproduct和maxproduct分别保存到第i个元素时,构成的子串
// 最小积和最大积
int minproduct = ret, maxproduct = ret;
for (int i = 1; i < nums.length; i++) {
minproduct *= nums[i];
maxproduct *= nums[i];
if (nums[i] < 0) {
int tmp = minproduct;
minproduct = maxproduct;
maxproduct = tmp;
}
// 对于当前元素nums[i],可以选择继续累积,也可以选择重头开始
if (maxproduct < nums[i]) {
maxproduct = nums[i];
}
if (minproduct > nums[i]) {
minproduct = nums[i];
}
ret = Math.max(ret, maxproduct);
}
return ret;
}
public int maxProduct2(int[] nums) {
if (nums.length == 0)
return 0;
return Math.max(help(nums), help(reverseInt(nums)));
}
public int[] reverseInt(int[] nums) {
int[] ret = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
ret[i] = nums[nums.length - 1 - i];
}
return ret;
}
public int help(int[] nums) {
if (nums.length == 0)
return 0;
int[] dp1 = new int[nums.length];
dp1[0] = nums[0];
int[] dp2 = new int[nums.length];
dp2[0] = nums[0];
int ret = dp1[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] >= 0) {
dp1[i] = Math.max(nums[i], nums[i] * dp1[i - 1]);
} else {
dp1[i] = Math.max(Math.max(nums[i] * dp2[i - 1], nums[i] * dp1[i - 1]), nums[i] * nums[i - 1]);
}
if (nums[i] == 0) {
dp2[i] = 0;
} else {
dp2[i] = (dp2[i - 1] == 0) ? nums[i] : nums[i] * dp2[i - 1];
}
if (dp1[i] > ret) {
ret = dp1[i];
}
}
return ret;
}
}
// @lc code=end
| [
"1104122155@qq.com"
] | 1104122155@qq.com |
dd05dfa1fc7b29cf8ca7f902dd906b1f651fce89 | eea9619a86616076731e5ebfaae778bec49d63fe | /src/test/java/com/carpooling/websocket/CarPositionTrackerWebSocketHandlerTest.java | 1b0b48e9f53160dfa20adc348a847873e1dbbd9c | [] | no_license | mihaita-tinta/carpooling-rest | 39a8b45a734a18cf6d50fdf1bb009aa9a90cad65 | c7686ad42742e3100d0970867381e3994f4cbef0 | refs/heads/master | 2020-04-20T19:48:54.938715 | 2019-02-08T15:04:30 | 2019-02-08T15:04:30 | 169,059,645 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,850 | java | package com.carpooling.websocket;
import com.carpooling.security.TokenProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpHeaders;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import org.springframework.web.reactive.socket.client.WebSocketClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.net.URI;
import java.time.Duration;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"logging.level.org.springframework.web=TRACE"},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CarPositionTrackerWebSocketHandlerTest {
private static final Logger log = LoggerFactory.getLogger(CarPositionTrackerWebSocketHandlerTest.class);
@LocalServerPort
int port;
@Autowired
TokenProvider tokenProvider;
@Autowired
@Qualifier("trackingChannel")
SubscribableChannel channel;
private String getAccessToken() {
Collection<? extends GrantedAuthority> authorities =
Stream.of("USER", "ADMIN")
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
User principal = new User("junitus", "password", authorities);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(principal, "pass", authorities);
return "Bearer " + tokenProvider.createToken(authentication);
}
@Test
public void test() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Executors.newScheduledThreadPool(1)
.schedule(() -> {
channel.send(MessageBuilder.withPayload("aaaaa").build());
}, 3, TimeUnit.SECONDS);
WebSocketClient client = new ReactorNettyWebSocketClient();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, getAccessToken());
client.execute(
URI.create("ws://localhost:" + port + "/api/websocket"),
headers,
session -> {
Flux<WebSocketMessage> output = session.receive()
.doOnNext(message -> {
log.info("test - doOnNext: " + message.getPayloadAsText() );
latch.countDown();
})
.map(value -> session.textMessage("Echo " + value));
return session.send(output);
})
.block(Duration.ofSeconds(10));
latch.await();
}
} | [
"mihaita.tinta@ing.com"
] | mihaita.tinta@ing.com |
2dc530bf1c5c73656a2753c95fd2127a9c200ab1 | efd37791871e2b3a589ea85c791825c31a5e8bae | /src/MAIN.java | 96d021dd9142ec9f7e57a4f0bb81c5212c8bbcc5 | [
"MIT"
] | permissive | ChiMuYuan/DouyuDanmu | 9ec3477efe70fa42e92a8687f37747b70bb546f8 | 4bc4f14244eff4f732912d7505ad51efccb5fdc3 | refs/heads/master | 2021-01-25T11:28:37.314009 | 2018-03-05T01:42:56 | 2018-03-05T01:42:56 | 123,402,088 | 0 | 0 | null | 2018-03-01T07:59:33 | 2018-03-01T07:59:33 | null | UTF-8 | Java | false | false | 103 | java | public class MAIN {
public static void main(String[] args) {
System.out.println();
}
}
| [
"MySNN@outlook.com"
] | MySNN@outlook.com |
fa50432ad599df18a13fff1b077bc47b871eae91 | bc4e6d787e39b815ac82440d3d2f9817c463ded8 | /app/src/main/java/com/jqyd/njztc/listview/MaterialHeadView.java | 68938078b9f1c694d7f44c03fe2d043b6c20b960 | [] | no_license | mlycookie/MaterialRefreshLayout | a473aa7c99fb2e62b4624111354916816ef72b1b | 4af09807b7b759cb6c4e077009c502caea6bcbaf | refs/heads/master | 2021-01-13T15:02:54.730534 | 2017-02-07T09:56:41 | 2017-02-07T09:56:41 | 79,425,151 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,190 | java | package com.jqyd.njztc.listview;
import android.content.Context;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.FrameLayout;
public class MaterialHeadView extends FrameLayout implements MaterialHeadListener {
private MaterialWaveView materialWaveView;
private CircleProgressBar circleProgressBar;
private int waveColor;
private int progressTextColor;
private int[] progress_colors;
private int progressStokeWidth;
private boolean isShowArrow,isShowProgressBg;
private int progressValue,progressValueMax;
private int textType;
private int progressBg;
private int progressSize;
private MaterialHeadListener listener;
public MaterialHeadView(Context context) {
this(context, null);
}
public MaterialHeadView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MaterialHeadView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
protected void init(AttributeSet attrs, int defStyle) {
if (isInEditMode()) return;
setClipToPadding(false);
setWillNotDraw(false);
}
public int getWaveColor() {
return waveColor;
}
public void setWaveColor(int waveColor) {
this.waveColor = waveColor;
if(null!= materialWaveView)
{
materialWaveView.setColor( this.waveColor );
}
}
public void setProgressSize(int progressSize)
{
this.progressSize = progressSize;
}
public void setProgressBg(int progressBg)
{
this.progressBg = progressBg;
}
public void setIsProgressBg(boolean isShowProgressBg)
{
this.isShowProgressBg = isShowProgressBg;
}
public void setProgressTextColor(int textColor)
{
this.progressTextColor = textColor;
}
public void setProgressColors(int[] colors)
{
this.progress_colors = colors;
}
public void setTextType(int textType)
{
this.textType = textType;
}
public void setProgressValue(int value)
{
this.progressValue = value;
this.post(new Runnable() {
@Override
public void run() {
if (circleProgressBar != null) {
circleProgressBar.setProgress(progressValue);
}
}
});
}
public void setProgressValueMax(int value)
{
this.progressValueMax = value;
}
public void setProgressStokeWidth(int w)
{
this.progressStokeWidth = w;
}
public void showProgressArrow(boolean isShowArrow)
{
this.isShowArrow = isShowArrow;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
materialWaveView = new MaterialWaveView(getContext());
materialWaveView.setColor(waveColor);
addView(materialWaveView);
circleProgressBar = new CircleProgressBar(getContext());
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(Util.dip2px(getContext(),progressSize), Util.dip2px(getContext(),progressSize));
layoutParams.gravity = Gravity.CENTER;
circleProgressBar.setLayoutParams(layoutParams);
circleProgressBar.setColorSchemeColors(progress_colors);
circleProgressBar.setProgressStokeWidth(progressStokeWidth);
circleProgressBar.setShowArrow(isShowArrow);
circleProgressBar.setShowProgressText(textType == 0);
circleProgressBar.setTextColor(progressTextColor);
circleProgressBar.setProgress(progressValue);
circleProgressBar.setMax(progressValueMax);
circleProgressBar.setCircleBackgroundEnabled(isShowProgressBg);
circleProgressBar.setProgressBackGroundColor(progressBg);
addView(circleProgressBar);
}
@Override
public void onComlete(MaterialRefreshLayout materialRefreshLayout) {
if(materialWaveView != null)
{
materialWaveView.onComlete(materialRefreshLayout);
}
if(circleProgressBar != null)
{
circleProgressBar.onComlete(materialRefreshLayout);
ViewCompat.setTranslationY(circleProgressBar,0);
ViewCompat.setScaleX(circleProgressBar, 0);
ViewCompat.setScaleY(circleProgressBar,0);
}
}
@Override
public void onBegin(MaterialRefreshLayout materialRefreshLayout) {
if(materialWaveView != null)
{
materialWaveView.onBegin(materialRefreshLayout);
}
if(circleProgressBar != null)
{
circleProgressBar.onBegin(materialRefreshLayout);
}
}
@Override
public void onPull(MaterialRefreshLayout materialRefreshLayout, float fraction) {
if(materialWaveView != null)
{
materialWaveView.onPull(materialRefreshLayout, fraction);
}
if(circleProgressBar != null)
{
circleProgressBar.onPull(materialRefreshLayout, fraction);
float a = Util.limitValue(1,fraction);
ViewCompat.setScaleX(circleProgressBar, 1);
ViewCompat.setScaleY(circleProgressBar, 1);
ViewCompat.setAlpha(circleProgressBar, a);
}
}
@Override
public void onRelease(MaterialRefreshLayout materialRefreshLayout, float fraction) {
}
@Override
public void onRefreshing(MaterialRefreshLayout materialRefreshLayout) {
if(materialWaveView != null)
{
materialWaveView.onRefreshing(materialRefreshLayout);
}
if(circleProgressBar != null)
{
circleProgressBar.onRefreshing(materialRefreshLayout);
}
}
// public void scaleView(View v,float a,float b) {
// ObjectAnimator ax = ObjectAnimator.ofFloat(v,"scaleX",a,b);
// ObjectAnimator ay = ObjectAnimator.ofFloat(v,"scaleY",a,b);
// AnimatorSet animSet = new AnimatorSet();
// animSet.play(ax).with(ay);
// animSet.setDuration(200);
// animSet.start();
// }
}
| [
"814432878@qq.com"
] | 814432878@qq.com |
6003d49660c209e63072f70124e3d8420a911b39 | c2548dc2886340b64bd705b6c91cebce8d4059e7 | /src/main/java/com/wupeng/crm/utils/DateTimeUtil.java | 2fd432cc642d732a7956de7ef2c77c0f0d393361 | [] | no_license | wupeng23333/crm | 474f86e24e70bdcc053a25ed7fcd1eae6118839b | acff0ca272921a7d8d185b743f4812db3f1bc9af | refs/heads/master | 2022-12-15T17:42:27.661740 | 2020-09-15T04:30:16 | 2020-09-15T04:30:16 | 293,268,162 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 326 | java | package com.wupeng.crm.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeUtil {
public static String getSysTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf.format(date);
return dateStr;
}
}
| [
"wupeng23333@gmail.com"
] | wupeng23333@gmail.com |
a3989fc2fcb8d4f58fe3d0dafff36b061eac7350 | 2d7dedb72da1ab730d267aafa1d62884dde544b5 | /src/main/java/baro/controller/GuildInfoController.java | e4cd0e7f96869c4bda4a57415bb99b74c75f3afd | [
"Apache-2.0"
] | permissive | BaroDevelopment/PaladinFX | fbf64ba3bef0a2147d2687cf839f2e6587a6da22 | 23c0aa33a489a77242d580eed52cd9dec9722617 | refs/heads/master | 2020-05-19T15:26:27.642113 | 2019-07-16T21:06:25 | 2019-07-16T21:06:25 | 185,084,444 | 6 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,123 | java | package baro.controller;
import baro.JavaApp;
import baro.model.GuildInfoModel;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import net.dv8tion.jda.core.entities.Guild;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Created with IntelliJ IDEA
* User: BaroDevelopment
* Date: 14.05.2019 10:20
*/
public class GuildInfoController implements Initializable {
@FXML
TableView<GuildInfoModel> guildInfoView;
@FXML
TableColumn<GuildInfoModel, String> guildName;
@FXML
TableColumn<GuildInfoModel, String> guildID;
@FXML
TableColumn<GuildInfoModel, String> guildOwner;
@FXML
TableColumn<GuildInfoModel, Integer> guildBotsCount;
@FXML
TableColumn<GuildInfoModel, Integer> guildTotalMembers;
private ObservableList<GuildInfoModel> guildInfoModels = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
//make sure the property value factory is exactly same as the e.g getGuildName from your model class
guildName.setCellValueFactory(new PropertyValueFactory<>("GuildName"));
guildID.setCellValueFactory(new PropertyValueFactory<>("GuildID"));
guildOwner.setCellValueFactory(new PropertyValueFactory<>("GuildOwner"));
guildBotsCount.setCellValueFactory(new PropertyValueFactory<>("GuildBotsCount"));
guildTotalMembers.setCellValueFactory(new PropertyValueFactory<>("GuildTotalMembers"));
// init observable list
for (Guild g : JavaApp.api.getGuilds()) {
int bots = (int) g.getMembers().stream().filter(m -> m.getUser().isBot()).count();
GuildInfoModel m = new GuildInfoModel(g.getName(), g.getId(), g.getOwner().getUser().getName(), bots, g.getMembers().size());
guildInfoModels.add(m);
guildInfoView.getItems().add(m);
}
guildInfoView.setItems(guildInfoModels);
}
}
//
| [
"baris.simonjan@gmail.com"
] | baris.simonjan@gmail.com |
84e079152bb830985f3c028cb0e821ccdcd86f2b | 2d7ca28df14ebd870e783e11988cea55f6283701 | /persistencia_proyectos_construccionReto5/src/main/java/Modelo/dao/Requerimiento_3Dao.java | b14a8b7a610d5ddf1b62638b41c65684e44504f3 | [] | no_license | miguelbart/JavaEstructura-Datos | 324c2f9ab30bc72706058bc17c8b1ef07328b1a1 | 8ec3fe49583ac4a2c3087ccfc5f2f397c32b392f | refs/heads/master | 2023-07-15T12:06:30.000271 | 2021-09-01T02:09:10 | 2021-09-01T02:09:10 | 385,454,169 | 0 | 1 | null | 2021-09-01T02:09:10 | 2021-07-13T02:55:01 | Java | UTF-8 | Java | false | false | 1,860 | java | package Modelo.dao;
//Estructura de datos
import java.util.ArrayList;
//Librerías para SQL y Base de Datos
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//Clase para conexión
import Util.JDBCUtilities;
import Modelo.vo.Requerimiento_3;
public class Requerimiento_3Dao {
//Obtener los 10 proyectos rankeados según las compras
public ArrayList<Requerimiento_3> requerimiento3() throws SQLException {
// Su código
ArrayList<Requerimiento_3> respuesta = new ArrayList<Requerimiento_3>();
Connection conexion = JDBCUtilities.getConnection();
// Su código
try{
String consulta = "Select c.Proveedor, c.Pagado, p.Constructora "+
"From Compra c inner join Proyecto p "+
"on c.ID_Proyecto = p.ID_Proyecto "+
"Where c.Pagado = 'No' AND c.Proveedor = 'JUMBO'; ";
PreparedStatement statement = conexion.prepareStatement(consulta);
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()){
Requerimiento_3 requerimiento_3 = new Requerimiento_3();
requerimiento_3.setProveedor(resultSet.getString("Proveedor"));
requerimiento_3.setPagado(resultSet.getString("Pagado"));
requerimiento_3.setConstructora(resultSet.getString("Constructora"));
respuesta.add(requerimiento_3);
}
resultSet.close();
statement.close();
}catch(SQLException e){
System.out.println("Error consultando " + e);
}finally{
if(conexion != null){
conexion.close();
}
}
return respuesta;
}
}
| [
"miguelbarts@gmail.com"
] | miguelbarts@gmail.com |
f189bfa2d22a6040a4247a29199acc110901d728 | 5619acba68edc3880397a70822bb217d680097dc | /src/main/java/com/monespace/model/DealsCategory.java | 52f2ceadb56a96d43c491c271f4eee3bbb88c524 | [] | no_license | gk100/monespace | 51e198b9fe178fd0e62e42243dc95b4b35aa7879 | 7ee49013eb32d3e815ca83b68bd4f5cd503cd415 | refs/heads/master | 2020-02-26T15:19:45.336648 | 2016-10-29T07:27:18 | 2016-10-29T07:27:18 | 70,221,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,009 | java | package com.monespace.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class DealsCategory implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int dealsCategoryId;
private String dealsCategoryName;
private String dealsCategoryDescription;
public int getdealsCategoryId() {
return dealsCategoryId;
}
public void setdealsCategoryId(int dealsCategoryId) {
this.dealsCategoryId = dealsCategoryId;
}
public String getdealsCategoryName() {
return dealsCategoryName;
}
public void setdealsCategoryName(String dealsCategoryname) {
this.dealsCategoryName = dealsCategoryname;
}
public String getdealsCategoryDescription() {
return dealsCategoryDescription;
}
public void setdealsCategoryDescription(String dealsCategoryDescription) {
this.dealsCategoryDescription = dealsCategoryDescription;
}
}
| [
"kedarssghag@gmail.com"
] | kedarssghag@gmail.com |
da758b14cd1e3a3e45ef9760ff77da91b8e32183 | ab0130f06d681dd6171c91b5851c8db383225ea3 | /java/simple-chat/complete/src/test/java/submission/simplechat/client/FXApplicationTest.java | 7f77e7120b9ec81d02a1e7d90fd02645d4e7cc93 | [] | no_license | mborko/code-examples | 6750f316a26791863e08ac08dba8ae3ec00234d1 | 3ea2be6179f0ed3094c66da0259d021067eb00c2 | refs/heads/master | 2022-10-25T19:36:00.745573 | 2022-10-01T13:57:19 | 2022-10-01T13:57:19 | 43,496,571 | 0 | 13 | null | 2020-10-13T06:47:43 | 2015-10-01T13:00:24 | C | UTF-8 | Java | false | false | 3,345 | java | package submission.simplechat.client;
import javafx.scene.Node;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.testfx.api.FxAssert.verifyThat;
import static org.testfx.matcher.base.NodeMatchers.hasChildren;
import static org.testfx.matcher.base.NodeMatchers.hasText;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.stage.Stage;
import org.testfx.api.FxToolkit;
import org.testfx.framework.junit.ApplicationTest;
import org.loadui.testfx.GuiTest;
import simplechat.client.FXApplication;
/**
* Testing the Client user interface
*
* @author Kai Hoeher {@literal <khoeher@tgm.ac.at>}
* @author Michael Borko {@literal <mborko@tgm.ac.at>}
* @author Hans Brabenetz {@literal <hbrabenetz@tgm.ac.at>}
* @version 1.0
*/
public class FXApplicationTest extends ApplicationTest {
@Override
public void start(Stage stage) throws Exception {
Parent mainNode = FXMLLoader.load(FXApplication.class.getResource("/client.fxml"));
stage.setScene(new Scene(mainNode, 300, 275));
stage.show();
stage.toFront();
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
FxToolkit.hideStage();
release(new KeyCode[]{});
release(new MouseButton[]{});
}
@Test
public void testHasTextArea() {
verifyThat("#grid", hasChildren(1, "#textArea"));
}
@Test
public void testHasTextField() {
verifyThat("#grid", hasChildren(1, "#textField"));
}
@Test
public void testHasHBox() {
verifyThat("#grid", hasChildren(1, "#hBox"));
}
@Test
public void testHasActionTarget() {
verifyThat("#grid", hasChildren(1, "#actionTarget"));
}
@Test
public void testHasButton() {
verifyThat("#hBox", hasChildren(1, "#btn"));
}
@Test
public void testWelcomeMessage() {
verifyThat("#textArea", hasText("Welcome to Simple Chat!"));
}
@Test
public void testSendButtonVisible() {
verifyThat("#btn", Node::isVisible);
}
@Test
public void testSendButtonText() {
verifyThat("#btn", hasText("Send"));
}
@Test
public void testTextFieldEditable() {
TextField txtFld = (TextField) GuiTest.find("#textField");
assert (txtFld.isEditable());
}
@Test
public void testTextAreaVisible() {
verifyThat("#textArea", Node::isVisible);
}
@Test
public void testTextAreaNotEditable() {
TextArea txtArea = (TextArea) GuiTest.find("#textArea");
assert (!txtArea.isEditable());
}
@Test
public void testInput() {
TextField txtFld = (TextField) GuiTest.find("#textField");
clickOn("#textField");
write("This is a test!");
// is not jet a strong test since it only checks what it has written before into the same field
assertThat(txtFld.getText(), is("This is a test!"));
// clickOn("#btn"); // would crash since socket is not up and running
}
}
| [
"michael.borko@tgm.ac.at"
] | michael.borko@tgm.ac.at |
fd1c767b0b11ab7ca916b76d6930b5d7cd8d2df5 | e017648019056fe82306fc5857287dd0de536603 | /rmi-api/src/main/java/com/zd/api/service/UserServiceI.java | abd5044aeefaf31cd988668421c8d369bd75393f | [] | no_license | jieyou-di/rmi-demo | 9a822ac66ff055972fd3ef7b3929d897cec5ba0f | e56524d0909db8f93511c6ff9ff7945cfeb663a4 | refs/heads/master | 2023-07-11T17:47:47.504478 | 2021-08-14T12:50:46 | 2021-08-14T12:50:46 | 396,007,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 257 | java | package com.zd.api.service;
import com.zd.api.pojo.User;
import java.rmi.RemoteException;
/**
* @Description
* @Author 笛
* @create 2021/8/14 10:53
*/
public interface UserServiceI {
User selectUserById(Integer userId) throws RemoteException;
}
| [
"1714090183@qq.com"
] | 1714090183@qq.com |
545a965f6dbb872e1658e56d46f617fd5cdad931 | 8e7185e189f4002ada874f1ece6268b8c6614a36 | /production/src/main/java/xyz/gaoliqing/production/config/PageHelperConfig.java | 43cfb6375053d3779c3e611493d7dc8f3eca186b | [] | no_license | gaoliqing/SpringGO | 25a68bd43bf91c9a39988bd0b6b40a28fbec662e | dc461cb5ad9ba4947ae2254cd5f96f03f334127c | refs/heads/master | 2022-12-11T16:37:37.874245 | 2020-03-31T06:30:51 | 2020-03-31T06:30:51 | 227,730,147 | 11 | 3 | null | 2022-12-06T00:44:40 | 2019-12-13T01:31:20 | Java | UTF-8 | Java | false | false | 1,600 | java | package xyz.gaoliqing.production.config;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* @author Mr.GaoLiqing
* @create 2020-03-26 11:35
* @description
*/
@Configuration
public class PageHelperConfig {
@Bean(name = "pageHelper")
public PageInterceptor pageHelper(){
PageInterceptor pageHelper = new PageInterceptor();
Properties properties = new Properties();
// 默认false,设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用*/
properties.setProperty("offsetAsPageNum","true");
// 默认false,设置为true时,使用RowBounds分页会进行count查询 */
properties.setProperty("rowBoundsWithCount","true");
// 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 */
properties.setProperty("reasonable","true");
// always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page */
properties.setProperty("returnPageInfo","check");
// 支持通过Mapper接口参数来传递分页参数 */
properties.setProperty("supportMethodsArguments","false");
// 配置数据库的方言 */
properties.setProperty("helperDialect","mysql");
pageHelper.setProperties(properties);
return pageHelper;
}
}
| [
"gaoliqing4832@163.com"
] | gaoliqing4832@163.com |
c880690b9d2cfe1fb634d27c2fe8cb56734fc82c | af0c4995d4bf5f76a6ca283fc55dfdca4e52ca3a | /program/src/main/java/com/whaley/biz/program/playersupport/component/normalplayer/tv/TVComponent.java | 1e5a8b9a46b7c85de8820ea5a0fae11a2600b8f8 | [] | no_license | portal-io/portal-android | da60c4a7d54fb56fbc983c635bb1d2c4d542f78e | 623757fbb4d7979745b4c8ee34cebbf395cbd249 | refs/heads/master | 2020-03-20T07:58:08.196164 | 2019-03-16T02:30:48 | 2019-03-16T02:30:48 | 137,295,692 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 544 | java | package com.whaley.biz.program.playersupport.component.normalplayer.tv;
import com.whaley.biz.playerui.component.BaseComponent;
import com.whaley.biz.playerui.component.BaseController;
import com.whaley.biz.playerui.component.BaseUIAdapter;
/**
* Created by YangZhi on 2017/8/23 16:58.
*/
public class TVComponent extends BaseComponent{
@Override
protected BaseController onCreateController() {
return new TVController();
}
@Override
protected BaseUIAdapter onCreateUIAdapter() {
return null;
}
}
| [
"lizs@snailvr.com"
] | lizs@snailvr.com |
541599b6f0ec979b34a4f2281f77119a4fa6b13e | e0f43f01f720ab4d92ba48b4f86d4a2e71eca2e5 | /app/src/main/java/com/example/a1nf0rmed/myapplication/LoginActivity.java | b9bd183c29edb19c9a2630c13359e386078d2b71 | [] | no_license | 1nF0rmed/EmergencyApp | 1f76857077937779b80d7547c374222c2df4d5b9 | 4eee6632aa4815b730f89847cff9f27b10566e67 | refs/heads/master | 2020-04-22T05:40:06.362399 | 2019-03-09T10:50:27 | 2019-03-09T10:50:27 | 170,163,918 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,275 | java | package com.example.a1nf0rmed.myapplication;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
| [
"prkinformed@gmail.com"
] | prkinformed@gmail.com |
48fa92ffca27439c3beac6be3e889009d27f5ea5 | 8d275e1f948112af96c1ccf63261b36db8363a0b | /src/test/java/org/basex/test/io/IOTest.java | c92c57fa0bd98bf02aa790d2053b192ba1937c3b | [
"BSD-3-Clause"
] | permissive | yzzo/basex | 038ae9a30021cea6c1971aa281c2df6400c3d4e2 | d38d2755fad977de7cfbe57bbd1976c748620340 | refs/heads/master | 2020-04-07T22:54:48.311512 | 2011-10-03T21:06:16 | 2011-10-03T21:06:16 | 2,318,527 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 872 | java | package org.basex.test.io;
import static org.junit.Assert.*;
import org.basex.io.IO;
import org.basex.io.IOFile;
import org.basex.io.IOUrl;
import org.junit.Test;
/**
* Test class for IO methods.
*
* @author BaseX Team 2005-11, BSD License
* @author Christian Gruen
*/
public final class IOTest {
/** URL to file conversions. */
@Test
public void urlToFile() {
assertEquals("/x", IOUrl.file("file:/x"));
assertEquals("c:/x y", IOUrl.file("file:/c:/x%20y"));
assertEquals("c:/x y", IOUrl.file("file:/c:/x y"));
assertEquals("D:/x+y", IOUrl.file("file:///D:/x%2By"));
assertEquals("/GG:/X", IOUrl.file("file:///GG:/X"));
}
/** File to URL conversions. */
@Test
public void fileToURL() {
final String url = new IOFile("X Y").url();
assertTrue(url.startsWith(IO.FILEPREF + '/'));
assertTrue(url.endsWith("X%20Y"));
}
}
| [
"'christian.gruen@gmail.com'"
] | 'christian.gruen@gmail.com' |
7964fa3312622d42eba35b36b276fbd305c4475f | 586760916c55a2537ea146d3d077977626bdeb31 | /test/java/com/epam/automation/listeners/TestListeners.java | 8d816f76b5a056d499d39e4a53f36238589c6e0c | [] | no_license | Nastassia123/CalculatorTask5_2 | 539216e2fe528311bac7aebafdc27b73bd00798d | dfbc8b908abca70bd1c6c4a368ebcbf476d9cf6d | refs/heads/master | 2022-04-21T18:22:37.054438 | 2020-04-14T17:22:06 | 2020-04-14T17:22:06 | 255,675,927 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 989 | java | package com.epam.automation.listeners;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import static com.sun.xml.internal.ws.spi.db.BindingContextFactory.LOGGER;
public class TestListeners implements ITestListener {
@Override
public void onTestStart(ITestResult result) {
LOGGER.info("On Test Start " + result.getName());
}
@Override
public void onTestSuccess(ITestResult result) {
LOGGER.info("On Test Success " + result.getName());
}
@Override
public void onTestFailure(ITestResult result) {
LOGGER.info("On Test Failed " + result.getName());
}
@Override
public void onTestSkipped(ITestResult iTestResult) {
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {
}
@Override
public void onStart(ITestContext context) {
}
@Override
public void onFinish(ITestContext context) {
}
}
| [
"Nastassia_Chaliapina@epam.com"
] | Nastassia_Chaliapina@epam.com |
7da92e97db7d55252e90b472be2394f1cc040371 | f652d1377f22f5009e0ca34a7bb5e90a57172db7 | /backend/src/main/java/br/com/ivanfsilva/ecommerce/model/Categoria.java | 875c0c335b016a8b9a9d3755ab31e9ed1b2f98db | [] | no_license | ivanfsilva/ecommerce | b53b25fe2c894886482828203aba003cafcfe59e | 4f71bb3d94efce7a297b10f0b185d87ec6db27ad | refs/heads/master | 2022-05-24T15:34:15.791657 | 2022-05-10T21:39:51 | 2022-05-10T21:39:51 | 244,218,369 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 835 | java | package br.com.ivanfsilva.ecommerce.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.List;
@Getter
@Setter
@Entity
@Table(name = "categoria",
uniqueConstraints = { @UniqueConstraint(name = "unq_nome", columnNames = { "nome" }) })
public class Categoria extends EntidadeBaseInteger {
@NotBlank
@Column(length = 100, nullable = false)
private String nome;
@ManyToOne
@JoinColumn(name = "categoria_pai_id",
foreignKey = @ForeignKey(name = "fk_categoria_categoriapai"))
private Categoria categoriaPai;
@OneToMany(mappedBy = "categoriaPai")
private List<Categoria> categorias;
@ManyToMany(mappedBy = "categorias")
private List<Produto> produtos;
} | [
"ivanfs27@gmail.com"
] | ivanfs27@gmail.com |
76a2a3dfb96a2458f461a2092eb007ae6cda3806 | 66e2f35b7b56865552616cf400e3a8f5928d12a2 | /src/main/java/com/alipay/api/domain/ZhimaCustomerCertificationCertifyModel.java | 8788d586533b78a30072dcd11a692b81b40779a6 | [
"Apache-2.0"
] | permissive | xiafaqi/alipay-sdk-java-all | 18dc797400847c7ae9901566e910527f5495e497 | 606cdb8014faa3e9125de7f50cbb81b2db6ee6cc | refs/heads/master | 2022-11-25T08:43:11.997961 | 2020-07-23T02:58:22 | 2020-07-23T02:58:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 642 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 芝麻认证开始认证
*
* @author auto create
* @since 1.0, 2018-08-29 14:42:03
*/
public class ZhimaCustomerCertificationCertifyModel extends AlipayObject {
private static final long serialVersionUID = 4688623347644377123L;
/**
* 一次认证的唯一标识,在完成芝麻认证初始化后可以获取
*/
@ApiField("biz_no")
private String bizNo;
public String getBizNo() {
return this.bizNo;
}
public void setBizNo(String bizNo) {
this.bizNo = bizNo;
}
}
| [
"ben.zy@antfin.com"
] | ben.zy@antfin.com |
3ac779ba3a3f39854de3a3d965a634d7f32d0e49 | 61602d4b976db2084059453edeafe63865f96ec5 | /com/xunlei/downloadprovider/download/openwith/e.java | 4bfc420cdc894e01bc0e812f5c50431bcd3baf5c | [] | no_license | ZoranLi/thunder | 9d18fd0a0ec0a5bb3b3f920f9413c1ace2beb4d0 | 0778679ef03ba1103b1d9d9a626c8449b19be14b | refs/heads/master | 2020-03-20T23:29:27.131636 | 2018-06-19T06:43:26 | 2018-06-19T06:43:26 | 137,848,886 | 12 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,531 | java | package com.xunlei.downloadprovider.download.openwith;
import android.content.Context;
import com.xunlei.common.androidutil.OSUtil;
import com.xunlei.common.businessutil.XLFileTypeUtil;
import com.xunlei.downloadprovider.download.d.d.a;
import com.xunlei.downloadprovider.download.d.f;
import com.xunlei.downloadprovider.download.downloadvod.TaskPlayInfo;
import com.xunlei.downloadprovider.vodnew.VodPlayerActivityNew;
/* compiled from: LocalFileOpenHelper */
final class e implements a {
final /* synthetic */ Context a;
e(Context context) {
this.a = context;
}
public final void a(f fVar, String str) {
if (!(fVar == null || fVar.c == null)) {
Context context = this.a;
fVar = fVar.c;
if (fVar == null || !fVar.activityInfo.packageName.equals(OSUtil.getCurProcessName(context))) {
fVar = c.a().a(context, str, fVar);
if (fVar != null) {
fVar.addFlags(67108864);
context.startActivity(fVar);
}
} else if (XLFileTypeUtil.isLocalVodSupport(str) != null) {
fVar = str.contains("/") != null ? str.substring(str.lastIndexOf("/") + 1) : str;
TaskPlayInfo taskPlayInfo = new TaskPlayInfo(str);
taskPlayInfo.mTitle = fVar;
VodPlayerActivityNew.a(context, taskPlayInfo, "app_other", null, true, 0, null);
}
}
d.a();
}
public final void a() {
d.a();
}
}
| [
"lizhangliao@xiaohongchun.com"
] | lizhangliao@xiaohongchun.com |
d50fbaac8e8b64e2f4d4061723726a711c37a026 | f3c0028d4138c69c4ce24b2fd01e4ca595a6af4d | /app/src/main/java/com/siweisoft/util/hellocharts/animation/ChartAnimationListener.java | 23f814ed8fb1241ce8aacfec69ef145b67a01ae3 | [] | no_license | canvaser/desktop | 83138fa37b36a02d4663d5e9cb136313f501a43e | 7652ece27d050d627c95fe0934734bf05db2cb0e | refs/heads/master | 2021-01-13T03:09:42.346997 | 2017-02-07T01:43:59 | 2017-02-07T01:43:59 | 77,433,645 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 427 | java | package com.siweisoft.util.hellocharts.animation;
import java.util.EventListener;
/**
* Listener used to listen for chart animation start and stop events. Implementations of this interface can be used for
* all types of chart animations(data, viewport, PieChart rotation).
*/
public interface ChartAnimationListener extends EventListener {
public void onAnimationStarted();
public void onAnimationFinished();
}
| [
"18721607438@163.com"
] | 18721607438@163.com |
c70f41431b45952b71533ed3bed5abcce78ca5af | f2271ff8b8fedc3e095973fcfe5d522b6e27c1d9 | /h2/src/test/org/h2/test/db/TestSpatial.java | 834ca48bfe70492ab6bad5da79713caca519cf00 | [] | no_license | AngelMalaga/ProyectoCuentas | 1edbfbc6dd497ccacceeaae155e79c948254ebc6 | f88173f5120f553d205b75f9abdbe64a3ce8fbe0 | refs/heads/master | 2023-03-11T20:03:15.583339 | 2021-03-05T01:44:37 | 2021-03-05T01:44:37 | 344,307,324 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 42,527 | java | /*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.db;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Types;
import java.util.Random;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.util.AffineTransformation;
import org.h2.api.Aggregate;
import org.h2.test.TestBase;
import org.h2.tools.SimpleResultSet;
import org.h2.tools.SimpleRowSource;
import org.h2.value.DataType;
import org.h2.value.Value;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.h2.value.ValueGeometry;
/**
* Spatial datatype and index tests.
*
* @author Thomas Mueller
* @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public class TestSpatial extends TestBase {
private static final String URL = "spatial";
/**
* Run just this test.
*
* @param a ignored
*/
public static void main(String... a) throws Exception {
TestBase.createCaller().init().test();
}
@Override
public void test() throws SQLException {
if (!config.mvStore && config.mvcc) {
return;
}
if (config.memory && config.mvcc) {
return;
}
if (DataType.GEOMETRY_CLASS != null) {
deleteDb("spatial");
testSpatial();
deleteDb("spatial");
}
}
private void testSpatial() throws SQLException {
testBug1();
testSpatialValues();
testOverlap();
testNotOverlap();
testPersistentSpatialIndex();
testSpatialIndexQueryMultipleTable();
testIndexTransaction();
testJavaAlias();
testJavaAliasTableFunction();
testMemorySpatialIndex();
testGeometryDataType();
testWKB();
testValueConversion();
testEquals();
testTableFunctionGeometry();
testHashCode();
testAggregateWithGeometry();
testTableViewSpatialPredicate();
testValueGeometryScript();
testInPlaceUpdate();
testScanIndexOnNonSpatialQuery();
testStoreCorruption();
testExplainSpatialIndexWithPk();
testNullableGeometry();
testNullableGeometryDelete();
testNullableGeometryInsert();
testNullableGeometryUpdate();
}
private void testBug1() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE VECTORS (ID INTEGER NOT NULL, GEOM GEOMETRY, S INTEGER)");
stat.execute("INSERT INTO VECTORS(ID, GEOM, S) " +
"VALUES(0, 'POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))', 1)");
stat.executeQuery("select * from (select * from VECTORS) WHERE S=1 " +
"AND GEOM && 'POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))'");
conn.close();
deleteDb("spatial");
}
private void testHashCode() {
ValueGeometry geomA = ValueGeometry
.get("POLYGON ((67 13 6, 67 18 5, 59 18 4, 59 13 6, 67 13 6))");
ValueGeometry geomB = ValueGeometry
.get("POLYGON ((67 13 6, 67 18 5, 59 18 4, 59 13 6, 67 13 6))");
ValueGeometry geomC = ValueGeometry
.get("POLYGON ((67 13 6, 67 18 5, 59 18 4, 59 13 5, 67 13 6))");
assertEquals(geomA.hashCode(), geomB.hashCode());
assertFalse(geomA.hashCode() == geomC.hashCode());
}
private void testSpatialValues() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("create memory table test" +
"(id int primary key, polygon geometry)");
stat.execute("insert into test values(1, " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))')");
ResultSet rs = stat.executeQuery("select * from test");
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertEquals("POLYGON ((1 1, 1 2, 2 2, 1 1))", rs.getString(2));
GeometryFactory f = new GeometryFactory();
Polygon polygon = f.createPolygon(new Coordinate[] {
new Coordinate(1, 1),
new Coordinate(1, 2),
new Coordinate(2, 2),
new Coordinate(1, 1) });
assertTrue(polygon.equals(rs.getObject(2)));
rs = stat.executeQuery("select * from test where polygon = " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))'");
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
stat.executeQuery("select * from test where polygon > " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))'");
stat.executeQuery("select * from test where polygon < " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))'");
stat.execute("drop table test");
conn.close();
deleteDb("spatial");
}
/**
* Generate a random line string under the given bounding box.
*
* @param geometryRand the random generator
* @param minX Bounding box min x
* @param maxX Bounding box max x
* @param minY Bounding box min y
* @param maxY Bounding box max y
* @param maxLength LineString maximum length
* @return A segment within this bounding box
*/
static Geometry getRandomGeometry(Random geometryRand,
double minX, double maxX,
double minY, double maxY, double maxLength) {
GeometryFactory factory = new GeometryFactory();
// Create the start point
Coordinate start = new Coordinate(
geometryRand.nextDouble() * (maxX - minX) + minX,
geometryRand.nextDouble() * (maxY - minY) + minY);
// Compute an angle
double angle = geometryRand.nextDouble() * Math.PI * 2;
// Compute length
double length = geometryRand.nextDouble() * maxLength;
// Compute end point
Coordinate end = new Coordinate(
start.x + Math.cos(angle) * length,
start.y + Math.sin(angle) * length);
return factory.createLineString(new Coordinate[] { start, end });
}
private void testOverlap() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("create memory table test" +
"(id int primary key, poly geometry)");
stat.execute("insert into test values(1, " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))')");
stat.execute("insert into test values(2, " +
"'POLYGON ((3 1, 3 2, 4 2, 3 1))')");
stat.execute("insert into test values(3, " +
"'POLYGON ((1 3, 1 4, 2 4, 1 3))')");
ResultSet rs = stat.executeQuery(
"select * from test " +
"where poly && 'POINT (1.5 1.5)'::Geometry");
assertTrue(rs.next());
assertEquals(1, rs.getInt("id"));
assertFalse(rs.next());
stat.execute("drop table test");
} finally {
conn.close();
}
}
private void testPersistentSpatialIndex() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("create table test" +
"(id int primary key, poly geometry)");
stat.execute("insert into test values(1, " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))')");
stat.execute("insert into test values(2,null)");
stat.execute("insert into test values(3, " +
"'POLYGON ((3 1, 3 2, 4 2, 3 1))')");
stat.execute("insert into test values(4,null)");
stat.execute("insert into test values(5, " +
"'POLYGON ((1 3, 1 4, 2 4, 1 3))')");
stat.execute("create spatial index on test(poly)");
ResultSet rs = stat.executeQuery(
"select * from test " +
"where poly && 'POINT (1.5 1.5)'::Geometry");
assertTrue(rs.next());
assertEquals(1, rs.getInt("id"));
assertFalse(rs.next());
rs.close();
// Test with multiple operator
rs = stat.executeQuery(
"select * from test " +
"where poly && 'POINT (1.5 1.5)'::Geometry " +
"AND poly && 'POINT (1.7 1.75)'::Geometry");
assertTrue(rs.next());
assertEquals(1, rs.getInt("id"));
assertFalse(rs.next());
rs.close();
} finally {
// Close the database
conn.close();
}
if (config.memory) {
return;
}
conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(
"select * from test " +
"where poly && 'POINT (1.5 1.5)'::Geometry");
assertTrue(rs.next());
assertEquals(1, rs.getInt("id"));
assertFalse(rs.next());
stat.execute("drop table test");
} finally {
conn.close();
}
}
private void testNotOverlap() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("create memory table test" +
"(id int primary key, poly geometry)");
stat.execute("insert into test values(1, " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))')");
stat.execute("insert into test values(2,null)");
stat.execute("insert into test values(3, " +
"'POLYGON ((3 1, 3 2, 4 2, 3 1))')");
stat.execute("insert into test values(4,null)");
stat.execute("insert into test values(5, " +
"'POLYGON ((1 3, 1 4, 2 4, 1 3))')");
ResultSet rs = stat.executeQuery(
"select * from test " +
"where NOT poly && 'POINT (1.5 1.5)'::Geometry");
assertTrue(rs.next());
assertEquals(3, rs.getInt("id"));
assertTrue(rs.next());
assertEquals(5, rs.getInt("id"));
assertFalse(rs.next());
stat.execute("drop table test");
} finally {
conn.close();
}
}
private static void createTestTable(Statement stat) throws SQLException {
stat.execute("create table area(idArea int primary key, the_geom geometry)");
stat.execute("create spatial index on area(the_geom)");
stat.execute("insert into area values(1, " +
"'POLYGON ((-10 109, 90 109, 90 9, -10 9, -10 109))')");
stat.execute("insert into area values(2, " +
"'POLYGON ((90 109, 190 109, 190 9, 90 9, 90 109))')");
stat.execute("insert into area values(3, " +
"'POLYGON ((190 109, 290 109, 290 9, 190 9, 190 109))')");
stat.execute("insert into area values(4, " +
"'POLYGON ((-10 9, 90 9, 90 -91, -10 -91, -10 9))')");
stat.execute("insert into area values(5, " +
"'POLYGON ((90 9, 190 9, 190 -91, 90 -91, 90 9))')");
stat.execute("insert into area values(6, " +
"'POLYGON ((190 9, 290 9, 290 -91, 190 -91, 190 9))')");
stat.execute("insert into area values(7,null)");
stat.execute("insert into area values(8,null)");
stat.execute("create table roads(idRoad int primary key, the_geom geometry)");
stat.execute("create spatial index on roads(the_geom)");
stat.execute("insert into roads values(1, " +
"'LINESTRING (27.65595463138 -16.728733459357244, " +
"47.61814744801515 40.435727788279806)')");
stat.execute("insert into roads values(2, " +
"'LINESTRING (17.674858223062415 55.861058601134246, " +
"55.78449905482046 76.73062381852554)')");
stat.execute("insert into roads values(3, " +
"'LINESTRING (68.48771266540646 67.65689981096412, " +
"108.4120982986768 88.52646502835542)')");
stat.execute("insert into roads values(4, " +
"'LINESTRING (177.3724007561437 18.65879017013235, " +
"196.4272211720227 -16.728733459357244)')");
stat.execute("insert into roads values(5, " +
"'LINESTRING (106.5973534971645 -12.191871455576518, " +
"143.79962192816637 30.454631379962223)')");
stat.execute("insert into roads values(6, " +
"'LINESTRING (144.70699432892252 55.861058601134246, " +
"150.1512287334594 83.9896030245747)')");
stat.execute("insert into roads values(7, " +
"'LINESTRING (60.321361058601155 -13.099243856332663, " +
"149.24385633270325 5.955576559546344)')");
stat.execute("insert into roads values(8, null)");
stat.execute("insert into roads values(9, null)");
}
private void testSpatialIndexQueryMultipleTable() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
createTestTable(stat);
testRoadAndArea(stat);
} finally {
// Close the database
conn.close();
}
deleteDb("spatial");
}
private void testRoadAndArea(Statement stat) throws SQLException {
ResultSet rs = stat.executeQuery(
"select idArea, COUNT(idRoad) roadCount " +
"from area, roads " +
"where area.the_geom && roads.the_geom " +
"GROUP BY idArea ORDER BY idArea");
assertTrue(rs.next());
assertEquals(1, rs.getInt("idArea"));
assertEquals(3, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(2, rs.getInt("idArea"));
assertEquals(4, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(3, rs.getInt("idArea"));
assertEquals(1, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(4, rs.getInt("idArea"));
assertEquals(2, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(5, rs.getInt("idArea"));
assertEquals(3, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(6, rs.getInt("idArea"));
assertEquals(1, rs.getInt("roadCount"));
assertFalse(rs.next());
rs.close();
}
private void testIndexTransaction() throws SQLException {
// Check session management in index
deleteDb("spatial");
Connection conn = getConnection(URL);
conn.setAutoCommit(false);
try {
Statement stat = conn.createStatement();
createTestTable(stat);
Savepoint sp = conn.setSavepoint();
// Remove a row but do not commit
stat.execute("delete from roads where idRoad=9");
stat.execute("delete from roads where idRoad=7");
// Check if index is updated
ResultSet rs = stat.executeQuery(
"select idArea, COUNT(idRoad) roadCount " +
"from area, roads " +
"where area.the_geom && roads.the_geom " +
"GROUP BY idArea ORDER BY idArea");
assertTrue(rs.next());
assertEquals(1, rs.getInt("idArea"));
assertEquals(3, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(2, rs.getInt("idArea"));
assertEquals(4, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(3, rs.getInt("idArea"));
assertEquals(1, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(4, rs.getInt("idArea"));
assertEquals(1, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(5, rs.getInt("idArea"));
assertEquals(2, rs.getInt("roadCount"));
assertTrue(rs.next());
assertEquals(6, rs.getInt("idArea"));
assertEquals(1, rs.getInt("roadCount"));
assertFalse(rs.next());
rs.close();
conn.rollback(sp);
// Check if the index is restored
testRoadAndArea(stat);
} finally {
conn.close();
}
}
/**
* Test the in the in-memory spatial index
*/
private void testMemorySpatialIndex() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("create memory table test(id int primary key, polygon geometry)");
stat.execute("create spatial index idx_test_polygon on test(polygon)");
stat.execute("insert into test values(1, 'POLYGON ((1 1, 1 2, 2 2, 1 1))')");
stat.execute("insert into test values(2, null)");
ResultSet rs;
// an query that can not possibly return a result
rs = stat.executeQuery("select * from test " +
"where polygon && 'POLYGON ((1 1, 1 2, 2 2, 1 1))'::Geometry " +
"and polygon && 'POLYGON ((10 10, 10 20, 20 20, 10 10))'::Geometry");
assertFalse(rs.next());
rs = stat.executeQuery(
"explain select * from test " +
"where polygon && 'POLYGON ((1 1, 1 2, 2 2, 1 1))'::Geometry");
rs.next();
if (config.mvStore) {
assertContains(rs.getString(1), "/* PUBLIC.IDX_TEST_POLYGON: POLYGON &&");
}
// TODO equality should probably also use the spatial index
// rs = stat.executeQuery("explain select * from test " +
// "where polygon = 'POLYGON ((1 1, 1 2, 2 2, 1 1))'");
// rs.next();
// assertContains(rs.getString(1),
// "/* PUBLIC.IDX_TEST_POLYGON: POLYGON =");
// these queries actually have no meaning in the context of a spatial
// index, but
// check them anyhow
stat.executeQuery("select * from test where polygon > " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))'::Geometry");
stat.executeQuery("select * from test where polygon < " +
"'POLYGON ((1 1, 1 2, 2 2, 1 1))'::Geometry");
rs = stat.executeQuery(
"select * from test " +
"where intersects(polygon, 'POLYGON ((1 1, 1 2, 2 2, 1 1))')");
assertTrue(rs.next());
rs = stat.executeQuery(
"select * from test " +
"where intersects(polygon, 'POINT (1 1)')");
assertTrue(rs.next());
rs = stat.executeQuery(
"select * from test " +
"where intersects(polygon, 'POINT (0 0)')");
assertFalse(rs.next());
stat.execute("drop table test");
conn.close();
deleteDb("spatial");
}
/**
* Test java alias with Geometry type.
*/
private void testJavaAlias() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS T_GEOM_FROM_TEXT FOR \"" +
TestSpatial.class.getName() + ".geomFromText\"");
stat.execute("create table test(id int primary key " +
"auto_increment, the_geom geometry)");
stat.execute("insert into test(the_geom) values(" +
"T_GEOM_FROM_TEXT('POLYGON ((" +
"62 48, 84 48, 84 42, 56 34, 62 48))',1488))");
stat.execute("DROP ALIAS T_GEOM_FROM_TEXT");
ResultSet rs = stat.executeQuery("select the_geom from test");
assertTrue(rs.next());
assertEquals("POLYGON ((62 48, 84 48, 84 42, 56 34, 62 48))",
rs.getObject(1).toString());
} finally {
conn.close();
}
deleteDb("spatial");
}
/**
* Test java alias with Geometry type.
*/
private void testJavaAliasTableFunction() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS T_RANDOM_GEOM_TABLE FOR \"" +
TestSpatial.class.getName() + ".getRandomGeometryTable\"");
stat.execute(
"create table test as " +
"select * from T_RANDOM_GEOM_TABLE(42,20,-100,100,-100,100,4)");
stat.execute("DROP ALIAS T_RANDOM_GEOM_TABLE");
ResultSet rs = stat.executeQuery("select count(*) from test");
assertTrue(rs.next());
assertEquals(20, rs.getInt(1));
} finally {
conn.close();
}
deleteDb("spatial");
}
/**
* Generate a result set with random geometry data.
* Used as an ALIAS function.
*
* @param seed the random seed
* @param rowCount the number of rows
* @param minX the smallest x
* @param maxX the largest x
* @param minY the smallest y
* @param maxY the largest y
* @param maxLength the maximum length
* @return a result set
*/
public static ResultSet getRandomGeometryTable(
final long seed, final long rowCount,
final double minX, final double maxX,
final double minY, final double maxY, final double maxLength) {
SimpleResultSet rs = new SimpleResultSet(new SimpleRowSource() {
private final Random random = new Random(seed);
private int currentRow;
@Override
public Object[] readRow() throws SQLException {
if (currentRow++ < rowCount) {
return new Object[] {
getRandomGeometry(random,
minX, maxX, minY, maxY, maxLength) };
}
return null;
}
@Override
public void close() {
// nothing to do
}
@Override
public void reset() throws SQLException {
random.setSeed(seed);
}
});
rs.addColumn("the_geom", Types.OTHER, "GEOMETRY", Integer.MAX_VALUE, 0);
return rs;
}
/**
* Convert the text to a geometry object.
*
* @param text the geometry as a Well Known Text
* @param srid the projection id
* @return Geometry object
*/
public static Geometry geomFromText(String text, int srid) throws SQLException {
WKTReader wktReader = new WKTReader();
try {
Geometry geom = wktReader.read(text);
geom.setSRID(srid);
return geom;
} catch (ParseException ex) {
throw new SQLException(ex);
}
}
private void testGeometryDataType() {
GeometryFactory geometryFactory = new GeometryFactory();
Geometry geometry = geometryFactory.createPoint(new Coordinate(0, 0));
assertEquals(Value.GEOMETRY, DataType.getTypeFromClass(geometry.getClass()));
}
/**
* Test serialization of Z and SRID values.
*/
private void testWKB() {
ValueGeometry geom3d = ValueGeometry.get(
"POLYGON ((67 13 6, 67 18 5, 59 18 4, 59 13 6, 67 13 6))", 27572);
ValueGeometry copy = ValueGeometry.get(geom3d.getBytes());
assertEquals(6, copy.getGeometry().getCoordinates()[0].z);
assertEquals(5, copy.getGeometry().getCoordinates()[1].z);
assertEquals(4, copy.getGeometry().getCoordinates()[2].z);
// Test SRID
copy = ValueGeometry.get(geom3d.getBytes());
assertEquals(27572, copy.getGeometry().getSRID());
}
/**
* Test conversion of Geometry object into Object
*/
private void testValueConversion() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS OBJ_STRING FOR \"" +
TestSpatial.class.getName() +
".getObjectString\"");
ResultSet rs = stat.executeQuery(
"select OBJ_STRING('POINT( 15 25 )'::geometry)");
assertTrue(rs.next());
assertEquals("POINT (15 25)", rs.getString(1));
conn.close();
deleteDb("spatial");
}
/**
* Get the toString value of the object.
*
* @param object the object
* @return the string representation
*/
public static String getObjectString(Object object) {
return object.toString();
}
/**
* Test equality method on ValueGeometry
*/
private void testEquals() {
// 3d equality test
ValueGeometry geom3d = ValueGeometry.get(
"POLYGON ((67 13 6, 67 18 5, 59 18 4, 59 13 6, 67 13 6))");
ValueGeometry geom2d = ValueGeometry.get(
"POLYGON ((67 13, 67 18, 59 18, 59 13, 67 13))");
assertFalse(geom3d.equals(geom2d));
// SRID equality test
GeometryFactory geometryFactory = new GeometryFactory();
Geometry geometry = geometryFactory.createPoint(new Coordinate(0, 0));
geometry.setSRID(27572);
ValueGeometry valueGeometry =
ValueGeometry.getFromGeometry(geometry);
Geometry geometry2 = geometryFactory.createPoint(new Coordinate(0, 0));
geometry2.setSRID(5326);
ValueGeometry valueGeometry2 =
ValueGeometry.getFromGeometry(geometry2);
assertFalse(valueGeometry.equals(valueGeometry2));
// Check illegal geometry (no WKB representation)
try {
ValueGeometry.get("POINT EMPTY");
fail("expected this to throw IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// expected
}
}
/**
* Check that geometry column type is kept with a table function
*/
private void testTableFunctionGeometry() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS POINT_TABLE FOR \"" +
TestSpatial.class.getName() + ".pointTable\"");
stat.execute("create table test as select * from point_table(1, 1)");
// Read column type
ResultSet columnMeta = conn.getMetaData().
getColumns(null, null, "TEST", "THE_GEOM");
assertTrue(columnMeta.next());
assertEquals("geometry",
columnMeta.getString("TYPE_NAME").toLowerCase());
assertFalse(columnMeta.next());
} finally {
conn.close();
}
deleteDb("spatial");
}
/**
* This method is called via reflection from the database.
*
* @param x the x position of the point
* @param y the y position of the point
* @return a result set with this point
*/
public static ResultSet pointTable(double x, double y) {
GeometryFactory factory = new GeometryFactory();
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("THE_GEOM", Types.JAVA_OBJECT, "GEOMETRY", 0, 0);
rs.addRow(factory.createPoint(new Coordinate(x, y)));
return rs;
}
private void testAggregateWithGeometry() throws SQLException {
deleteDb("spatialIndex");
Connection conn = getConnection("spatialIndex");
try {
Statement st = conn.createStatement();
st.execute("CREATE AGGREGATE TABLE_ENVELOPE FOR \""+
TableEnvelope.class.getName()+"\"");
st.execute("CREATE TABLE test(the_geom GEOMETRY)");
st.execute("INSERT INTO test VALUES ('POINT(1 1)'), (null), (null), ('POINT(10 5)')");
ResultSet rs = st.executeQuery("select TABLE_ENVELOPE(the_geom) from test");
assertEquals("geometry", rs.getMetaData().
getColumnTypeName(1).toLowerCase());
assertTrue(rs.next());
assertTrue(rs.getObject(1) instanceof Geometry);
assertTrue(new Envelope(1, 10, 1, 5).equals(
((Geometry) rs.getObject(1)).getEnvelopeInternal()));
assertFalse(rs.next());
} finally {
conn.close();
}
deleteDb("spatialIndex");
}
/**
* An aggregate function that calculates the envelope.
*/
public static class TableEnvelope implements Aggregate {
private Envelope tableEnvelope;
@Override
public int getInternalType(int[] inputTypes) throws SQLException {
for (int inputType : inputTypes) {
if (inputType != Value.GEOMETRY) {
throw new SQLException("TableEnvelope accept only Geometry argument");
}
}
return Value.GEOMETRY;
}
@Override
public void init(Connection conn) throws SQLException {
tableEnvelope = null;
}
@Override
public void add(Object value) throws SQLException {
if (value instanceof Geometry) {
if (tableEnvelope == null) {
tableEnvelope = ((Geometry) value).getEnvelopeInternal();
} else {
tableEnvelope.expandToInclude(((Geometry) value).getEnvelopeInternal());
}
}
}
@Override
public Object getResult() throws SQLException {
return new GeometryFactory().toGeometry(tableEnvelope);
}
}
private void testTableViewSpatialPredicate() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("drop table if exists test");
stat.execute("drop view if exists test_view");
stat.execute("create table test(id int primary key, poly geometry)");
stat.execute("insert into test values(1, 'POLYGON ((1 1, 1 2, 2 2, 1 1))')");
stat.execute("insert into test values(4, null)");
stat.execute("insert into test values(2, 'POLYGON ((3 1, 3 2, 4 2, 3 1))')");
stat.execute("insert into test values(3, 'POLYGON ((1 3, 1 4, 2 4, 1 3))')");
stat.execute("create view test_view as select * from test");
//Check result with view
ResultSet rs;
rs = stat.executeQuery(
"select * from test where poly && 'POINT (1.5 1.5)'::Geometry");
assertTrue(rs.next());
assertEquals(1, rs.getInt("id"));
assertFalse(rs.next());
rs = stat.executeQuery(
"select * from test_view where poly && 'POINT (1.5 1.5)'::Geometry");
assertTrue(rs.next());
assertEquals(1, rs.getInt("id"));
assertFalse(rs.next());
rs.close();
} finally {
// Close the database
conn.close();
}
deleteDb("spatial");
}
/**
* Check ValueGeometry conversion into SQL script
*/
private void testValueGeometryScript() throws SQLException {
ValueGeometry valueGeometry = ValueGeometry.get("POINT(1 1 5)");
Connection conn = getConnection(URL);
try {
ResultSet rs = conn.createStatement().executeQuery(
"SELECT " + valueGeometry.getSQL());
assertTrue(rs.next());
Object obj = rs.getObject(1);
ValueGeometry g = ValueGeometry.getFromGeometry(obj);
assertTrue("got: " + g + " exp: " + valueGeometry, valueGeometry.equals(g));
} finally {
conn.close();
}
}
/**
* If the user mutate the geometry of the object, the object cache must not
* be updated.
*/
private void testInPlaceUpdate() throws SQLException {
Connection conn = getConnection(URL);
try {
ResultSet rs = conn.createStatement().executeQuery(
"SELECT 'POINT(1 1)'::geometry");
assertTrue(rs.next());
// Mutate the geometry
((Geometry) rs.getObject(1)).apply(new AffineTransformation(1, 0,
1, 1, 0, 1));
rs.close();
rs = conn.createStatement().executeQuery(
"SELECT 'POINT(1 1)'::geometry");
assertTrue(rs.next());
// Check if the geometry is the one requested
assertEquals(1, ((Point) rs.getObject(1)).getX());
assertEquals(1, ((Point) rs.getObject(1)).getY());
rs.close();
} finally {
conn.close();
}
}
private void testScanIndexOnNonSpatialQuery() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("drop table if exists test");
stat.execute("create table test(id serial primary key, " +
"value double, the_geom geometry)");
stat.execute("create spatial index spatial on test(the_geom)");
ResultSet rs = stat.executeQuery("explain select * from test where _ROWID_ = 5");
assertTrue(rs.next());
assertContains(rs.getString(1), "/* PUBLIC.SPATIAL: _ROWID_ = 5 */");
} finally {
// Close the database
conn.close();
}
deleteDb("spatial");
}
private void testStoreCorruption() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("drop table if exists pt_cloud;\n" +
"CREATE TABLE PT_CLOUD AS " +
" SELECT CONCAT('POINT(',A.X,' ',B.X,')')::geometry the_geom from" +
" system_range(1e6,1e6+10) A,system_range(6e6,6e6+10) B;\n" +
"create spatial index pt_index on pt_cloud(the_geom);");
// Wait some time
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
throw new SQLException(ex);
}
stat.execute("drop table if exists pt_cloud;\n" +
"CREATE TABLE PT_CLOUD AS " +
" SELECT CONCAT('POINT(',A.X,' ',B.X,')')::geometry the_geom from" +
" system_range(1e6,1e6+50) A,system_range(6e6,6e6+50) B;\n" +
"create spatial index pt_index on pt_cloud(the_geom);\n" +
"shutdown compact;");
} finally {
// Close the database
conn.close();
}
deleteDb("spatial");
}
private void testExplainSpatialIndexWithPk() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
try {
Statement stat = conn.createStatement();
stat.execute("drop table if exists pt_cloud;");
stat.execute("CREATE TABLE PT_CLOUD(id serial, the_geom geometry) AS " +
"SELECT null, CONCAT('POINT(',A.X,' ',B.X,')')::geometry the_geom " +
"from system_range(0,120) A,system_range(0,10) B;");
stat.execute("create spatial index on pt_cloud(the_geom);");
ResultSet rs = stat.executeQuery(
"explain select * from PT_CLOUD " +
"where the_geom && 'POINT(1 1)'");
try {
assertTrue(rs.next());
assertFalse("H2 should use spatial index got this explain:\n" +
rs.getString(1), rs.getString(1).contains("tableScan"));
} finally {
rs.close();
}
} finally {
// Close the database
conn.close();
}
deleteDb("spatial");
}
private void testNullableGeometry() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("create memory table test"
+ "(id int primary key, the_geom geometry)");
stat.execute("create spatial index on test(the_geom)");
stat.execute("insert into test values(1, null)");
stat.execute("insert into test values(2, null)");
stat.execute("delete from test where the_geom is null");
stat.execute("insert into test values(1, null)");
stat.execute("insert into test values(2, null)");
stat.execute("insert into test values(3, " +
"'POLYGON ((1000 2000, 1000 3000, 2000 3000, 1000 2000))')");
stat.execute("insert into test values(4, null)");
stat.execute("insert into test values(5, null)");
stat.execute("insert into test values(6, " +
"'POLYGON ((1000 3000, 1000 4000, 2000 4000, 1000 3000))')");
ResultSet rs = stat.executeQuery("select * from test");
int count = 0;
while (rs.next()) {
count++;
int id = rs.getInt(1);
if (id == 3 || id == 6) {
assertTrue(rs.getObject(2) != null);
} else {
assertNull(rs.getObject(2));
}
}
assertEquals(6, count);
rs = stat.executeQuery("select * from test where the_geom is null");
count = 0;
while (rs.next()) {
count++;
assertNull(rs.getObject(2));
}
assertEquals(4, count);
rs = stat.executeQuery("select * from test where the_geom is not null");
count = 0;
while (rs.next()) {
count++;
assertTrue(rs.getObject(2) != null);
}
assertEquals(2, count);
rs = stat.executeQuery(
"select * from test " +
"where intersects(the_geom, " +
"'POLYGON ((1000 1000, 1000 2000, 2000 2000, 1000 1000))')");
conn.close();
if (!config.memory) {
conn = getConnection(URL);
stat = conn.createStatement();
rs = stat.executeQuery("select * from test");
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertNull(rs.getObject(2));
conn.close();
}
deleteDb("spatial");
}
private void testNullableGeometryDelete() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("create memory table test"
+ "(id int primary key, the_geom geometry)");
stat.execute("create spatial index on test(the_geom)");
stat.execute("insert into test values(1, null)");
stat.execute("insert into test values(2, null)");
stat.execute("insert into test values(3, null)");
ResultSet rs = stat.executeQuery("select * from test order by id");
while (rs.next()) {
assertNull(rs.getObject(2));
}
stat.execute("delete from test where id = 1");
stat.execute("delete from test where id = 2");
stat.execute("delete from test where id = 3");
stat.execute("insert into test values(4, null)");
stat.execute("insert into test values(5, null)");
stat.execute("insert into test values(6, null)");
stat.execute("delete from test where id = 4");
stat.execute("delete from test where id = 5");
stat.execute("delete from test where id = 6");
conn.close();
deleteDb("spatial");
}
private void testNullableGeometryInsert() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("create memory table test"
+ "(id identity, the_geom geometry)");
stat.execute("create spatial index on test(the_geom)");
for (int i = 0; i < 1000; i++) {
stat.execute("insert into test values(null, null)");
}
ResultSet rs = stat.executeQuery("select * from test");
while (rs.next()) {
assertNull(rs.getObject(2));
}
conn.close();
deleteDb("spatial");
}
private void testNullableGeometryUpdate() throws SQLException {
deleteDb("spatial");
Connection conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("create memory table test"
+ "(id int primary key, the_geom geometry, description varchar2(32))");
stat.execute("create spatial index on test(the_geom)");
stat.execute("insert into test values(1, null, null)");
stat.execute("insert into test values(2, null, null)");
stat.execute("insert into test values(3, null, null)");
ResultSet rs = stat.executeQuery("select * from test");
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertNull(rs.getObject(2));
stat.execute("update test set description='DESCRIPTION' where id = 1");
stat.execute("update test set description='DESCRIPTION' where id = 2");
stat.execute("update test set description='DESCRIPTION' where id = 3");
conn.close();
deleteDb("spatial");
}
}
| [
"renzo.carrera@hotmail.com"
] | renzo.carrera@hotmail.com |
d0dc54860ae070b881bfc46dcaf142e05dcd0f5e | 1e8efeaf88f0e99031a8269081745f76aaae5218 | /src/main/java/com/boco/workflow/webservice/builder/ProjectBuilder.java | 1bab5a25570c533ffbd2124602795cb428ef1915 | [] | no_license | GaodYang/wf_pon | 4202297d7aa6caf5a078d8e7e4b26d4da7c76a33 | 9fd00356adb6951f079d2d784874dfa493c32995 | refs/heads/master | 2021-01-22T19:55:01.874454 | 2017-03-17T03:08:36 | 2017-03-17T03:08:36 | 85,262,090 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 601 | java | package com.boco.workflow.webservice.builder;
import com.boco.core.utils.id.CUIDHexGenerator;
import com.boco.workflow.webservice.pojo.Project;
/**
* 构建工程的结构
* @author gaoyang 2017年3月7日
*
*/
public class ProjectBuilder extends AbstractBuilder<Project> implements IBuilder<Project>{
public ProjectBuilder() {
super(new Project());
}
public ProjectBuilder(Project project){
super(project);
}
public ProjectBuilder addCuid(){
pojo.setCuid(CUIDHexGenerator.getInstance().generate("T_WF_PROJECT"));
return this;
}
}
| [
"wiggler@DESKTOP-HBS8N4O"
] | wiggler@DESKTOP-HBS8N4O |
02aa3c80d30a6b0872ff5d63af2908a9ab25ae57 | 2c23f296ad57b1ff12ecafdc352ace28e116beb9 | /src/main/java/io/connectedhealth_idaas/eventbuilder/pojos/clinical/fhir/ImmunizationResource/StatusReason.java | 1cdc2c45b04437aa71797547f50092b80b2b995f | [
"Apache-2.0"
] | permissive | jbmyer94/iDaaS-EventBuilder | 448976955daaf1c9424d0742f1752cb95787de0f | 66f815a1071538928f717a2b0d293858596b6086 | refs/heads/master | 2023-05-23T14:17:41.071220 | 2021-06-16T16:16:02 | 2021-06-16T16:16:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 474 | java | package io.connectedhealth_idaas.eventbuilder.pojos.clinical.fhir.ImmunizationResource;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import java.util.List;
public class StatusReason {
public List<Coding> coding;
public List<Coding> getCoding() { return coding; }
public void setCoding(List<Coding> coding) { this.coding = coding; }
public String toString()
{
return ReflectionToStringBuilder.toString(this);
}
}
| [
"rxj7063@Rj-MacBook-Pro.local"
] | rxj7063@Rj-MacBook-Pro.local |
6ab909a6d96d29da532c01d24d042fe4ac2dfda3 | 1034a7e75c3aa44cac50502da2919f806ec42628 | /changgou-parent/changgou-service-api/changgou-service-user-api/src/main/java/com/changgou/user/feign/UserFeign.java | b03bff00b117fc1ffb67bf796c8a64c7c11a516c | [] | no_license | moonlight-lyle/legou | 5a2c4bfc440cc0ee96d118071ccdb62a1fd206b8 | 6aba74bcd08d867b75c4fe1d615020b205dd8b06 | refs/heads/master | 2023-08-15T06:59:25.443764 | 2021-09-20T07:14:48 | 2021-09-20T07:14:48 | 400,937,476 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,074 | java | package com.changgou.user.feign;
import com.changgou.user.pojo.User;
import entity.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/***
* 描述
* @author
* @packagename com.changgou.user
* @version 1.0
* @date 2020/3/30
*/
@FeignClient(name="user")
@RequestMapping("/user")
public interface UserFeign {
@GetMapping("/load/{id}")
public Result<User> loadById(@PathVariable(name="id") String id);
//添加积分 给某一个用户 添加指定的积分
/**
* 给指定的用户添加积分
* @param username 指定用户名
* @param points 指定要添加的积分
* @return
*/
@GetMapping("/points/add")
public Result addPoints(@RequestParam(name="username") String username,
@RequestParam(name="points") Integer points);
}
| [
"15755589769@163.com"
] | 15755589769@163.com |
84a1bdf46b4a4a9de5d34b1be5bb9d8926005a63 | 994ac976b9ecb8b22a91f9adc7f509f094cd7af0 | /Java/sunruofei/task7/ssm/src/main/java/com/ptteng/service/UserService.java | 4ecc474bd26f4082a10bfb566bb38dadda6a9e09 | [] | no_license | lisiming-1993/Task | fce7d884c3d0caab4094e237da63671d0e3eb270 | de5c3116ef263efef5f3daeca678b3c25c039295 | refs/heads/master | 2020-05-03T00:21:40.300954 | 2019-03-26T16:36:36 | 2019-03-26T16:36:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 730 | java | package com.ptteng.service;
import com.ptteng.model.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
public interface UserService {
boolean insert(User record);
User selectByName(String name);
User selectByCondition(@Param("name") String name, @Param("password") String password);
User selectById(Long id);
User selectCodePhone(@Param("code") String code ,@Param("phone") String phone);
User selectCodeMail(@Param("mail") String mail ,@Param("code") String code);
int insertMail( @Param("name") String name ,@Param("password") String password
, @Param("mail") String mail ,@Param("phone") String phone);
}
| [
"1744207827@qq.com"
] | 1744207827@qq.com |
3eda2222df73c7a5bd6177a98363d561fe331894 | 69cd2c960e14297f364ea83ef0c1106d8368b15c | /mbhd-swing/src/test/java/org/multibit/hd/ui/fest/use_cases/sidebar/contacts/EditBobContactUseCase.java | b1cc3c010721f5270e6e2b2703dde8c7e5303095 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | litecoin-project/multibit-hd | 90d03bd4fd8828931efcfde47d26ba4d330116ad | e4a6c84d5adf42e300be9a71b5faa97914793063 | refs/heads/develop | 2020-12-28T21:27:49.173734 | 2015-03-19T07:21:41 | 2015-03-19T07:21:41 | 29,544,039 | 7 | 13 | null | 2015-01-20T18:11:52 | 2015-01-20T18:11:52 | null | UTF-8 | Java | false | false | 4,443 | java | package org.multibit.hd.ui.fest.use_cases.sidebar.contacts;
import org.fest.swing.fixture.FrameFixture;
import org.multibit.hd.ui.fest.use_cases.AbstractFestUseCase;
import org.multibit.hd.ui.languages.MessageKey;
import org.multibit.hd.ui.views.components.tables.ContactTableModel;
import org.multibit.hd.ui.views.wizards.edit_contact.EditContactState;
import java.util.Map;
import static org.fest.assertions.Assertions.assertThat;
/**
* <p>Use case to provide the following to FEST testing:</p>
* <ul>
* <li>Verify the "contacts" screen edit Bob contact</li>
* </ul>
* <p>Requires the "contacts" screen to be showing</p>
* <p>Requires the "Bob" contact to be present</p>
*
* @since 0.0.1
*
*/
public class EditBobContactUseCase extends AbstractFestUseCase {
public EditBobContactUseCase(FrameFixture window) {
super(window);
}
@Override
public void execute(Map<String, Object> parameters) {
// Get the initial row count
int rowCount1 = window
.table(MessageKey.CONTACTS.getKey())
.rowCount();
// Find Bob's row
int bobRow = window
.table(MessageKey.CONTACTS.getKey())
.cell("Bob")
.row;
// Get the contacts
String[][] contacts = window
.table(MessageKey.CONTACTS.getKey())
.contents();
ensureCheckboxIsSelected(MessageKey.CONTACTS, bobRow, ContactTableModel.CHECKBOX_COLUMN_INDEX);
// Click on Edit
window
.button(MessageKey.EDIT.getKey())
.click();
// Verify the single contact edit wizard appears
assertLabelText(MessageKey.EDIT_CONTACT_TITLE);
window
.button(MessageKey.CANCEL.getKey())
.requireVisible()
.requireEnabled();
// Verify contact image
window
.label(MessageKey.CONTACT_IMAGE.getKey())
.requireVisible();
// Update Bob's details
window
.textBox(MessageKey.NAME.getKey())
.requireText("Bob")
.setText("Bob Cratchit");
window
.textBox(MessageKey.EMAIL_ADDRESS.getKey())
.requireText("bob@example.org")
.setText("bob.cratchit@example.org");
// Ensure Add button is disabled without tag
addTag("Scrooge Staff", 1);
// Private notes
window
.textBox(MessageKey.PRIVATE_NOTES.getKey())
.setText("Bob is now working for Scrooge");
verifyCancel();
// Click Apply
window
.button(MessageKey.APPLY.getKey())
.click();
// Verify the underlying screen is back
window
.button(MessageKey.ADD.getKey())
.requireVisible()
.requireEnabled();
// Get an updated row count
int rowCount2 = window
.table(MessageKey.CONTACTS.getKey())
.rowCount();
// Verify that no new row has been added
assertThat(rowCount2).isEqualTo(rowCount1);
// Verify that "Alice" is unaffected
window
.table(MessageKey.CONTACTS.getKey())
.cell("Alice");
// Verify that "Bob" is now "Bob Cratchit"
window
.table(MessageKey.CONTACTS.getKey())
.cell("Bob Cratchit");
}
/**
* Verifies that clicking cancel with data present gives a Yes/No popover
*/
private void verifyCancel() {
// Click Cancel
window
.button(MessageKey.CANCEL.getKey())
.click();
// Expect Yes/No popover
window
.button(MessageKey.YES.getKey())
.requireVisible()
.requireEnabled();
window
.button("popover_"+MessageKey.CLOSE.getKey())
.requireVisible()
.requireEnabled();
// Click No
window
.button(MessageKey.NO.getKey())
.requireVisible()
.requireEnabled()
.click();
}
private void addTag(String tag, int startCount) {
window
.button(EditContactState.EDIT_CONTACT_ENTER_DETAILS + "." + MessageKey.ADD.getKey())
.requireVisible()
.requireDisabled();
// Add a tag
window
.textBox(MessageKey.TAGS.getKey())
.setText(tag);
// Count the tags
final int tagCount1 = window
.list(MessageKey.TAGS.getKey())
.contents().length;
assertThat(tagCount1).isEqualTo(startCount);
// Click Add tag
window
.button(EditContactState.EDIT_CONTACT_ENTER_DETAILS + "." + MessageKey.ADD.getKey())
.requireVisible()
.requireEnabled()
.click();
// Count the tags
final int tagCount2 = window
.list(MessageKey.TAGS.getKey())
.contents().length;
assertThat(tagCount2).isEqualTo(tagCount1 + 1);
}
}
| [
"g.rowe@froot.co.uk"
] | g.rowe@froot.co.uk |
c65870c95cd64a1dab678bacff528858c3be9e7f | 4f6b3a7c54b62b26479df99f812865dcf5ec5254 | /src/com/shooterland/states/WorldMapState.java | 8850afccd24900ef6469caf26a11d23b2eb99920 | [] | no_license | rgw0094/shooterland | 39acb847fafba691f882648cfb8537616784bf41 | 88e99e042df39903d00e838d10b94993817b7106 | refs/heads/master | 2021-01-01T03:54:22.170442 | 2010-06-26T21:26:20 | 2010-06-26T21:26:20 | 56,730,493 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,023 | java | package com.shooterland.states;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.Menu;
import com.shooterland.entities.Button;
import com.shooterland.entities.MainMenuButton;
import com.shooterland.enums.MenuOption;
import com.shooterland.framework.AbstractState;
import com.shooterland.framework.SL;
public class WorldMapState extends AbstractState
{
private Button _menuButton;
private Button _playButton;
public void buildMenu(Menu menu)
{
MenuOption.Achievements.addToMenu(menu);
MenuOption.Stats.addToMenu(menu);
MenuOption.ToggleSound.addToMenu(menu);
MenuOption.Help.addToMenu(menu);
}
@Override
public void draw(Canvas canvas, float dt)
{
canvas.drawRect(new Rect(0, 0, SL.ScreenWidth, SL.ScreenHeight), SL.Graphics.BlackPaint);
int size = 15;
for (int x = 0; x <= SL.ScreenWidth; x += size)
canvas.drawLine(x, 0, x, SL.ScreenHeight, SL.Graphics.DarkGreenPaint);
for (int y = 0; y <= SL.ScreenHeight; y += size)
canvas.drawLine(0, y, SL.ScreenWidth, y, SL.Graphics.DarkGreenPaint);
canvas.drawBitmap(SL.Graphics.WorldMapBackground, SL.GameAreaX, 0, null);
_menuButton.draw(canvas);
_playButton.draw(canvas);
}
@Override
public void enterState()
{
_menuButton = new Button(SL.Graphics.WorldMapButtonBack, "Back", (float)SL.GameAreaX + (float)SL.GameAreaWidth * 0.2f, (float)SL.GameAreaHeight * 0.86f);
_playButton = new Button(SL.Graphics.WorldMapButtonForward, "Play", (float)SL.GameAreaX + (float)SL.GameAreaWidth * 0.8f, (float)SL.GameAreaHeight * 0.86f);
}
@Override
public void leaveState()
{
}
@Override
public void update(float dt)
{
if (_menuButton.isClicked() || SL.Input.isBackClicked())
{
SL.enterState(new MainMenuState(false));
return;
}
else if (_playButton.isClicked())
{
SL.enterState(new OverworldState());
return;
}
}
@Override
public boolean isFinished()
{
return true;
}
}
| [
"rgw0094@33fdbde0-16ca-11df-98f2-4dfa3b4eb4a2"
] | rgw0094@33fdbde0-16ca-11df-98f2-4dfa3b4eb4a2 |
df31363f7d4838f194e48961f1c53df8a501cb29 | ee5aefd578e1c466b6b42eef90e5d85344880df3 | /src/main/java/com/vahundos/model/Vote.java | 6bccaed55398a2339f903987a5b4ff44a85c8233 | [] | no_license | vahundos/Restaurant-voting-system | 780bf2a78a9160e7e5cc0ee78837a15828a699c4 | caf637f3609f34e74c48ef8acd368d32471dbaf3 | refs/heads/master | 2022-04-05T02:40:23.416128 | 2018-02-27T06:07:58 | 2018-02-27T06:07:58 | 116,108,811 | 0 | 0 | null | 2020-01-12T15:09:13 | 2018-01-03T07:54:44 | Java | UTF-8 | Java | false | false | 459 | java | package com.vahundos.model;
import javax.persistence.Embeddable;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Embeddable
public class Vote {
public Vote() {
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| [
"vahundos@gmail.com"
] | vahundos@gmail.com |
51a00c3071f2feb3fabfb262f6201423a81528a1 | 4d3d0b511279f20dc56442b4bdd24bbcbb99f702 | /src/main/java/com/chase/useraccessmanagement/config/SwaggerConfig.java | c8310b258ca05b50107434a0733488acff44d0f9 | [] | no_license | karunakarreddych/assignments | 08932f5ee9b0f1b7a5bbff9a8a81a86c69abb051 | 4f2e56a6d80ec962147c013fc6c185d1cbf84a53 | refs/heads/master | 2022-11-30T06:57:05.604025 | 2020-08-09T14:39:21 | 2020-08-09T14:39:21 | 286,105,494 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,833 | java | package com.chase.useraccessmanagement.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api()
{
ParameterBuilder paramBuilder = new ParameterBuilder();
List<Parameter> params = new ArrayList<>();
paramBuilder.name("Authorization").modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build();
params.add(paramBuilder.build());
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(params)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.consumes(new HashSet<String>(Arrays.asList("application/json")))
.produces(new HashSet<String>(Arrays.asList("application/json")));
}
private ApiInfo apiInfo() {
return new ApiInfo(
"USER ACCESS MANAGEMENT",
"Manages Users",
"1.0",
"Terms of service",
new Contact("", "", ""),
"License of API", "API license URL", Collections.emptyList());
}
}
| [
"karunakarc@nblap103.karunakar.com"
] | karunakarc@nblap103.karunakar.com |
f3a646076d4276575bed3687db31bd48a814029c | 914b64df8e466085ac767148a1d2326b4663e0ac | /app/src/main/java/com/wing/listitemscaledemo/MainActivity.java | b3f6f1e8ca05b83c40b10390dd7b9c564575832f | [] | no_license | wingfordream/ListItemScaleDemo | bfcb6779eb2bf263fe6c3546da1636cafdcae2e2 | 441db9a891f883de58d75ea5db99e531980c094a | refs/heads/master | 2020-07-06T10:05:11.096527 | 2016-08-24T06:56:51 | 2016-08-24T06:56:51 | 66,429,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,657 | java | package com.wing.listitemscaledemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView listView;
private List<Info> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
listView = (RecyclerView) findViewById(R.id.listView);
listView.setAdapter(new ListAdapter());
}
private void initData() {
data = new ArrayList<>();
for (int i=0;i<20;i++){
Info info = new Info();
info.setName("微头条");
info.setImageRes(R.drawable.icon);
info.setInstalled_count(i);
info.setSize(6.7f);
info.setIntroduce("趣味内容分享平台");
data.add(info);
}
}
class ListAdapter extends RecyclerView.Adapter{
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return data.size();
}
}
class ListItemHolder extends RecyclerView.ViewHolder{
public ListItemHolder(View itemView) {
super(itemView);
}
}
}
| [
"564731560@qq.com"
] | 564731560@qq.com |
ff89f136ea70d7eab30542880d4c17b42d6be32c | e8724b6290d92a8b7a463e808c69674dde151fd4 | /src/javapracticeday5/LargestNumber.java | aee7f20c57feab943a723e0e128a3a81e8ce09ff | [] | no_license | rahullabade/JavaPracticeDay5 | aa340e91277ef77e00f1f23d1dac34c179579997 | 820baece9b12d9cabd7d1cf51fcff1fe191fcf9e | refs/heads/master | 2023-08-16T15:03:10.287221 | 2021-09-29T15:52:43 | 2021-09-29T15:52:43 | 411,734,345 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 526 | java | package javapracticeday5;
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
int a, b, c, largest, temp;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number:");
a = sc.nextInt();
System.out.println("Enter the second number:");
b = sc.nextInt();
System.out.println("Enter the third number:");
c = sc.nextInt();
temp=a>b?a:b;
largest=c>temp?c:temp;
System.out.println("The largest number is: "+largest);
}
}
| [
"rahullabade05@gmail.com"
] | rahullabade05@gmail.com |
0715b4ba17113fb40c19d3426fd52c7d36143629 | 9afa0da468e3d16ab27c3981e8e8226c2512e7c0 | /src/main/java/org/lzy/flume/source/tailDir/TailSource.java | 4aaac4e8c6376ff6056638ae374659267c8541f5 | [] | no_license | kobelzy/flume-ftp-source | ca36e2ef6eec3f29600e15905edfa437aa2643ff | 3c9f241f82faa9822718d6d0209f2f0f2b19f2ab | refs/heads/master | 2021-04-06T06:41:45.740660 | 2018-04-07T13:48:30 | 2018-04-07T13:48:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,340 | java | /**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lzy.flume.source.tailDir;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* This "tail"s a filename. Like a unix tail utility, it will wait for more
* information to come to the file and periodically dump data as it is written.
* It assumes that each line is a separate event.
* <p/>
* This is for legacy log files where the file system is the only mechanism
* flume has to get events. It assumes that there is one entry per line (per
* \n). If a file currently does not end with \n, it will remain buffered
* waiting for more data until either a different file with the same name has
* appeared, or the tail source is closed.
* <p/>
* It also has logic to deal with file rotations -- if a file is renamed and
* then a new file is created, it will shift over to the new file. The current
* file is read until the file pointer reaches the end of the file. It will wait
* there until periodic checks notice that the file has become longer. If the
* file "shrinks" we assume that the file has been replaced with a new log file.
* <p/>
* TODO (jon) This is not perfect.
* <p/>
* This reads bytes and does not assume any particular character encoding other
* than that entry are separated by new lines ('\n').
* <p/>
* There is a possibility for inconsistent conditions when logs are rotated.
* <p/>
* 1) If rotation periods are faster than periodic checks, a file may be missed.
* (this mimics gnu-tail semantics here)
* <p/>
* 2) Truncations of files will reset the file pointer. This is because the Java
* file api does not a mechanism to get the inode of a particular file, so there
* is no way to differentiate between a new file or a truncated file!
* <p/>
* 3) If a file is being read, is moved, and replaced with another file of
* exactly the same size in a particular window and the last mod time of the two
* are identical (this is often at the second granularity in FS's), the data in
* the new file may be lost. If the original file has been completely read and
* then replaced with a file of the same length this problem will not occur.
* (See TestTailSource.readRotatePrexistingFailure vs
* TestTailSource.readRotatePrexistingSameSizeWithNewModetime)
* <p/>
* Ideally this would use the inode number of file handle number but didn't find
* java api to get these, or Java 7's WatchService file watcher API.
*/
public class TailSource {
private static final Logger logger = LoggerFactory.getLogger(TailSource.class);
private static int thdCount = 0;
private volatile boolean done = false;
private final long sleepTime; // millis
final List<Cursor> cursors = new ArrayList<Cursor>();
private final List<Cursor> newCursors = new ArrayList<Cursor>();
private final List<Cursor> rmCursors = new ArrayList<Cursor>();
private TailThread thd = null;
/**
* This creates an empty tail source. It expects something else to add cursors
* to it
*/
public TailSource(long waitTime) {
this.sleepTime = waitTime;
}
/**
* This is the main driver thread that runs through the file cursor list
* checking for updates and sleeping if there are none.
*/
class TailThread extends Thread {
TailThread() {
super("TailThread-" + thdCount++);
}
@Override
public void run() {
try {
// initialize based on initial settings.
for (Cursor c : cursors) {
c.initCursorPos();
}
while (!done) {
synchronized (newCursors) {
cursors.addAll(newCursors);
newCursors.clear();
}
synchronized (rmCursors) {
cursors.removeAll(rmCursors);
for (Cursor c : rmCursors) {
c.flush();
}
rmCursors.clear();
}
boolean madeProgress = false;
for (Cursor c : cursors) {
logger.debug("Progress loop: " + c.file);
if (c.tailBody()) {
madeProgress = true;
}
}
if (!madeProgress) {
Thread.sleep(sleepTime);
}
}
logger.debug("Tail got done flag");
} catch (InterruptedException e) {
logger.error("Tail thread nterrupted: " + e.getMessage(), e);
} finally {
logger.info("TailThread has exited");
}
}
}
/**
* Add another file Cursor to tail concurrently.
*/
public synchronized void addCursor(Cursor cursor) {
Preconditions.checkArgument(cursor != null);
if (thd == null) {
cursors.add(cursor);
logger.debug("Unstarted Tail has added cursor: " + cursor.file.getName());
} else {
synchronized (newCursors) {
newCursors.add(cursor);
}
logger.debug("Tail added new cursor to new cursor list: "
+ cursor.file.getName());
}
}
/**
* Remove an existing cursor to tail.
*/
synchronized public void removeCursor(Cursor cursor) {
Preconditions.checkArgument(cursor != null);
if (thd == null) {
cursors.remove(cursor);
} else {
synchronized (rmCursors) {
rmCursors.add(cursor);
}
}
}
public void close() {
synchronized (this) {
done = true;
if (thd == null) {
logger.warn("TailSource double closed");
return;
}
try {
while (thd.isAlive()) {
thd.join(100L);
thd.interrupt();
}
} catch (InterruptedException e) {
logger.error("Tail source Interrupted Exception: " + e.getMessage(), e);
}
thd = null;
}
}
synchronized public void open() {
if (thd != null) {
throw new IllegalStateException("Attempted to open tail source twice!");
}
thd = new TailThread();
thd.start();
}
}
| [
"kobeliuziyang@gmail.com"
] | kobeliuziyang@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.