text stringlengths 10 2.72M |
|---|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
class Calculator extends JFrame implements ActionListener
{
final int WIDTH = 400;
final int HEIGHT = 500;
protected int operator;
protected double a, b, r;
protected JTextField jtf;
JButton badd, bsub, bmul, bdiv, bdec, bequals, bclear, broot, bpower, bmod;
JButton bdigits[];
Calculator()
{
int i;
operator = 0;
a = b = r = 0.0d;
jtf = new JTextField();
badd = new JButton("+");
bsub = new JButton("-");
bmul = new JButton("*");
bdiv = new JButton("/");
bdec = new JButton(".");
bequals = new JButton("=");
broot = new JButton("Root");
bpower = new JButton("^");
bmod = new JButton("%");
bclear = new JButton("<-");
bdigits = new JButton[10];
for(i = 0; i < 10; i++)
bdigits[i] = new JButton(String.valueOf(i));
jtf.setBounds(40, 35, 300, 40);
buttonLayout();
addComponents();
for(i = 0; i < 10; i++)
bdigits[i].addActionListener(this);
badd.addActionListener(this);
bsub.addActionListener(this);
bmul.addActionListener(this);
bdiv.addActionListener(this);
bmod.addActionListener(this);
bdec.addActionListener(this);
bequals.addActionListener(this);
bpower.addActionListener(this);
bclear.addActionListener(this);
broot.addActionListener(this);
setLayout(null);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void buttonLayout()
{
int x, y, d, i, j, x_space, y_space, flag;
x_space = 40;
y_space = 150;
d = 9;
flag = 0;
for(i = 0; i < 5; i++)
{
if(flag == 0)
{
for(j = 0; j < 4; j++)
{
switch(j + 1)
{
case 1: broot.setBounds((x_space + (75 * j)), 120, 75, 30);
break;
case 2: bpower.setBounds((x_space + (75 * j)), 120, 75, 30);
break;
case 3: bclear.setBounds((x_space + (75 * j)), 120, 75, 30);
break;
case 4: bmod.setBounds((x_space + (75 * j)), 120, 75, 30);
break;
}
}
flag = 1;
}
if(i < 3)
{
for(j = 0; j < 3; j++)
{
x = x_space + (75 * j);
y = y_space + (30 * i);
bdigits[d].setBounds(x, y, 75, 30);
d--;
}
}
if(i == 3)
{
for(j = 0; j <= 3; j++)
{
switch(j + 1)
{
case 1: bdec.setBounds((x_space + (75 * j)), (y_space + 30 * i), 75, 30);
break;
case 2: bdigits[0].setBounds((x_space + (75 * j)), (y_space + 30 * i), 75, 30);
break;
case 3: bequals.setBounds((x_space + (75 * j)), (y_space + 30 * i), 75, 30);
break;
case 4: bdiv.setBounds((x_space + (75 * j)), (y_space + (30 * i)), 75, 30);
break;
}
}
}
switch(i + 1)
{
case 1: badd.setBounds((x_space + (75 * 3)), (y_space + (30 * i)), 75, 30);
break;
case 2: bsub.setBounds((x_space + (75 * 3)), (y_space + (30 * i)), 75, 30);
break;
case 3: bmul.setBounds((x_space + (75 * 3)), (y_space+ (30 * i)), 75, 30);
break;
}
}
}
public void addComponents()
{
add(jtf);
for(int i = 0; i < 10; i++)
add(bdigits[i]);
add(bdec);
add(bmod);
add(bequals);
add(bclear);
add(bpower);
add(broot);
add(badd);
add(bsub);
add(bmul);
add(bdiv);
}
public void actionPerformed(ActionEvent e)
{
int i, j;
for(i = 0; i < 10; i++)
{
if(e.getSource() == bdigits[i])
{
jtf.setText(jtf.getText().concat(i + ""));
}
}
if(e.getSource() == badd)
{
a = Double.parseDouble(jtf.getText());
jtf.setText("");
operator = 1;
}
if(e.getSource() == bsub)
{
a = Double.parseDouble(jtf.getText());
jtf.setText("");
operator = 2;
}
if(e.getSource() == bmul)
{
a = Double.parseDouble(jtf.getText());
jtf.setText("");
operator = 3;
}
if(e.getSource() == bdiv)
{
a = Double.parseDouble(jtf.getText());
jtf.setText("");
operator = 4;
}
if(e.getSource() == bmod)
{
a = Double.parseDouble(jtf.getText());
jtf.setText("");
operator = 5;
}
if(e.getSource() == bpower)
{
a = Double.parseDouble(jtf.getText());
jtf.setText("");
operator = 6;
}
if(e.getSource() == broot)
{
a = Double.parseDouble(jtf.getText());
jtf.setText("");
operator = 7;
}
if(e.getSource() == bdec)
{
String temp = jtf.getText();
for(i = 0; i < temp.length(); i++)
{
if(temp.charAt(i) == '.')
jtf.setText(temp.substring(0,(i - 1)));
}
a = Double.parseDouble(jtf.getText());
jtf.setText(String.valueOf(a).concat("."));
}
if(e.getSource() == bclear)
{
jtf.setText(jtf.getText().substring(0,(jtf.getText().length() - 2)));
}
if(e.getSource() == bequals)
{
switch(operator)
{
case 1: b = Double.parseDouble(jtf.getText());
r = addition(a, b);
jtf.setText(String.valueOf(r));
break;
case 2: b = Double.parseDouble(jtf.getText());
r = subtraction(a, b);
jtf.setText(String.valueOf(r));
break;
case 3: b = Double.parseDouble(jtf.getText());
r = multiplication(a, b);
jtf.setText(String.valueOf(r));
break;
case 4: b = Double.parseDouble(jtf.getText());
r = division(a, b);
jtf.setText(String.valueOf(r));
break;
case 5: b = Double.parseDouble(jtf.getText());
r = modulus(a, b);
jtf.setText(String.valueOf(r));
break;
case 6: b = Double.parseDouble(jtf.getText());
r = power(a, b);
jtf.setText(String.valueOf(r));
break;
case 7: r = root(a);
jtf.setText(String.valueOf(r));
break;
}
}
}
double addition(double x, double y)
{
return (x + y);
}
double subtraction(double x, double y)
{
return (x - y);
}
double multiplication(double x, double y)
{
return (x * y);
}
double division(double x, double y)
{
return (x / y);
}
double modulus(double x, double y)
{
return (x % y);
}
double power(double x, double y)
{
return (Math.pow(x,y));
}
double root(double x)
{
return (Math.sqrt(x));
}
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
e.printStackTrace();
}
new Calculator();
}
} |
package no.nav.vedtak.felles.integrasjon.dokarkiv;
import java.net.URI;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.core.UriBuilderException;
import no.nav.vedtak.exception.TekniskException;
import no.nav.vedtak.felles.integrasjon.dokarkiv.dto.TilknyttVedleggRequest;
import no.nav.vedtak.felles.integrasjon.dokarkiv.dto.TilknyttVedleggResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import no.nav.vedtak.felles.integrasjon.dokarkiv.dto.FerdigstillJournalpostRequest;
import no.nav.vedtak.felles.integrasjon.dokarkiv.dto.OppdaterJournalpostRequest;
import no.nav.vedtak.felles.integrasjon.dokarkiv.dto.OpprettJournalpostRequest;
import no.nav.vedtak.felles.integrasjon.dokarkiv.dto.OpprettJournalpostResponse;
import no.nav.vedtak.felles.integrasjon.rest.RestClient;
import no.nav.vedtak.felles.integrasjon.rest.RestConfig;
import no.nav.vedtak.felles.integrasjon.rest.RestRequest;
// @RestClientConfig(tokenConfig = TokenFlow.STS_CC, endpointProperty = "dokarkiv.base.url", endpointDefault = "http://dokarkiv.teamdokumenthandtering/rest/journalpostapi/v1/journalpost")
public class AbstractDokArkivKlient implements DokArkiv {
private static final Logger LOG = LoggerFactory.getLogger(AbstractDokArkivKlient.class);
private final RestClient restKlient;
private final RestConfig restConfig;
protected AbstractDokArkivKlient() {
this(RestClient.client());
}
protected AbstractDokArkivKlient(RestClient client) {
this.restKlient = client;
this.restConfig = RestConfig.forClient(this.getClass());
}
@Override
public OpprettJournalpostResponse opprettJournalpost(OpprettJournalpostRequest request, boolean ferdigstill) {
try {
var opprett = ferdigstill ? UriBuilder.fromUri(restConfig.endpoint())
.queryParam("forsoekFerdigstill", "true")
.build() : restConfig.endpoint();
var restRequest = RestRequest.newPOSTJson(request, opprett, restConfig);
var res = restKlient.sendExpectConflict(restRequest, OpprettJournalpostResponse.class);
return res;
} catch (Exception e) {
LOG.info("DOKARKIV OPPRETT feilet for {}", request, e);
return null;
}
}
@Override
public boolean oppdaterJournalpost(String journalpostId, OppdaterJournalpostRequest request) {
try {
var oppdater = URI.create(restConfig.endpoint().toString() + String.format("/%s", journalpostId));
var method = new RestRequest.Method(RestRequest.WebMethod.PUT, RestRequest.jsonPublisher(request));
var restRequest = RestRequest.newRequest(method, oppdater, restConfig);
restKlient.send(restRequest, String.class);
return true;
} catch (Exception e) {
LOG.info("DOKARKIV OPPDATER {} feilet for {}", journalpostId, request, e);
return false;
}
}
@Override
public boolean ferdigstillJournalpost(String journalpostId, String enhet) {
try {
var ferdigstill = URI.create(restConfig.endpoint().toString() + String.format("/%s/ferdigstill", journalpostId));
var method = new RestRequest.Method(RestRequest.WebMethod.PATCH, RestRequest.jsonPublisher(new FerdigstillJournalpostRequest(enhet)));
var request = RestRequest.newRequest(method, ferdigstill, restConfig);
restKlient.send(request, String.class);
return true;
} catch (Exception e) {
LOG.info("DOKARKIV FERDIGSTILL {} feilet for {}", journalpostId, enhet, e);
return false;
}
}
@Override
public void tilknyttVedlegg(TilknyttVedleggRequest request, String journalpostId) {
try {
var tilknyttPath = String.format("/%s/tilknyttVedlegg", journalpostId);
var uri = UriBuilder.fromUri(restConfig.endpoint()).path(tilknyttPath).build();
var method = new RestRequest.Method(RestRequest.WebMethod.PUT, RestRequest.jsonPublisher(request));
var rrequest = RestRequest.newRequest(method, uri, restConfig);
var tilknyttVedleggResponse = restKlient.send(rrequest, TilknyttVedleggResponse.class);
if (!tilknyttVedleggResponse.feiledeDokumenter().isEmpty()) {
throw new IllegalStateException(
"Følgende vedlegg feilet " + tilknyttVedleggResponse + " for journalpost " + journalpostId);
} else {
LOG.info("Vedlegg tilknyttet {} OK", journalpostId);
}
} catch (UriBuilderException | IllegalArgumentException e) {
throw new TekniskException("FPFORMIDLING-156531",
String.format("Feil ved oppretting av URI for tilknytning av vedlegg til %s: %s.", journalpostId, request.toString()), e);
}
}
}
|
package br.com.rafagonc.tjdata.repositories;
import br.com.rafagonc.tjdata.models.ESAJCaptcha;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ESAJCaptchaRepository extends JpaRepository<ESAJCaptcha, Long> {
@Query("SELECT c FROM ESAJCaptcha c WHERE c.state LIKE :state ORDER BY id DESC")
List<ESAJCaptcha> captchas(@Param("state") String state);
}
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.appcloud.provisioning.runtime.test;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.extensions.Deployment;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.appcloud.provisioning.runtime.KubernetesRuntimeProvisioningService;
import org.wso2.appcloud.provisioning.runtime.RuntimeProvisioningException;
import org.wso2.appcloud.provisioning.runtime.beans.DeploymentLogs;
import org.wso2.appcloud.provisioning.runtime.beans.LogQuery;
import java.util.HashMap;
import java.util.Map;
public class LoggingTest {
private static final Log log = LogFactory.getLog(LoggingTest.class);
public static TestUtils testUtils;
KubernetesRuntimeProvisioningService afKubClient;
Deployment deployment;
Namespace namespace;
@BeforeClass
public void initialize() throws RuntimeProvisioningException {
log.info("Starting Logging test case");
testUtils = new TestUtils();
namespace = testUtils.createNamespace();
deployment = testUtils.createDeployment();
}
/**
* Test getting snapshot logs of containers.
*
* @throws RuntimeProvisioningException
*/
@Test(groups = {"org.wso2.carbon.appfactory.provisioning.runtime" }, description = "Kub get snapshot logs")
public void testSnapshotLogs() throws RuntimeProvisioningException, InterruptedException {
DeploymentLogs deploymentLogs;
Map<String, String> selector = new HashMap<>();
selector.put("app", "My-JAXRS");
afKubClient = new KubernetesRuntimeProvisioningService(testUtils.getAppCtx());
//Initially waits until deployment successful
log.info("Waiting for deployment to complete : " + deployment.getMetadata().getName());
Thread.sleep(60000);
int counter;
//todo get the upper bound value from a config
for (counter = 0; counter < 10; counter++) {
if (testUtils.getPodStatus(namespace, selector)) {
log.info("Pod status : Running");
//Waiting until tomcat starts
log.info("Waiting until server startup complete ");
Thread.sleep(10000);
deploymentLogs = afKubClient.getRuntimeLogs(null);
Map<String, String> logs = deploymentLogs.getDeploymentLogs();
for (Map.Entry<String, String> logEntry : logs.entrySet()) {
String logSegment = logEntry.getValue();
Assert.assertTrue(logSegment.indexOf("Starting service Catalina") > 0);
}
break;
} else {
log.info("Pod status : Pending");
log.info("Retrying until deployment complete : " + deployment.getMetadata().getName());
//If deployment is not successful check again in 30 seconds
Thread.sleep(30000);
}
if (counter == 9) {
log.info("Pods didn't start Running during the retrying period");
Assert.assertTrue(false);
}
}
}
/**
* Test getting logs with specific number of records by querying in deployed containers.
*
* @throws RuntimeProvisioningException
*/
@Test(dependsOnMethods = "testSnapshotLogs", groups = {"org.wso2.carbon.appfactory.provisioning.runtime" },
description = "Kub snapshot logs with querying records count")
public void testLogsWithQueryRecords() throws RuntimeProvisioningException, InterruptedException {
DeploymentLogs deploymentLogs;
Map<String, String> selector = new HashMap<>();
selector.put("app", "My-JAXRS");
afKubClient = new KubernetesRuntimeProvisioningService(testUtils.getAppCtx());
LogQuery query = new LogQuery(false, 1000, -1);
//Initially waits until deployment successful
log.info("Waiting for deployment to complete : " + deployment.getMetadata().getName());
Thread.sleep(60000);
//todo get the upper bound value from a config
int counter;
for (counter = 0; counter < 10; counter++) {
if (testUtils.getPodStatus(namespace, selector)) {
log.info("Pod status : Running");
//Waiting until tomcat starts
log.info("Waiting until server startup complete ");
Thread.sleep(10000);
deploymentLogs = afKubClient.getRuntimeLogs(query);
Map<String, String> logs = deploymentLogs.getDeploymentLogs();
for (Map.Entry<String, String> logEntry : logs.entrySet()) {
String logSegment = logEntry.getValue();
Assert.assertTrue(logSegment.indexOf("Starting service Catalina") > 0);
}
break;
} else {
log.info("Pod status : Pending");
log.info("Retrying until deployment complete : " + deployment.getMetadata().getName());
//If deployment is not successful check again in 30 seconds
Thread.sleep(30000);
}
if (counter == 9) {
log.info("Pods didn't start Running during the retrying period");
Assert.assertTrue(false);
}
}
}
/**
* Test getting logs in a specific duration by querying in deployed containers.
*
* @throws RuntimeProvisioningException
*/
@Test(dependsOnMethods = "testLogsWithQueryRecords", groups = {"org.wso2.carbon.appfactory.provisioning.runtime" },
description = "Kub snapshot logs with querying duration")
public void testLogsWithQueryDuration() throws RuntimeProvisioningException, InterruptedException {
DeploymentLogs deploymentLogs;
Map<String, String> selector = new HashMap<>();
selector.put("app", "My-JAXRS");
afKubClient = new KubernetesRuntimeProvisioningService(testUtils.getAppCtx());
LogQuery query = new LogQuery(false, -1, 1);
//Initially waits until deployment successful
log.info("Waiting for deployment to complete : " + deployment.getMetadata().getName());
Thread.sleep(60000);
//todo get the upper bound value from a config
int counter;
for (counter = 0; counter < 10; counter++) {
if (testUtils.getPodStatus(namespace, selector)) {
log.info("Pod status : Running");
//Waiting until tomcat starts
log.info("Waiting until server startup complete ");
Thread.sleep(10000);
deploymentLogs = afKubClient.getRuntimeLogs(query);
Map<String, String> logs = deploymentLogs.getDeploymentLogs();
for (Map.Entry<String, String> logEntry : logs.entrySet()) {
String logSegment = logEntry.getValue();
Assert.assertTrue(logSegment.indexOf("Starting service Catalina") > 0);
}
break;
} else {
log.info("Pod status : Pending");
log.info("Retrying until deployment complete : " + deployment.getMetadata().getName());
//If deployment is not successful check again in 30 seconds
Thread.sleep(30000);
}
if (counter == 9) {
log.info("Pods didn't start Running during the retrying period");
Assert.assertTrue(false);
}
}
}
/**
* Test log streaming in deployed containers.
*
* @throws RuntimeProvisioningException
*/
// @Test(groups = {"org.wso2.carbon.appfactory.provisioning.runtime" }, description = "Kub Logging")
public void testLogStream() throws RuntimeProvisioningException, InterruptedException {
LogQuery query = new LogQuery(true, -1, 1);
Map<String, String> selector = new HashMap<>();
selector.put("app", "My-JAXRS");
//Initially waits until deployment successful
Thread.sleep(30000);
for (int i = 0; i < 5; i++) {
if (testUtils.getPodStatus(namespace, selector)) {
afKubClient.streamRuntimeLogs();
} else {
//If deployment is not successful check again in 30 seconds
Thread.sleep(30000);
}
//todo add assertions
}
}
//@AfterClass
private void cleanup() throws InterruptedException {
log.info("Cleaning up the namespace");
testUtils.deleteNamespace();
Thread.sleep(30000);
}
}
|
package io.codex.cryptogram.encoding;
import org.apache.commons.codec.binary.Hex;
/**
* 十六进制编码器
*
* @author 杨昌沛 646742615@qq.com
* 2018/10/17
*/
public class HexEncoder implements Encoder {
public String algorithm() {
return "Hex";
}
public String encode(byte[] data) {
return new String(Hex.encodeHex(data));
}
}
|
package common.util;
public class GeoUtil {
public static float oneMileLat = 0.0145f;
public static float[] oneMileLngTable = {
0.0144f, 0.0144f, 0.0144f, 0.0144f, 0.0145f, 0.0145f, 0.0145f, 0.0145f,
0.0146f, 0.0146f, 0.0146f, 0.0147f, 0.0147f, 0.0148f, 0.0149f, 0.0149f,
0.0150f, 0.0151f, 0.0152f, 0.0153f, 0.0154f, 0.0155f, 0.0156f, 0.0157f,
0.0158f, 0.0159f, 0.0161f, 0.0162f, 0.0163f, 0.0165f, 0.0167f, 0.0168f,
0.0170f, 0.0172f, 0.0174f, 0.0176f, 0.0178f, 0.0181f, 0.0183f, 0.0186f,
0.0188f, 0.0191f, 0.0194f, 0.0197f, 0.0201f, 0.0204f, 0.0208f, 0.0212f,
0.0216f, 0.0220f, 0.0225f, 0.0229f, 0.0235f, 0.0240f, 0.0246f, 0.0252f,
0.0258f, 0.0265f, 0.0273f, 0.0281f, 0.0289f, 0.0298f, 0.0308f, 0.0318f,
0.0330f, 0.0342f, 0.0355f, 0.0370f, 0.0386f, 0.0403f, 0.0423f, 0.0444f,
0.0468f, 0.0495f, 0.0525f, 0.0559f, 0.0598f, 0.0643f, 0.0696f, 0.0758f,
0.0833f, 0.0925f, 0.1040f, 0.1187f, 0.1384f, 0.1660f, 0.2074f, 0.2765f,
0.4147f, 0.8293f,
};
public static GeoRange getRange(float lat, float lng, float miles) {
float oneMileLng = oneMileLngTable[(int) lat];
float latDiff = oneMileLat * miles;
float lngDiff = oneMileLng * miles;
float minLat = lat - latDiff;
float maxLat = lat + latDiff;
float minLng = lng - lngDiff;
float maxLng = lng + lngDiff;
GeoRange range = new GeoRange();
range.setMinLat(minLat);
range.setMaxLat(maxLat);
range.setMinLng(minLng);
range.setMaxLng(maxLng);
return range;
}
public static double distance(double lat1, double lon1, double lat2, double lon2) {
return distance(lat1, lon1, lat2, lon2, 'M');
}
public static double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
if (Math.abs(lat1 - lat2) < 0.000001 && Math.abs(lon1 - lon2) < 0.000001)
return 0.0;
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1))
* Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
public static class GeoRange {
private float minLat;
private float maxLat;
private float minLng;
private float maxLng;
public float getMaxLat() {
return maxLat;
}
public void setMaxLat(float maxLat) {
this.maxLat = maxLat;
}
public float getMinLng() {
return minLng;
}
public void setMinLng(float minLng) {
this.minLng = minLng;
}
public float getMaxLng() {
return maxLng;
}
public void setMaxLng(float maxLng) {
this.maxLng = maxLng;
}
public void setMinLat(float minLat) {
this.minLat = minLat;
}
public float getMinLat() {
return minLat;
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DataAccess;
import Entity.Account;
import Utility.SQLHelper;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author TUNT
*/
public class AccountDAL {
private ResultSet objResult;
private static AccountDAL instance;
public static AccountDAL getInstance() {
if (instance == null) {
instance = new AccountDAL();
}
return instance;
}
public boolean addAccount(Account account) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String[] params = new String[10];
params[0] = String.valueOf(account.getRoleID());
params[1] = account.getUsername();
params[2] = account.getPassword();
params[3] = account.getFirstName();
params[4] = account.getLastName();
params[5] = sdf.format(account.getBirthday());
params[6] = String.valueOf(account.isGender());
params[7] = account.getAddress();
params[8] = account.getPhone();
params[9] = account.getEmail();
try {
if (SQLHelper.getInstance().executeUpdate("Ins_Account", params) < 0) {
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean updateAccount(Account account) {
try {
String[] params = new String[11];
params[0] = String.valueOf(account.getAccountID());
params[1] = String.valueOf(account.getRole().getRoleID());
params[2] = account.getUsername();
params[3] = account.getFirstName();
params[4] = account.getLastName();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
params[5] = sdf.format(account.getBirthday());
params[6] = String.valueOf(account.isGender());
params[7] = account.getAddress();
params[8] = account.getPhone();
params[9] = account.getEmail();
params[10] = String.valueOf(account.isAllowLogin());
if (SQLHelper.getInstance().executeUpdate("Udp_Account", params) < 0) {
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean deleteAccount(Account account) {
try {
String[] params = new String[1];
params[0] = String.valueOf(account.getAccountID());
if (SQLHelper.getInstance().executeUpdate("proc name", params) < 0) {
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean changePassword(int accountID, String oldPassword, String newPassword) {
String[] params = new String[3];
params[0] = String.valueOf(accountID);
params[1] = oldPassword;
params[2] = newPassword;
try {
if (SQLHelper.getInstance().executeUpdate("changePassword", params) < 0) {
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public Account getAccountById(int id) {
String[] params = new String[1];
params[0] = String.valueOf(id);
Account a = new Account();
try {
ResultSet rs = SQLHelper.getInstance().executeQuery("Sel_AccountById", params);
while (rs.next()) {
a = CreateAccountByResultSet(rs);
}
} catch (Exception ex) {
Logger.getLogger(AccountDAL.class.getName()).log(Level.SEVERE, null, ex);
}
return a;
}
public int getAccountIDByUsername(String username) {
String[] params = new String[2];
params[0] = username;
params[1] = null;
int result = 0;
try {
CallableStatement objCall = SQLHelper.getInstance().execute("Sel_getAcountIdByUsername", params);
result = objCall.getInt("Result");
} catch (Exception ex) {
}
return result;
}
public int accountLogin(Account a) {
Account account = new Account();
account.setUsername(a.getUsername());
account.setPassword(a.getPassword());
String[] params = new String[3];
params[0] = a.getUsername();
params[1] = a.getPassword();
params[2] = null;
int result = 0;
try {
CallableStatement objCall = SQLHelper.getInstance().execute("AccountLogin", params);
result = objCall.getInt("Result");
} catch (Exception ex) {
Logger.getLogger(AccountDAL.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public List<Account> getAdminList() {
List<Account> accountList = new ArrayList<Account>();
try {
objResult = SQLHelper.getInstance().executeQuery("Sel_AllAdmin", null);
while (objResult.next()) {
accountList.add(CreateAccountByResultSet(objResult));
}
} catch (Exception ex) {
ex.printStackTrace();
}
return accountList;
}
public List<Account> getCustomerList() {
List<Account> accountList = new ArrayList<Account>();
try {
objResult = SQLHelper.getInstance().executeQuery("Sel_AllCustomer", null);
while (objResult.next()) {
accountList.add(CreateAccountByResultSet(objResult));
}
} catch (Exception ex) {
ex.printStackTrace();
}
return accountList;
}
public List<Account> getEmployeeList() {
List<Account> accountList = new ArrayList<Account>();
try {
objResult = SQLHelper.getInstance().executeQuery("Sel_AllEmployee", null);
while (objResult.next()) {
accountList.add(CreateAccountByResultSet(objResult));
}
} catch (Exception ex) {
ex.printStackTrace();
}
return accountList;
}
public Account CreateAccountByResultSet(ResultSet objResult) {
Account account = new Account();
try {
account.setAccountID(objResult.getInt("AccountID"));
account.setRole(RoleDAL.getInstance().CreateRoleByResultSet(objResult));
account.setUsername(objResult.getString("Username"));
account.setPassword(objResult.getString("Password"));
account.setFirstName(objResult.getString("FirstName"));
account.setLastName(objResult.getString("LastName"));
account.setBirthday(objResult.getDate("Birthday"));
account.setGender(objResult.getBoolean("Gender"));
account.setAddress(objResult.getString("Address"));
account.setPhone(objResult.getString("Phone"));
account.setEmail(objResult.getString("Email"));
account.setAllowLogin(objResult.getBoolean("AllowLogin"));
} catch (Exception ex) {
ex.printStackTrace();
try {
return getAccountById(objResult.getInt("AccountID"));
} catch (SQLException ex1) {
}
}
return account;
}
} |
package com.codehunte.tis91d.restcontrollers;
import com.codehunte.tis91d.model.Person;
import com.codehunte.tis91d.services.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/person")
public class PersonRestController {
@Autowired
PersonService service;
@GetMapping("/list")
public List<Person> list() {
return service.list();
}
@PostMapping("/add")
public void add(@RequestBody Person person) {
service.add(person);
}
@PutMapping("/update/{id}")
public void update(@RequestBody Person person, @PathVariable int id) {
service.update(person, id);
}
@DeleteMapping("/delete/{id}")
public void delete(@PathVariable int id) {
service.delete(id);
}
}
|
package diplomski.autoceste.repositories;
import diplomski.autoceste.models.Discount;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
import java.util.List;
public interface DiscountRepository extends JpaRepository<Discount, Long> {
List<Discount> findByStartDateLessThanAndEndDateGreaterThan(LocalDate startDate, LocalDate endDate);
}
|
package com.example.kevpreneur.smartshopper;
import android.content.Intent;
import android.net.wifi.hotspot2.pps.Credential;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.android.volley.toolbox.HttpResponse;
import java.io.IOException;
import java.util.ArrayList;
public class Cart extends AppCompatActivity {
String[] productArray = {"Apples (pack of 5) - MUR 80.94",
"Bananas (1kg) - MUR 50.68",
"Oranges (pack of 5) - MUR 11.50",
"Pineapple - MUR 50.69",
"Mango - MUR 70.75",
"Potatoes (2.5kg) - MUR 11.98",
"Tomatoes (1kg) - MUR 21.99",
"Onions (pack of 4) - MUR 51.83",
"Lettuce - MUR 47.49",
"Rice (1kg) - MUR 40.48",
"Pasta (1kg) - MUR 80.00",
"Bread (800g loaf) - MUR 15.00",
"Pizza (350g) - MUR 40.60",
"Beef Mince (500g) - MUR 75.99",
"Chicken Breast (pack of 2) - MUR 78.00",
"Salmon Fillets (pack of 2) - MUR 500.23",
"Pasta Sauce (500g jar) - MUR 41.84",
"Curry Sauce (500g jar) - MUR 20.84",
"Cheese (250g) - MUR 23.74",
"Butter (250g) - MUR 20.92",
"Plain Yoghurt (500g) - MUR 60.94",
"Milk (568ml / 1pint) - MUR 20.58",
"Milk (2.27L / 4pints) - MUR 150.89",
"Fresh Orange Juice (1L) - MUR 20.69",
"Cola (2L) - MUR 25.00",
"Beer (pack of 4 bottles) - MUR 410.00"};
// ArrayList<String> cartItems = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
// cartItems.add("Colgate");
// cartItems.add("Shoe");
// cartItems.add("Laptop");
// cartItems.add("Mouse");
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.activity_listview,productArray);
ListView listView = (ListView) findViewById(R.id.items_List);
listView.setAdapter(adapter);
findViewById(R.id.btn_scan_product).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Cart.this, ScanActivity.class));
}
});
findViewById(R.id.btn_pay).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mcbAPICall();
}
});
}
public void mcbAPICall(){
oAuth();
}
String token;
WebView webview;
public void oAuth() {
webview = new WebView(this);
setContentView(webview);
webview.loadUrl("https://mcboauth3.azurewebsites.net/oauth/authorize?client_id=59b2e360-a0ad-449a-b364-3be2c46b7b3e&response_type=token&redirect_uri=http://smartshopper?&response_mode=query&scope=read,write");
// webview.setWebViewClient(new WebViewClient(){
// @Override
// public void onLoadResource(WebView view, String url) {
// super.onPageFinished(view, url);
// Log.e("test", "------Url:" + url);
// if (url.contains("?#access_token")) {
// token = webview.getUrl().substring(35, -36);
// startActivity(new Intent(getApplicationContext(), ReceiptActivity.class));
// }
// }
// });
}
//
// public void addToCart (ProductDetails.Product product){
//// repository.add(product);
// }
//
// public void removeFromCart (ProductDetails.Product product){
//// repository.remove(product);
// }
//
// private void getRepoItems(){
// for (ProductDetails.Product product : repository ){
// cartItems.add(product.getName());
// }
// }
}
|
package com.jalsalabs.ticklemyphonefull;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AntiTheftContact extends Activity {
static EditText alternativeemail;
static EditText alternativeno1;
static EditText alternativeno2;
static Button updatecontacts;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
TML_Library.SetFullScreen(this);
setContentView(R.layout.antitheftcontact);
TML_Library.Debug("0.0001");
}
public void onResume() {
super.onResume();
setContentView(R.layout.antitheftcontact);
alternativeno1 = (EditText) findViewById(R.id.alternativeno1);
alternativeno2 = (EditText) findViewById(R.id.alternativeno2);
alternativeemail = (EditText) findViewById(R.id.alternativeemail);
updatecontacts = (Button) findViewById(R.id.updatecontacts);
String LS_second_phone = TML_Library.GetprefnoAT(this, "SIM_SECONDARY_PHONE");
String LS_second_phone2 = TML_Library.GetprefnoAT(this, "SIM_SECONDARY_PHONE2");
String LS_second_email = TML_Library.GetprefnoAT(this, "SIM_SECONDARY_EMAIL");
if (LS_second_phone.equals("@")) {
LS_second_phone = "";
}
if (LS_second_phone2.equals("@")) {
LS_second_phone2 = "";
}
if (LS_second_email.equals("@")) {
LS_second_email = "";
}
alternativeno1.setText(LS_second_phone);
alternativeno2.setText(LS_second_phone2);
alternativeemail.setText(LS_second_email);
if (TML_Library.GetprefnoAT(this, "KEY_IS_FREE").equals("Y")) {
TML_Library.PutToast(this, "Please note SIM change settings done here will not be saved. Since you are using Free Version");
TML_Library.UpdateSettingsBacktoFree(this);
}
updatecontacts.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TML_Library.HapticFeedback(AntiTheftContact.this);
String LS_second_phone = AntiTheftContact.alternativeno1.getText().toString();
String LS_second_phone2 = AntiTheftContact.alternativeno2.getText().toString();
String LS_second_email = AntiTheftContact.alternativeemail.getText().toString();
TML_Library.SetPref(AntiTheftContact.this, "SIM_SECONDARY_PHONE", LS_second_phone);
TML_Library.SetPref(AntiTheftContact.this, "SIM_SECONDARY_PHONE2", LS_second_phone2);
TML_Library.SetPref(AntiTheftContact.this, "SIM_SECONDARY_EMAIL", LS_second_email);
}
});
}
}
|
package calendar;
import enums.TestConstants;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class CalendarTest {
public static void main(String[] args) throws InterruptedException {
System.setProperty(TestConstants.CHROME_DRIVER.toString(), TestConstants.DRIVER_PATH.toString());
WebDriver driver = new ChromeDriver();
driver.get("https://www.spicejet.com/");
//(//a[@value="MAA"])[2]
//a[@value="BLR"]
WebElement from, to, departDate;
Thread.sleep(4000);
from = driver.findElement(By.xpath(".//*[@id=\"ctl00_mainContent_ddl_originStation1_CTXT\"]"));
from.click();
Thread.sleep(4000);
driver.findElement(By.xpath("//a[@value=\"BLR\"]")).click();
Thread.sleep(2000);
to = driver.findElement(By.xpath("//*[@id=\"ctl00_mainContent_ddl_destinationStation1_CTXT\"]"));
to.click();
Thread.sleep(2000);
driver.findElement(By.xpath("(//a[@value=\"MAA\"])[2]")).click();
//*[@id="ctl00_mainContent_ddl_originStation1_CTNR"]
Thread.sleep(2000);
/* Calendar */
departDate = driver.findElement(By.xpath("//*[@id=\"ui-datepicker-div\"]/div[1]/table/tbody/tr[4]/td[2]/a"));
departDate.click();
driver.close();
}
}
|
import javax.swing.JOptionPane;
public class Conta implements BancoInterface {
private String numero;
private double saldo;
private String dataAbertura;
private Titular titular;
private Banco banco;
public static int proximoNumero = 1;
//Método Construtor da Classe
public Conta(Titular titular, Banco banco) {
this.numero = Integer.toString(Conta.proximoNumero);
this.saldo = 0;
this.banco = banco;
this.titular = titular;
this.dataAbertura = Long.toString(System.currentTimeMillis());
}
public boolean sacar(double valor) {
if(this.saldo >= valor) {
//saldo = saldo - valor;
this.saldo -= valor;
return true;
}else {
JOptionPane.showMessageDialog(null, "Saldo Insuficiente!",
"ATENÇÃO", JOptionPane.ERROR_MESSAGE);
return false;
}
}
public void depositar(double valor) {
if(valor <= 0) {
JOptionPane.showMessageDialog(null, "Valor Inválido!",
"ATENÇÃO", JOptionPane.WARNING_MESSAGE);
}else {
this.saldo += valor;
}
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public double getSaldo() {
return saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
public String getDataAbertura() {
return dataAbertura;
}
public void setDataAbertura(String dataAbertura) {
this.dataAbertura = dataAbertura;
}
public Titular getTitular() {
return titular;
}
public void setTitular(Titular titular) {
this.titular = titular;
}
public Banco getBanco() {
return banco;
}
public void setBanco(Banco banco) {
this.banco = banco;
}
public String imprimirDados() {
String dados = this.getBanco().imprimeDados()
+ "\n \n Dados de Conta:"
+ "\n Número: " + this.getNumero()
+ "\n Data de Abertura: " + this.getDataAbertura()
+ "\n Saldo: R$ " + this.getSaldo() + "\n\n"
+ this.getTitular().imprimirDados();
return dados;
}
public boolean transferir(double valor) {
return false;
}
}
|
package net.acomputerdog.BlazeLoader.api.chat;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
/**
* API for chat-related functions.
*/
public class ApiChat {
/**
* Sends a raw chat to a command user.
*
* @param user The command user to send the chat to.
* @param message The message to send.
*/
public static void sendChat(ICommandSender user, String message) {
user.addChatMessage(new ChatComponentText(message));
}
}
|
package io.rong.imkit;
import android.app.Activity;
/**
* Created by Bob on 2018/6/19.
*/
public class MainActivity extends Activity {
}
|
package aaa.assignment1.tests;
import aaa.Agent;
import aaa.PredatorRandom;
import aaa.PreySimple;
import aaa.State;
import aaa.StateSimple;
import aaa.assignment1.algorithms.IterativePolicyEvaluation;
/**
* TEST 3 (Assignment 1.2)
* Tests the Iterative Policy Evaluation against the random predator's policy and then prints the state-value function for some states.
* The number of iterations performed by the algorithm is also displayed.
* @author josago
*/
public class Test3
{
public static final float THETA = 0.000000001f;
public static final float GAMMA = 0.8f;
public static void main(String[] args)
{
State stateInitial = new StateSimple(0, 0, 5, 5);
Agent predator = new PredatorRandom();
Agent prey = new PreySimple();
IterativePolicyEvaluation ipe = new IterativePolicyEvaluation(stateInitial, predator, prey, THETA, GAMMA);
System.out.println(ipe.getEvaluation(new StateSimple(0, 0, 5, 5)));
System.out.println(ipe.getEvaluation(new StateSimple(2, 3, 5, 4)));
System.out.println(ipe.getEvaluation(new StateSimple(2, 10, 10, 0)));
System.out.println(ipe.getEvaluation(new StateSimple(10, 10, 0, 0)));
System.out.println("The IPE algorithm converged in " + ipe.getIterations() + " iterations.");
}
}
|
package DataStructure.Stack;
public class App {
public static void main(String[] args) {
Stack theStack = new Stack(10); // a is size of stack or array implementation of stack
theStack.push('h');
theStack.push('e');
theStack.push('l');
theStack.push('l'); // this is most recent item and will be removed first
theStack.push('o');
// for pop
while (!theStack.isEmpty()) {
char a = theStack.pop();
System.out.print(a);
}
}
public static String reveresString(String str) {
int strLength = str.length();
Stack theNewStack = new Stack(strLength);
for (int i = 0; i < strLength; i++) {
theNewStack.push(str.charAt(i));
}
String result = "";
while (!theNewStack.isEmpty()) {
char eachElement = theNewStack.pop();
result += eachElement;
}
return result;
}
}
|
package com.example.mdt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Lightsensor extends AppCompatActivity {
private static final int STORAGE_PERMISSION_REQUEST_CODE = 0;
private static final int REQUEST_WRITE_PERMISSION = 0;
Button save;
DatabaseHelper databaseHelper;
ArrayList arrayList;
String s = "";
Button btn20;
TextView TV, tv70;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lightsensor);
btn20 = (Button)findViewById(R.id.btn20);
TV = (TextView)findViewById(R.id.TV);
tv70 = (TextView)findViewById(R.id.tv70);
btn20.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SensorManager mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor lightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(lightSensor != null){
TV.setText("Sensor.TYPE_LIGHT Available");
Toast.makeText(getApplicationContext()," ✔ "+"Light Sensor is working fine",Toast.LENGTH_LONG).show();
s = tv70.getText().toString()+"\n"+" ✔ "+"Light Sensor is working fine"+"\n\n";
mySensorManager.registerListener(
lightSensorListener,
lightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
TV.setText("Sensor.TYPE_LIGHT NOT Available");
Toast.makeText(getApplicationContext()," X "+"Device doesn't support light sensor",Toast.LENGTH_LONG).show();
s = tv70.getText().toString()+"\n"+" X "+"Device doesn't support light sensor"+"\n\n";
}
}
});
databaseHelper = new DatabaseHelper(this);
arrayList = databaseHelper.getAllText();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = s;
if (!text.isEmpty()){
if(databaseHelper.addText(text)){
Toast.makeText(getApplicationContext(), "Data Saved...", Toast.LENGTH_SHORT).show();
arrayList.clear();
arrayList.addAll(databaseHelper.getAllText());
}
}
}
});
}
private final SensorEventListener lightSensorListener
= new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_LIGHT){
TV.setText("LIGHT: " + event.values[0]);
}
}
};
} |
package Hackathon;
import java.util.Scanner;
public class Library {
public static void library() {
int i = Stats.getIntel();
Scanner input = new Scanner(System.in);{
for (int j = 0; j < 3; j++) {
if(i <= 0) {
int a = (int)(Math.random() * 5);
int b = (int)(Math.random() * 5);
System.out.print("Solve:" + a+"+"+b+"=?" );
int answer = a + b;
int ansIn = input.nextInt();
if(answer == ansIn) {
Stats.setIntel(1);
Stats.setGold(25);
System.out.println ( "Intelligence + 1, Gold + 25" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
if(i == 1) {
int a = (int)(Math.random() * 25);
int b = (int)(Math.random() * 25);
System.out.print("Solve:" + a+"-"+b+"=?" );
int answer = a - b;
int ansIn = input.nextInt();
if(answer == ansIn) {
Stats.setIntel(1);
Stats.setGold(50);
System.out.println ( "Intelligence + 1, Gold + 50" );
}
else {
Stats.setIntel(-1);
}
}
if(i == 2) {
System.out.print("Solve:Why did the chicken cross the Road?" );
String answer = input.nextLine();
answer = input.nextLine();
if(answer.equals ( "to get to the other side" ) || answer.equals ( "to get to the other side" ) ) {
Stats.setIntel(1);
Stats.setGold(100);
System.out.println ( "Intelligence + 1, Gold + 100" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
if(i == 3) {
int a = (int)(Math.random() * 1000);
int b = (int)(Math.random() * 1000);
System.out.print("Solve:" + a+"+"+b+"=?" );
int answer = a + b;
int ansIn = input.nextInt();
if(answer == ansIn) {
Stats.setIntel(1);
Stats.setGold(150);
System.out.println ( "Intelligence + 1, Gold + 150" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
if(i == 4) {
int a = (int)(Math.random() * 5);
int b = (int)(Math.random() * 5);
System.out.print("Solve:We have a barrel in the shape of a cylinder, the base is a circle with a radius of"+ a +"and the height is"+ b +"what is the volume of the Barrel?");
int answer = (int) ((Math.PI)*(Math.pow(a, 2)) * b );
int ansIn = input.nextInt();
if(answer == ansIn) {
Stats.setIntel(1);
Stats.setGold(200);
System.out.println ( "Intelligence + 1, Gold + 200" );
}
else {
Stats.setIntel(-1);
}
}
if(i == 5) {
int a = (int)(Math.random() * 11);
int b = (int)(Math.random() * 21);
System.out.print("Solve:We have a pile of grain in the shape of a circlular prism , The raduis of the base is"+ a +"and the height is"+ b +"what is the volume of the pile of grain?");
int answer = (int) ((1/3)*(Math.PI)*(Math.pow(a, 2)) * b );
int ansIn = input.nextInt();
if(answer == ansIn) {
Stats.setIntel(1);
Stats.setGold(250);
System.out.println ( "Intelligence + 1, Gold + 250" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
if(i == 6) {
System.out.print("Solve:What common English verb becomes its own past tence by rearranging its letters?" );
String answer = input.nextLine();
if(answer == "eat" || answer == "Eat" ) {
Stats.setIntel(1);
Stats.setGold(300);
System.out.println ( "Intelligence + 1, Gold + 300" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
if(i == 7) {
int a = (int)(Math.random() * 100);
System.out.print("Solve:If "+a+" is the tempature in Fahrenheit what would that be in celcius?");
int answer = ((5/9)*(a-32));
int ansIn = input.nextInt();
if(answer == ansIn) {
Stats.setIntel(1);
Stats.setGold(350);
System.out.println ( "Intelligence + 1, Gold + 350" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
if(i == 8) {
System.out.print("Solve:If Jack is older then Jenny. Jimmy is older Jack. Jenny is older then Jimmy. If the First two statements are true. Is the third statement true?" );
String answer = input.nextLine();
if(answer == "no" || answer == "No" ) {
Stats.setIntel(1);
Stats.setGold(400);
System.out.println ( "Intelligence + 1, Gold + 400" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
if(i == 9) {
int a = (int)(Math.random() * 25);
int b = (int)(Math.random() * 50);
System.out.print("Solve:We have another much bigger pile of grain in the shape of a circlular prism , The raduis of the base is"+ a +"and the height is"+ b +"what is the volume of the pile of grain?");
int answer = (int) ((1/3)*(Math.PI)*(Math.pow(a, 2)) * b );
int ansIn = input.nextInt();
if(answer == ansIn) {
Stats.setIntel(1);
Stats.setGold(450);
System.out.println ( "Intelligence + 1, Gold + 450" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
if(i == 10) {
System.out.print("Solve:It occurs once in a minute, twice in a moment, but never in an hour?" );
String answer = input.nextLine();
if(answer == "m" || answer == "M" ) {
Stats.setIntel(0);
Stats.setGold(500);
System.out.println ( "Intelligence + 1, Gold + 500" );
}
else {
Stats.setIntel(-1);
System.out.println ( "Intelligence - 1" );
}
}
i++;
}
}
}
}
|
package io.breen.socrates.model.wrapper;
import io.breen.socrates.model.event.*;
import io.breen.socrates.submission.Submission;
import io.breen.socrates.util.Observable;
import io.breen.socrates.util.*;
import io.breen.socrates.util.Observer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import java.util.*;
/**
* A class that "wraps" a Submission object. Serves as the parent of all SubmittedFileWrapperNode
* objects in the submission tree. Also observes its children so that its "completed" state can be
* computed if all of its children's tests are complete.
*/
public class SubmissionWrapperNode extends DefaultMutableTreeNode
implements Observer<SubmittedFileWrapperNode>, Observable<SubmissionWrapperNode>
{
protected final List<Observer<SubmissionWrapperNode>> observers;
private final Set<SubmittedFileWrapperNode> unfinishedFiles;
/**
* Whether a grade report has been saved for this submission.
*/
private boolean saved;
public SubmissionWrapperNode(Submission submission) {
super(submission);
saved = false;
unfinishedFiles = new HashSet<>();
observers = new LinkedList<>();
}
public boolean isComplete() {
return unfinishedFiles.isEmpty();
}
@Override
public void add(MutableTreeNode newChild) {
if (newChild instanceof SubmittedFileWrapperNode) {
SubmittedFileWrapperNode sfwn = (SubmittedFileWrapperNode)newChild;
super.add(newChild);
if (!sfwn.isComplete()) unfinishedFiles.add(sfwn);
sfwn.addObserver(this);
} else if (newChild instanceof UnrecognizedFileWrapperNode) {
super.add(newChild);
} else {
throw new IllegalArgumentException();
}
}
@Override
public void objectChanged(ObservableChangedEvent<SubmittedFileWrapperNode> event) {
// any change of submitted files should invalidate saved state
setSaved(false);
int numBefore = unfinishedFiles.size();
if (event instanceof FileCompletedChangeEvent) {
FileCompletedChangeEvent e = (FileCompletedChangeEvent)event;
if (e.isNowComplete) unfinishedFiles.remove(e.source);
else unfinishedFiles.add(e.source);
}
int numAfter = unfinishedFiles.size();
SubmissionCompletedChangeEvent e;
if (numBefore == 0 && numAfter > 0) {
e = new SubmissionCompletedChangeEvent(this, false);
for (Observer<SubmissionWrapperNode> o : observers)
o.objectChanged(e);
} else if (numBefore > 0 && numAfter == 0) {
e = new SubmissionCompletedChangeEvent(this, true);
for (Observer<SubmissionWrapperNode> o : observers)
o.objectChanged(e);
}
}
@Override
public void addObserver(Observer<SubmissionWrapperNode> observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer<SubmissionWrapperNode> observer) {
observers.remove(observer);
}
public boolean isSaved() {
return saved;
}
public void setSaved(boolean saved) {
if (saved == this.saved) return;
this.saved = saved;
GradeReportSavedEvent e = new GradeReportSavedEvent(this);
for (Observer<SubmissionWrapperNode> o : observers)
o.objectChanged(e);
}
}
|
package org.tudresden.ecatering.model.accountancy;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToOne;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.javamoney.moneta.Money;
import org.salespointframework.order.Order;
import org.salespointframework.payment.PaymentMethod;
import org.tudresden.ecatering.model.customer.Customer;
@Entity
public class MealOrder extends Order {
private static final long serialVersionUID = -2060482524899570502L;
@OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL) private Address invoiceAddress;
private Discount discount;
@SuppressWarnings({ "deprecation", "unused" })
private MealOrder() {}
public MealOrder(Customer customer, PaymentMethod paymentMethod, Address invoiceAddress) {
super(customer.getUserAccount(),paymentMethod);
this.invoiceAddress = invoiceAddress;
this.discount = customer.getDiscount();
}
/**
* returns the Invoiceaddress
* @return Invoiceaddress
*/
public Address getInvoiceAddress() {
return invoiceAddress;
}
/**
* returns the Discount
* @return Discount
*/
public Discount getDiscount() {
return discount;
}
/**
* Assigns new invoiceAddress
*/
public void setInvoiceAddress(Address invoiceAddress) {
this.invoiceAddress = invoiceAddress;
}
/**
* returns the Totalprice
* @return Totalprice
*/
@Override
public Money getTotalPrice() {
return super.getTotalPrice().multiply(discount.getDiscountFactor());
}
@Override
public int hashCode() {
return new HashCodeBuilder(171, 259).
append(super.hashCode()).
append(invoiceAddress).
append(discount).
toHashCode();
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package com.vicutu.persistence.query.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.vicutu.persistence.query.CriterionLikeMatchMode;
import com.vicutu.persistence.query.CriterionRestriction;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
public @interface QueryProperty {
String target() default "";
CriterionRestriction restriction() default CriterionRestriction.EQUAL;
CriterionLikeMatchMode matchMode() default CriterionLikeMatchMode.ANYWHERE;
}
|
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.entity.Llama;
import me.libraryaddict.disguise.disguisetypes.AnimalColor;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class LlamaWatcher extends ChestedHorseWatcher {
public LlamaWatcher(Disguise disguise) {
super(disguise);
}
public void setColor(Llama.Color color) {
setData(MetaIndex.LLAMA_COLOR, color.ordinal());
sendData(MetaIndex.LLAMA_COLOR);
}
public Llama.Color getColor() {
return Llama.Color.values()[getData(MetaIndex.LLAMA_COLOR)];
}
public void setCarpet(AnimalColor color) {
setData(MetaIndex.LLAMA_CARPET, color.getId());
sendData(MetaIndex.LLAMA_CARPET);
}
public AnimalColor getCarpet() {
return AnimalColor.getColor(getData(MetaIndex.LLAMA_CARPET));
}
public void setStrength(int strength) {
setData(MetaIndex.LLAMA_STRENGTH, strength);
sendData(MetaIndex.LLAMA_STRENGTH);
}
public int getStrength() {
return getData(MetaIndex.LLAMA_STRENGTH);
}
}
|
package uk.nhs.hee.web.platform.services.channel;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.jcr.Session;
import javax.jcr.security.Privilege;
import org.hippoecm.hst.container.RequestContextProvider;
import org.onehippo.cms7.services.hst.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Restricts/hides the channel if the user doesn't have one of
* <code>hippo:author, hippo:editor and hippo:admin</code> privileges.
* This essentially means that the user has got readonly access
* to the channel content folder (probably to use the corresponding
* channel content) and the channel should be hidden from the user.
* <p>
* For instance, if a user has readonly (<code>jcr:read</code>) privilege to
* global channel content, then global channel should be hidden from the user.
*/
public class GlobalChannelAccessFilter implements BiPredicate<Session, Channel> {
public static final List<String> AUTHOR_AND_EDITOR_PRIVILEGES =
Arrays.asList("hippo:author", "hippo:editor", "hippo:admin");
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalChannelAccessFilter.class);
@Override
public boolean test(Session cmsSession, Channel channel) {
try {
if (RequestContextProvider.get() == null) {
// invoked by background thread, no filtering
return true;
}
LOGGER.info("Channel name => '{}' and it's content root => '{}'", channel.getName(), channel.getContentRoot());
Privilege[] privileges = cmsSession.getAccessControlManager().getPrivileges(channel.getContentRoot());
LOGGER.info("User has got {} privileges on the content folder '{}'",
Stream.of(privileges).map(Privilege::getName).collect(Collectors.toList()),
channel.getContentRoot());
return Stream.of(privileges)
.map(Privilege::getName)
.anyMatch(AUTHOR_AND_EDITOR_PRIVILEGES::contains);
} catch (Exception e) {
LOGGER.warn(
"Caught error '{}' while checking the current user privilege for the channel '{}'",
e.getMessage(),
channel.getName(),
e);
return false;
}
}
}
|
package com.fszuberski.tweets.authorizer.core.domain;
import lombok.*;
@Setter
@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class TokenAuthorizerContext {
private String type;
private String authorizationToken;
private String methodArn;
}
|
package sr.hakrinbank.intranet.api.mapping;
import org.modelmapper.PropertyMap;
import sr.hakrinbank.intranet.api.dto.RelationshipCrossSellOfficerDto;
import sr.hakrinbank.intranet.api.model.RelationshipCrossSellOfficer;
/**
* Created by clint on 6/6/17.
*/
public class RelationshipCrossSellOfficerToDtoMap extends PropertyMap<RelationshipCrossSellOfficer, RelationshipCrossSellOfficerDto> {
@Override
protected void configure() {
map().setBusinessAccountType(source.getBusinessAccountType().getId());
map().setCrossSellOfficer(source.getCrossSellOfficer().getId());
map().setRelationshipManager(source.getRelationshipManager().getId());
}
}
|
package com.daexsys.automata.world.tiletypes.pulsers;
import com.daexsys.automata.Tile;
import com.daexsys.automata.world.TileCoord;
import com.daexsys.automata.world.WorldLayer;
import com.daexsys.automata.world.tiletypes.TilePulser;
import com.daexsys.automata.world.tiletypes.TileType;
public class WaterTilePulser implements TilePulser {
@Override
public void pulse(Tile tile) {
// if(tile.getType() == TileType.WATER && tile.getEnergy() > 0) {
//
// int offsetX = tile.getWorld().getRandom().nextInt(3) - 1;
// int offsetY = tile.getWorld().getRandom().nextInt(3) - 1;
//
// try {//
// if (tile.getWorld().getTileAt(
// WorldLayer.ABOVE_GROUND,
// tile.getCoordinate().x + offsetX,
// tile.getCoordinate().y + offsetY)
// .getType() == TileType.AIR
// && tile.getEnergy() > 0
// ) {
//
// TileCoord newCoordinate = tile.getCoordinate().add(offsetX, offsetY);
//
// // Create a new water and split the energy of this one amongst the two.
// tile.getWorld().queueChangeAt(
// newCoordinate,
// TileType.WATER,
// tile.getEnergy()
// );
//
// tile.setEnergy(tile.getEnergy() / 2);
// }
// } catch (Exception ignore) {}
// }
}
}
|
public class WildcardMatching1 {
public boolean isMatch(String s, String p) {
int sl = s.length() , pl = p.length() , i=0 , j=0;
int start = -1 , s_start = 0;
while(i < sl){
if(i<sl && j <pl && ( s.charAt(i)==p.charAt(j) || p.charAt(j) == '?' )){
i++;j++;
}else if(p.charAt(j) == '*'){
start = j;
s_start = i;
j++;
}else if(start != -1){
j = start + 1;
s_start++;
i = s_start;
}else{
return false;
}
}
while(j<pl && p.charAt(j) == '*'){
j++;
}
return j == pl;
}
}
|
package com.wq.user.dao;
import java.util.List;
import java.util.Map;
public interface WqUserDao
{
List<Map<String, Object>> queryOne(Map<String, Object> param);
List<Map<String, Object>> getUserList(Map<String, Object> param);
}
|
package com.lojaDeComputadorV3.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name = "tbl_endereco")
@NamedQueries({ @NamedQuery(name = "Endereco.listar", query = "SELECT endereco FROM Endereco endereco"),
@NamedQuery(name = "Endereco.buscarPorCodigo", query = "SELECT endereco FROM Endereco endereco WHERE endereco.codigo = :codigo ") })
public class Endereco extends EntidadeDominio {
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo tipo de residencia é obrigatório")
// coluna no banco de dados
@Column(name = "end_tiporesidencia", length = 50, nullable = false)
private String tiporesidencia;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo tipo de logradouro é obrigatório")
// coluna no banco de dados
@Column(name = "end_tipologradouro", length = 50, nullable = false)
private String tipologradouro;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo logradouro é obrigatório")
// coluna no banco de dados
@Column(name = "end_logradouro", length = 50, nullable = false)
private String logradouro;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo numero é obrigatório")
// coluna no banco de dados
@Column(name = "end_numero", length = 50, nullable = false)
private String numero;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo bairro é obrigatório")
// coluna no banco de dados
@Column(name = "end_bairro", length = 50, nullable = false)
private String bairro;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo cep é obrigatório")
// coluna no banco de dados
@Column(name = "end_cep", length = 50, nullable = false)
private String cep;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo cidade é obrigatório")
// coluna no banco de dados
@Column(name = "end_cidade", length = 50, nullable = false)
private String cidade;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo estado é obrigatório")
// coluna no banco de dados
@Column(name = "end_estado", length = 50, nullable = false)
private String estado;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo pais é obrigatório")
// coluna no banco de dados
@Column(name = "end_pais", length = 50, nullable = false)
private String pais;
// Validação, campo não pode estar vazio
@NotEmpty(message = "O campo complemento é obrigatório")
// coluna no banco de dados
@Column(name = "end_complemento", length = 50, nullable = false)
private String complemento;
@NotNull(message = "O campo cliente é obrigatório!")
// Tipo de relacionamento entre tabelas do banco que contem chave estrangeira
@ManyToOne(fetch = FetchType.EAGER)
// juntando as colunas||nome na tabela filha - produto|||nome na tabela pai -
// produto
@JoinColumn(name = "tbl_cliente_id_codigo", referencedColumnName = "id_codigo")
private Cliente cliente;
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getTiporesidencia() {
return tiporesidencia;
}
public void setTiporesidencia(String tiporesidencia) {
this.tiporesidencia = tiporesidencia;
}
public String getTipologradouro() {
return tipologradouro;
}
public void setTipologradouro(String tipologradouro) {
this.tipologradouro = tipologradouro;
}
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public String getComplemento() {
return complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((bairro == null) ? 0 : bairro.hashCode());
result = prime * result + ((cep == null) ? 0 : cep.hashCode());
result = prime * result + ((cidade == null) ? 0 : cidade.hashCode());
result = prime * result + ((cliente == null) ? 0 : cliente.hashCode());
result = prime * result + ((complemento == null) ? 0 : complemento.hashCode());
result = prime * result + ((estado == null) ? 0 : estado.hashCode());
result = prime * result + ((logradouro == null) ? 0 : logradouro.hashCode());
result = prime * result + ((numero == null) ? 0 : numero.hashCode());
result = prime * result + ((pais == null) ? 0 : pais.hashCode());
result = prime * result + ((tipologradouro == null) ? 0 : tipologradouro.hashCode());
result = prime * result + ((tiporesidencia == null) ? 0 : tiporesidencia.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Endereco other = (Endereco) obj;
if (bairro == null) {
if (other.bairro != null)
return false;
} else if (!bairro.equals(other.bairro))
return false;
if (cep == null) {
if (other.cep != null)
return false;
} else if (!cep.equals(other.cep))
return false;
if (cidade == null) {
if (other.cidade != null)
return false;
} else if (!cidade.equals(other.cidade))
return false;
if (cliente == null) {
if (other.cliente != null)
return false;
} else if (!cliente.equals(other.cliente))
return false;
if (complemento == null) {
if (other.complemento != null)
return false;
} else if (!complemento.equals(other.complemento))
return false;
if (estado == null) {
if (other.estado != null)
return false;
} else if (!estado.equals(other.estado))
return false;
if (logradouro == null) {
if (other.logradouro != null)
return false;
} else if (!logradouro.equals(other.logradouro))
return false;
if (numero == null) {
if (other.numero != null)
return false;
} else if (!numero.equals(other.numero))
return false;
if (pais == null) {
if (other.pais != null)
return false;
} else if (!pais.equals(other.pais))
return false;
if (tipologradouro == null) {
if (other.tipologradouro != null)
return false;
} else if (!tipologradouro.equals(other.tipologradouro))
return false;
if (tiporesidencia == null) {
if (other.tiporesidencia != null)
return false;
} else if (!tiporesidencia.equals(other.tiporesidencia))
return false;
return true;
}
@Override
public String toString() {
return "Endereco [tiporesidencia=" + tiporesidencia + ", tipologradouro=" + tipologradouro + ", logradouro="
+ logradouro + ", numero=" + numero + ", bairro=" + bairro + ", cep=" + cep + ", cidade=" + cidade
+ ", estado=" + estado + ", pais=" + pais + ", complemento=" + complemento + ", cliente=" + cliente
+ ", getCodigo()=" + getCodigo() + "]";
}
}
|
package Dao.dao;
import Dao.model.SaleGoodsClickNumber;
import java.util.List;
public interface SaleGoodsClickNumberMapper {
void deleteByPrimaryKey(Integer sgclicknumberid);
void insert(SaleGoodsClickNumber record);
void insertSelective(SaleGoodsClickNumber record);
SaleGoodsClickNumber selectByPrimaryKey(Integer sgclicknumberid);
void updateByPrimaryKeySelective(SaleGoodsClickNumber record);
void updateByPrimaryKey(SaleGoodsClickNumber record);
SaleGoodsClickNumber selectBySaleGoodsId(int saleGoodsId);
List<SaleGoodsClickNumber> selectAll();
} |
package com.classichu.titlebar.helper;
import android.support.v7.widget.PopupMenu;
import android.view.View;
/**
* Created by louisgeek on 2017/2/28.
*/
public class ClassicTitleBarMenuHelper {
private static PopupMenu mPopupMenu;
public static void initMenu(View anchorView, int menuResId) {
//
mPopupMenu = new PopupMenu(anchorView.getContext(), anchorView);
mPopupMenu.getMenuInflater().inflate(menuResId, mPopupMenu.getMenu());
mPopupMenu.show();
}
public static void setOnMenuItemClickListener(OnClassicTitleBarMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
public interface OnClassicTitleBarMenuItemClickListener extends PopupMenu.OnMenuItemClickListener{
}
}
|
package com.lenovohit.hcp.base.manager.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.lenovohit.hcp.appointment.model.RegInfo;
import com.lenovohit.hcp.base.model.HcpUser;
import com.lenovohit.hcp.finance.model.InvoiceInfo;
import com.lenovohit.hcp.finance.model.InvoiceManage;
import com.lenovohit.hcp.finance.model.OutpatientChargeDetail;
@Service("hisRegistBizChargeManager")
public class HisRegistBizChargeManagerImpl extends AbstractHisBizChargeManagerImpl {
@Override
protected String getInvoiceSource() {
return InvoiceInfo.INVOICE_SOURCE_REGIST;
}
@Override
protected String getInvoiceType() {
return InvoiceManage.INVOICE_TYPE_REGIST;
}
@Override
protected List<OutpatientChargeDetail> getChargeDetailInfo(List<String> chargeDetailIds) {
List<OutpatientChargeDetail> details = new ArrayList<>();
for (String s : chargeDetailIds) {
OutpatientChargeDetail detail = outpatientChargeDetailManager.get(s);
if (detail != null)
details.add(detail);
}
return details;
}
@Override
protected void updatePaySuccessOtherInfo(HcpUser operator, BigDecimal amt, String orderId, String invoiceNo,
RegInfo regInfo, List<OutpatientChargeDetail> details) {
regInfo.setInvoiceNo(invoiceNo);
regInfoManager.save(regInfo);
}
@Override
protected void doBizAfterPayFailed(String operator, BigDecimal amt, String orderId, List<String> chargeDetailIds) {
// 挂号付费失败,将此笔挂号记录,收费明细记录删除
String regId = outpatientChargeDetailManager.get(chargeDetailIds.get(0)).getRegId();
RegInfo regInfo = regInfoManager.get(regId);
if (regInfo != null) {
regInfoManager.delete(regInfo);
}
for (String s : chargeDetailIds)
outpatientChargeDetailManager.delete(s);
}
@Override
protected void refundUpdateOtherInfos(InvoiceInfo info) {
String hql = "from RegInfo where hosId = ? and invoiceNo = ? ";
RegInfo regInfo = regInfoManager.findOne(hql, info.getHosId(), info.getInvoiceNo());
regInfo.setCancelFlag(CANCLELED);
regInfo.setRegState(RegInfo.REG_CANCELED);
regInfo.setCancelOper(info.getCancelOper());
regInfo.setCancelTime(info.getCancelTime());
regInfoManager.save(regInfo);
}
}
|
package com.needii.dashboard.dao;
import com.needii.dashboard.model.ShippersLikeCount;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
/**
* @author modani
*
*/
@Repository("shippersLikeCountDao")
public class ShippersLikeCountDaoImpl extends AbstractDao<Integer, ShippersLikeCount> implements ShippersLikeCountDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<ShippersLikeCount> findAll() {
Criteria criteria = sessionFactory.getCurrentSession()
.createCriteria(ShippersLikeCount.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return criteria.list();
}
@Override
public List<ShippersLikeCount> findAllShippersId(Long shippersId){
Criteria criteria = sessionFactory.getCurrentSession()
.createCriteria(ShippersLikeCount.class)
.add(Restrictions.eq("shippersId", shippersId));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return criteria.list();
}
@Override
public List<ShippersLikeCount> findAllFromTo(Date from, Date to) {
Criteria criteria = sessionFactory.getCurrentSession()
.createCriteria(ShippersLikeCount.class);
if(from != null) criteria.add(Restrictions.ge("createdAt", from));
if(to != null) criteria.add(Restrictions.le("createdAt", to));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return criteria.list();
}
@Override
public ShippersLikeCount findOne(long id) {
return (ShippersLikeCount)sessionFactory.getCurrentSession()
.createCriteria(ShippersLikeCount.class)
.add(Restrictions.eq("id", id))
.uniqueResult();
}
@Override
public ShippersLikeCount findOneOrderCode(String orderCode) {
return (ShippersLikeCount)sessionFactory.getCurrentSession()
.createCriteria(ShippersLikeCount.class)
.add(Restrictions.eq("orderCode", orderCode))
.uniqueResult();
}
@Override
public void create(ShippersLikeCount entity) {
Session session = sessionFactory.getCurrentSession();
session.persist(entity);
}
@Override
public void update(ShippersLikeCount entity) {
Session session = sessionFactory.getCurrentSession();
session.update(entity);
}
@Override
public void delete(ShippersLikeCount entity) {
Session session = sessionFactory.getCurrentSession();
session.delete(entity);
}
}
|
package com.mykarsol.appconnectivity;
/*
* 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.
*/
import DataObjects.Candidate_Profile_Object;
import DataObjects.Placement_Details_Object;
import DataOperations.Candidate_Profile_Operation;
import DataOperations.Placement_Details_Operation;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Shivam Patel
*/
public class Placement_Server extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String batchyear,candidate_id,designation,salarydetails,workprofile,doj;
int companyid;
String message="";
PrintWriter out = response.getWriter();
batchyear=request.getParameter("batchyear");
candidate_id = request.getParameter("candidate_id");
companyid = Integer.parseInt(request.getParameter("companyname"));
designation = request.getParameter("designation");
salarydetails = request.getParameter("salarydetails");
workprofile = request.getParameter("workprofile");
doj = request.getParameter("doj");
Placement_Details_Object pdo=new Placement_Details_Object();
pdo.setCandidate_ID(candidate_id);
pdo.setCid(companyid);
pdo.setDesignation(designation);
pdo.setSalarydetails(salarydetails);
pdo.setWorkprofile(workprofile);
pdo.setDoj(doj);
//out.println("<h1>" + message + "</h1>");
Placement_Details_Operation pdop= new Placement_Details_Operation();
message = pdop.InsertPlacementetails(pdo);
out.println(message);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.xianzaishi.wms.tmscore.manage.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.xianzaishi.wms.tmscore.vo.DistributionBoxStatuVO;
import com.xianzaishi.wms.tmscore.vo.DistributionBoxStatuDO;
import com.xianzaishi.wms.tmscore.vo.DistributionBoxStatuQueryVO;
import com.xianzaishi.wms.common.exception.BizException;
import com.xianzaishi.wms.tmscore.manage.itf.IDistributionBoxStatuManage;
import com.xianzaishi.wms.tmscore.dao.itf.IDistributionBoxStatuDao;
public class DistributionBoxStatuManageImpl implements
IDistributionBoxStatuManage {
@Autowired
private IDistributionBoxStatuDao distributionBoxStatuDao = null;
private void validate(DistributionBoxStatuVO distributionBoxStatuVO) {
if (distributionBoxStatuVO.getBoxId() == null
|| distributionBoxStatuVO.getBoxId() <= 0) {
throw new BizException("boxID error:"
+ distributionBoxStatuVO.getBoxId());
}
}
private void validate(Long id) {
if (id == null || id <= 0) {
throw new BizException("ID error:" + id);
}
}
public IDistributionBoxStatuDao getDistributionBoxStatuDao() {
return distributionBoxStatuDao;
}
public void setDistributionBoxStatuDao(
IDistributionBoxStatuDao distributionBoxStatuDao) {
this.distributionBoxStatuDao = distributionBoxStatuDao;
}
public Boolean addDistributionBoxStatuVO(
DistributionBoxStatuVO distributionBoxStatuVO) {
validate(distributionBoxStatuVO);
distributionBoxStatuDao.addDO(distributionBoxStatuVO);
return true;
}
public List<DistributionBoxStatuVO> queryDistributionBoxStatuVOList(
DistributionBoxStatuQueryVO distributionBoxStatuQueryVO) {
return distributionBoxStatuDao.queryDO(distributionBoxStatuQueryVO);
}
public DistributionBoxStatuVO getDistributionBoxStatuVOByID(Long id) {
return (DistributionBoxStatuVO) distributionBoxStatuDao.getDOByID(id);
}
public Boolean modifyDistributionBoxStatuVO(
DistributionBoxStatuVO distributionBoxStatuVO) {
return distributionBoxStatuDao.updateDO(distributionBoxStatuVO);
}
public Boolean deleteDistributionBoxStatuVOByID(Long id) {
return distributionBoxStatuDao.delDO(id);
}
public void assign(Long deliverID, Long boxID) {
distributionBoxStatuDao.assign(deliverID, boxID);
}
public void release(DistributionBoxStatuVO distributionBoxStatuVO) {
distributionBoxStatuDao.release(distributionBoxStatuVO);
}
}
|
package xyz.javista.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import xyz.javista.config.AuditorAwareImpl;
import xyz.javista.core.domain.Order;
import xyz.javista.core.domain.OrderLineNumber;
import xyz.javista.core.domain.User;
import xyz.javista.core.repository.OrderLineNumberRepository;
import xyz.javista.core.repository.OrderRepository;
import xyz.javista.core.repository.UserRepository;
import xyz.javista.exception.DateTimeConverterException;
import xyz.javista.exception.OrderLineItemException;
import xyz.javista.mapper.OrderLineNumberMapper;
import xyz.javista.mapper.OrderMapper;
import xyz.javista.web.command.CreateOrderLineItemCommand;
import xyz.javista.web.command.UpdateOrderLineItemCommand;
import xyz.javista.web.dto.OrderDTO;
import xyz.javista.web.dto.OrderLineNumberDTO;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.UUID;
@Service
@Transactional
public class OrderLineItemService {
private static final String ORDER_NOT_EXISTS_MESSAGE = "Order not exists!";
private static final String ORDER_EXPIRED_MESSAGE = "Order expired!";
private static final String ORDER_ITEM_NOT_EXISTS_MESSAGE = "Order item not exists!";
private static final String OPERATION_NOT_ALLOWED_MESSAGE = "Operation not allowed!";
@Autowired
OrderRepository orderRepository;
@Autowired
OrderLineNumberMapper orderLineNumberMapper;
@Autowired
private UserRepository userRepository;
@Autowired
private OrderLineNumberRepository orderLineNumberRepository;
@Autowired
private OrderMapper orderMapper;
@Autowired
AuditorAwareImpl auditorAware;
public OrderDTO createOrderLineItem(CreateOrderLineItemCommand createOrderLineItemCommand, String orderId) throws OrderLineItemException, DateTimeConverterException {
UUID parentOrderId;
try {
parentOrderId = UUID.fromString(orderId);
} catch (IllegalArgumentException ex) {
throw new OrderLineItemException(OrderLineItemException.FailReason.ORDER_NOT_EXIST, ORDER_NOT_EXISTS_MESSAGE);
}
Order order = orderRepository.findOne(parentOrderId);
if (order == null) {
throw new OrderLineItemException(OrderLineItemException.FailReason.ORDER_NOT_EXIST, ORDER_NOT_EXISTS_MESSAGE);
}
User user = auditorAware.getCurrentAuditor();
if (!order.getCreatedBy().getLogin().equals(user.getLogin()) && order.getEndDatetime().isBefore(LocalDateTime.now())) {
throw new OrderLineItemException(OrderLineItemException.FailReason.ORDER_EXPIRED, ORDER_EXPIRED_MESSAGE);
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UUID userId = ((User) authentication.getPrincipal()).getId();
User purchaser = userRepository.findOne(userId);
OrderLineNumber orderLineNumber = orderLineNumberMapper.toEntity(createOrderLineItemCommand);
orderLineNumber.setOrder(order);
orderLineNumber.setPurchaser(purchaser);
orderLineNumberRepository.saveAndFlush(orderLineNumber);
return orderMapper.toDto(orderRepository.findOne(parentOrderId));
}
public void removeOrderItem(String orderId, String orderItemId) throws OrderLineItemException {
OrderLineNumber orderItem = orderLineNumberRepository.findOne(UUID.fromString(orderItemId));
canUpdateOrDelete(orderItem);
if (orderItem.getOrder().getId().equals(UUID.fromString(orderId))) {
orderLineNumberRepository.delete(orderItem);
} else {
throw new OrderLineItemException(OrderLineItemException.FailReason.ORDER_NOT_EXIST, ORDER_NOT_EXISTS_MESSAGE);
}
}
public OrderLineNumberDTO updateOrderItem(UpdateOrderLineItemCommand updateOrderLineItemCommand) throws OrderLineItemException, DateTimeConverterException {
OrderLineNumber orderLineNumber = orderLineNumberRepository.findOne(updateOrderLineItemCommand.getOrderLineItemId());
if (orderLineNumber == null) {
throw new OrderLineItemException(OrderLineItemException.FailReason.ORDER_ITEM_NOT_EXIST, ORDER_ITEM_NOT_EXISTS_MESSAGE);
}
canUpdateOrDelete(orderLineNumber);
if (updateOrderLineItemCommand.getDishName().isPresent()) {
orderLineNumber.setDishName(updateOrderLineItemCommand.getDishName().get());
}
if (updateOrderLineItemCommand.getPrice().isPresent()) {
orderLineNumber.setPrice(updateOrderLineItemCommand.getPrice().get());
}
if (updateOrderLineItemCommand.getPaid().isPresent()) {
orderLineNumber.setPaid(updateOrderLineItemCommand.getPaid().get());
}
return orderLineNumberMapper.toDTO(orderLineNumberRepository.saveAndFlush(orderLineNumber));
}
private void canUpdateOrDelete(OrderLineNumber orderLineNumber) throws OrderLineItemException {
User user = auditorAware.getCurrentAuditor();
if (!orderLineNumber.getOrder().getCreatedBy().getLogin().equals(user.getLogin()) && orderLineNumber.getOrder().getEndDatetime().isBefore(LocalDateTime.now())) {
throw new OrderLineItemException(OrderLineItemException.FailReason.ORDER_EXPIRED, ORDER_EXPIRED_MESSAGE);
}
if (!orderLineNumber.getOrder().getCreatedBy().getLogin().equals(user.getLogin()) && !orderLineNumber.getPurchaser().getLogin().equals(user.getLogin())) {
throw new OrderLineItemException(OrderLineItemException.FailReason.NOT_ALLOWED, OPERATION_NOT_ALLOWED_MESSAGE);
}
}
}
|
package com.navegg.challenge.CRUDApi.config;
import com.navegg.challenge.CRUDApi.model.Category;
import com.navegg.challenge.CRUDApi.model.Item;
import com.navegg.challenge.CRUDApi.model.Url;
import com.navegg.challenge.CRUDApi.repository.ItemRepository;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class MyConfiguration {
@Autowired
private ItemRepository itemRepository;
@PostConstruct
public void populateDB() throws IOException {
String urlString = "https://raw.githubusercontent.com/Navegg/navegg-backend-challenge/master/sites.csv";
// create the url
URL url = new URL(urlString);
// open the url stream, wrap it an a few "readers"
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
String[] row;
while ((row = csvReader.readNext()) != null) {
Set<Url> urls = new HashSet<>();
Set<Category> categories = new HashSet<>();
for(String ur : row[1].split(";")){
urls.add(new Url(ur));
}
for(String category : row[2].split(";")){
categories.add(new Category(category));
}
Item item = new Item(row[0], urls, categories, row[3]);
item.getUrlList().forEach(url1 -> url1.setItem(item));
item.getCategoryList().forEach(category1 -> category1.setItem(item));
itemRepository.save(item);
}
reader.close();
}
}
|
package com.revolut.moneytransfer.repository;
import com.google.inject.Inject;
import com.revolut.moneytransfer.config.WebConfig;
import com.revolut.moneytransfer.enums.TransactionStatus;
import com.revolut.moneytransfer.exceptions.InsufficientBalanceException;
import com.revolut.moneytransfer.model.CreditTransactionRequest;
import com.revolut.moneytransfer.model.LedgerEntry;
import com.revolut.moneytransfer.model.MoneyTransferRequest;
import com.revolut.moneytransfer.model.TransactionEntry;
import com.revolut.moneytransfer.persistence.jooq.Tables;
import com.revolut.moneytransfer.persistence.jooq.tables.records.AccountRecord;
import com.revolut.moneytransfer.persistence.jooq.tables.records.LedgerRecord;
import com.revolut.moneytransfer.persistence.jooq.tables.records.TransactionRecord;
import org.jooq.DSLContext;
import org.jooq.exception.DataAccessException;
import org.jooq.impl.DSL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
public class TransactionRepository {
private final DSLContext jooq;
private static final Logger logger = LoggerFactory.getLogger(TransactionRepository.class);
@Inject
public TransactionRepository(final DSLContext jooq) {
this.jooq = jooq;
}
private static void addTransactionEntry(DSLContext ctx, TransactionEntry transactionEntry) {
logger.info(String.format("Adding transaction with uuid : %s", transactionEntry.getUuid()));
ctx.insertInto(Tables.TRANSACTION)
.set(Tables.TRANSACTION.UUID, transactionEntry.getUuid())
.set(Tables.TRANSACTION.FROM_ACCOUNT_ID, transactionEntry.getFrom())
.set(Tables.TRANSACTION.TO_ACCOUNT_ID, transactionEntry.getTo())
.set(Tables.TRANSACTION.AMOUNT, transactionEntry.getAmount())
.set(Tables.TRANSACTION.STATUS, transactionEntry.getStatus())
.set(Tables.TRANSACTION.TYPE, transactionEntry.getType())
.execute();
}
private static void updateTransactionStatus(DSLContext ctx, UUID uuid, TransactionStatus status) {
ctx.update(Tables.TRANSACTION)
.set(Tables.TRANSACTION.STATUS, status)
.where(Tables.TRANSACTION.UUID.eq(uuid))
.execute();
}
private static void addLedgerEntry(DSLContext ctx, LedgerEntry ledgerEntry) {
logger.info(String.format("Adding Ledger entry with uuid : %s", ledgerEntry.getUuid()));
ctx.insertInto(Tables.LEDGER)
.set(Tables.LEDGER.UUID, ledgerEntry.getUuid())
.set(Tables.LEDGER.ACCOUNT_ID, ledgerEntry.getAccountId())
.set(Tables.LEDGER.AMOUNT, ledgerEntry.getAmount())
.set(Tables.LEDGER.TRANSACTION_ID, ledgerEntry.getTransactionId())
.execute();
}
public TransactionRecord[] getTransactionRecordByFromAccountId(final UUID uuid) {
return jooq.selectFrom(Tables.TRANSACTION)
.where(Tables.TRANSACTION.FROM_ACCOUNT_ID.eq(uuid))
.fetchArray();
}
public TransactionRecord[] getTransactionRecordByToAccountId(final UUID uuid) {
return jooq.selectFrom(Tables.TRANSACTION)
.where(Tables.TRANSACTION.TO_ACCOUNT_ID.eq(uuid))
.fetchArray();
}
public LedgerRecord[] getLedgerRecordByAccountId(final UUID uuid) {
return jooq.selectFrom(Tables.LEDGER)
.where(Tables.LEDGER.ACCOUNT_ID.eq(uuid))
.fetchArray();
}
public void transferMoney(MoneyTransferRequest moneyTransferRequest, UUID fromUuid) {
/* This method first creates objects of TransactionEntry and LedgerEntry classes, I am doing that outside of
* transaction. Inside the transaction I take a lock on the source account and validate that balance > amount. If
* not I mark the transaction FAILED otherwise I take the lock on the destination account as well, update the
* balance of both and create the ledger statements. Ledger statements are important in case we have to reconcile.
* For one transfer transaction I am creating two Ledger entries, one for source account with -amount and other
* for destination account with +amount.
*
* The sum of all ledger entries for a particular account should be the balance for that account.
* */
TransactionEntry transactionEntry = TransactionEntry.getTransferTransactionEntry(
fromUuid, moneyTransferRequest.getTo(), moneyTransferRequest.getAmount());
LedgerEntry creditLedgerEntry = LedgerEntry.getCreditLedgerEntry(fromUuid, moneyTransferRequest.getTo(),
moneyTransferRequest.getAmount(), transactionEntry.getUuid());
LedgerEntry debitLedgerEntry = LedgerEntry.getDebitLedgerEntry(fromUuid, moneyTransferRequest.getTo(),
moneyTransferRequest.getAmount(), transactionEntry.getUuid());
addTransactionEntry(jooq, transactionEntry);
try {
jooq.transaction(c -> {
DSLContext dslContext = DSL.using(c);
AccountRecord fromAccountRecord = AccountRepository.lockAccount(dslContext, fromUuid);
if (fromAccountRecord.getBalance() < moneyTransferRequest.getAmount()) {
throw new InsufficientBalanceException();
} else {
AccountRecord toAccountRecord = AccountRepository.lockAccount(dslContext, moneyTransferRequest.getTo());
addLedgerEntry(dslContext, creditLedgerEntry);
addLedgerEntry(dslContext, debitLedgerEntry);
updateTransactionStatus(dslContext, transactionEntry.getUuid(), TransactionStatus.COMPLETED);
fromAccountRecord.setBalance(fromAccountRecord.getBalance() - moneyTransferRequest.getAmount());
fromAccountRecord.store();
toAccountRecord.setBalance(toAccountRecord.getBalance() + moneyTransferRequest.getAmount());
toAccountRecord.store();
}
});
} catch(Exception exception) {
updateTransactionStatus(jooq, transactionEntry.getUuid(), TransactionStatus.FAILED);
throw exception;
}
}
public void addCreditToAccount(CreditTransactionRequest creditTransactionRequest, UUID toUuid) {
/*CREDIT transaction is a special case of money transfer where we don't have any source account,
* hence I am creating only one ledger entry for destination account.
* */
TransactionEntry transactionEntry = TransactionEntry.getCreditTransactionEntry(
toUuid, creditTransactionRequest.getAmount());
LedgerEntry creditLedgerEntry = LedgerEntry.getCreditLedgerEntry(null, toUuid,
creditTransactionRequest.getAmount(), transactionEntry.getUuid());
addTransactionEntry(jooq, transactionEntry);
try {
jooq.transaction(c -> {
DSLContext dslContext = DSL.using(c);
AccountRecord accountRecord = AccountRepository.lockAccount(dslContext, toUuid);
addLedgerEntry(dslContext, creditLedgerEntry);
updateTransactionStatus(dslContext, transactionEntry.getUuid(), TransactionStatus.COMPLETED);
accountRecord.setBalance(accountRecord.getBalance() + creditTransactionRequest.getAmount());
accountRecord.store();
});
} catch(Exception exception) {
updateTransactionStatus(jooq, transactionEntry.getUuid(), TransactionStatus.FAILED);
throw exception;
}
}
}
|
package org.test.ht;
public class RegularExp {
public boolean isMatch(String s, String p) {
if (p.length() == 0) {
return s.length() == 0;
}
if (p.charAt(p.length() - 1) == '.') {
if (s.length() >= 1 && p.length() >= 1) {
return this.isMatch(s.substring(0,s.length() - 1), p.substring(0, p.length() - 1));
}
else {
return false;
}
}
else if(p.charAt(p.length() - 1) == '*') {
char last = p.charAt(p.length() - 2);
boolean match = this.isMatch(s, p.substring(0, p.length() - 2));
int offset = 0;
while (!match && s.length() - offset >= 1 && charMatch(s.charAt(s.length() - offset - 1), last)) {
match = this.isMatch(s.substring(0, s.length() - offset - 1), p.substring(0, p.length() - 2));
offset++;
}
return match;
}
else {
if (s.length() >= 1 && p.length() >= 1) {
return this.isMatch(s.substring(0,s.length() - 1), p.substring(0, p.length() - 1)) &&
s.charAt(s.length() - 1) == p.charAt(p.length() - 1);
}
else {
return false;
}
}
}
private static boolean charMatch(char c, char toMatch) {
return toMatch == '.' ? true : toMatch == c;
}
public static void main(String args[]) {
String s = "mississippi";
String p = ".*.*";
RegularExp r = new RegularExp();
System.out.println(r.isMatch(s, p));
}
}
|
package com.egova.baselibrary.util;
import android.view.Gravity;
import android.widget.Toast;
import com.egova.baselibrary.application.EgovaApplication;
import es.dmoral.toasty.Toasty;
public class ToastUtil {
public static void showNormal(String message) {
Toast toast = Toasty.info(EgovaApplication.getContext(), message);
// toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public static void showWaring(String message){
Toast toast = Toasty.warning(EgovaApplication.getContext(), message);
// toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public static void showSuccess(String message) {
Toast toast = Toasty.success(EgovaApplication.getContext(), message);
// toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public static void showError(String message){
Toast toast = Toasty.error(EgovaApplication.getContext(), message);
// toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
|
package DataStructures.linkedlists;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
/**
* Created by sydgsk9 on 5/15/2017.
*/
public class MergeKListPQ {
public ListNode mergeKListsUsingPQ(List<ListNode> lists) {
ListNode prev = new ListNode(-1);
ListNode head = prev;
PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return Integer.compare(o1.val, o2.val);
}
});
for (int i = 0; i < lists.size(); i++) {
ListNode temp = lists.get(i);
pq.add(temp);
}
while (!pq.isEmpty()) {
ListNode node = pq.poll();
prev.next = node;
prev = prev.next;
if (node.next != null) {
pq.add(node.next);
}
}
return head.next;
}
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> pq = new PriorityQueue<>(new Comparator<ListNode>() {
public int compare(ListNode l1, ListNode l2) {
return Integer.compare(l1.val, l2.val);
}
});
for (ListNode node : lists) {
pq.add(node);
}
ListNode prev = new ListNode(-1);
ListNode result = prev;
while (!pq.isEmpty()) {
ListNode temp = pq.poll();
prev.next = temp;
prev = prev.next;
if (temp.next != null) {
pq.add(temp.next);
}
}
return result.next;
}
public static void main(String a[]) {
LinkedList ll = new LinkedList();
MergeKListPQ ml = new MergeKListPQ();
ListNode l1 = ll.buildLinkedList(new int[]{1, 2, 13, 20}, new ListNode());
ListNode l2 = ll.buildLinkedList(new int[]{3, 4, 35, 41}, new ListNode());
ListNode l3 = ll.buildLinkedList(new int[]{5, 9, 11, 25}, new ListNode());
ListNode l4 = ll.buildLinkedList(new int[]{1, 21, 39, 40}, new ListNode());
/*List<ListNode> list = new ArrayList<>();
list.add(l1);
list.add(l2);
list.add(l3);
list.add(l4);
ListNode result = ml.mergeKListsUsingPQ(list);*/
ListNode result = ml.mergeKLists(new ListNode[]{l1, l2, l3, l4});
System.out.println(result);
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.theplugin.idea.jira.controls;
import com.atlassian.connector.commons.jira.JIRAActionField;
import com.atlassian.connector.commons.jira.JIRAActionFieldBean;
import javax.swing.*;
import java.awt.*;
/**
* @autrhor pmaruszak
* @date Jul 7, 2010
*/
public class FieldNumber extends JTextField implements ActionFieldEditor {
private JIRAActionField field;
public FieldNumber(final String text, final JIRAActionField field) {
super(text);
setCaretPosition(0);
this.field = field;
}
public JIRAActionField getEditedFieldValue() {
JIRAActionField ret = new JIRAActionFieldBean(field);
ret.addValue(getText());
return ret;
}
public Component getComponent() {
return this;
}
public String getFieldName() {
return field.getName();
}
}
|
package com.emed.shopping.service.admin.store.impl;
import com.emed.shopping.base.BaseService;
import com.emed.shopping.base.BaseServiceImpl;
import com.emed.shopping.dao.model.admin.store.ShopStoreGrade;
import org.springframework.stereotype.Service;
/**
* @Author: 叶飞
* @Date: create in 2018/1/26 0026 下午 3:44
* @Project: shopping
* @Description:
*/
@Service
public class ShopStoreGradeServiceImpl extends BaseServiceImpl<ShopStoreGrade> implements BaseService<ShopStoreGrade> {
}
|
package oop;
import java.util.Scanner;
public class swatch extends watch implements gender,qualities{
//public class swatch extends inventory implements gender,qualities{
public void show(){
System.out.println("========================================================");
System.out.println(" Swatch ");
System.out.println("========================================================");
print();
//หลุดเเล้ว กลับไป class menu.show(){} บรรทัด 92
}
public void print(){
do{
System.out.println("What products for gender?");
System.out.println("Enter Number : 1 for Male");
System.out.println("Enter Number : 2 for Female");
System.out.print("Enter Number : >>>>>>>>>> ");
Scanner gender = new Scanner(System.in);
sex = gender.nextInt();
System.out.println();
}while(sex !=1 && sex !=2);
gender();
//หลุดเเล้ว กลับไป show(){}
}
public void gender(){
if(sex == 1){
MaleQualities();
Msum();
//หลุดเเล้ว กลับไป print(){}
}
else {
FemaleQualities();
Fsum();
//หลุดเเล้ว กลับไป print(){}
}
}
public void MaleQualities(){
Scanner model = new Scanner(System.in);
do{
System.out.println("Please select a model Male");
System.out.println("Enter Number : 1 for "+swatch1+" Price: "+MPswatch1+" >>Inventory " + Mswatchinven1 );
System.out.println("Enter Number : 2 for "+swatch2+" Price: "+MPswatch2+" >>Inventory " + Mswatchinven2 );
System.out.print("Enter Number model : >>>>>>>>>> ");
Mswatch = model.nextInt();
System.out.println();
}while(Mswatch != 1 && Mswatch != 2);
int i;
do{
i=0;
System.out.print("How many do you want ? >>>>>>>>> ");
Swatchamount = model.nextInt();
System.out.println("");
if(Mswatch == 1){
if(Mswatchinven1 < Swatchamount ){
System.out.println("****************************");
System.out.println(" The goods was sold-out");
System.out.println("****************************");
System.out.println("");
i++;
}
}
if(Mswatch == 2){
if(Mswatchinven2 < Swatchamount){
System.out.println("****************************");
System.out.println(" The goods was sold-out");
System.out.println("****************************");
System.out.println("");
i++;
}
}
}while(i>0);
//หลุดเเล้วกลับไป gender(){} ทำ Msum
}
public void FemaleQualities(){
Scanner model = new Scanner(System.in);
do{
System.out.println("Please select a model Female");
System.out.println("Enter Number : 1 for "+swatch1+" Price : "+FPswatch1+" >>Inventory : " + Fswatchinven1 );
System.out.println("Enter Number : 2 for "+swatch2+" Price : "+FPswatch2+" >>Inventory : " + Fswatchinven2 );
System.out.print("Enter Number model : >>>>>>>>>> ");
Fswatch = model.nextInt();
System.out.println();
}while(Fswatch != 1 && Fswatch != 2);
int i; //ตัวเเปรวน
do{
i=0;
System.out.print("How many do you want ? >>>>>>>>> ");
Swatchamount = model.nextInt();
System.out.println();
if(Fswatch == 1){
if(Fswatchinven1 < Swatchamount ){ //สินค้าที่มี น้อยกว่าจำนวนที่ลูกค้าสั่งซื้อ?
System.out.println("****************************");
System.out.println(" The goods was sold-out");
System.out.println("****************************");
System.out.println("");
i++;
}
}
if(Fswatch == 2){
if(Fswatchinven2 < Swatchamount){
System.out.println("****************************");
System.out.println(" The goods was sold-out");
System.out.println("****************************");
System.out.println("");
i++;
}
}
}while(i>0);
//หลุดเเล้วกลับไป gender(){} ทำ Fsum
}
public void Msum(){
System.out.println("=============================== Show Detail ===============================");
if(Mswatch == 1){
sumprice = MPswatch1 * Swatchamount;
System.out.println("Male "+swatch1+" amount : "+Swatchamount+" Price : "+sumprice);
Mswatchinven1 = Mswatchinven1-Swatchamount;
}
else{
sumprice = MPswatch2 * Swatchamount;
System.out.println("Male "+swatch2+" amount : "+Swatchamount+" Price : "+sumprice);
Mswatchinven2 = Mswatchinven2-Swatchamount;
}
System.out.println("===========================================================================");
System.out.println();
//หลุดเเล้วกลับไป gender(){}
}
public void Fsum(){
System.out.println("============================== Show Detail ================================");
if(Fswatch == 1) {
sumprice = FPswatch1* Swatchamount;
System.out.println("Female "+swatch1+" amount : "+Swatchamount+" Price : "+sumprice);
Fswatchinven1 = Fswatchinven1-Swatchamount;
}
else{
sumprice = FPswatch2 * Swatchamount;
System.out.println("Female "+swatch2+" amount : "+Swatchamount+" Price : "+sumprice);
Fswatchinven2 = Fswatchinven2-Swatchamount;
}
System.out.println("===========================================================================");
System.out.println();
//หลุดเเล้วกลับไป gender(){}
}
public int getMswatchinven1() { //เรียก
return Mswatchinven1;
}
public void setMswatchinven1(int Mswatchinven1) { //กำหนด
super.Mswatchinven1 = Mswatchinven1;
}
public int getFswatchinven1() {
return Fswatchinven1;
}
public void setFswatchinven1(int Fswatchinven1) {
super.Fswatchinven1 = Fswatchinven1;
}
public int getMswatchinven2() {
return Mswatchinven2;
}
public void setMswatchinven2(int Mswatchinven2) {
super.Mswatchinven2 = Mswatchinven2;
}
public int getFswatchinven2() {
return Fswatchinven2;
}
public void setFswatchinven2(int Fswatchinven2) {
super.Fswatchinven2 = Fswatchinven2;
}
}
|
package com.example.funcionariocadastro;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Button btnInserir, btnListar, btnExcluir, btnLer, btnLimpar, btnAlterar;
private EditText editId, editNome, editCargo, editSetor, editSalario;
private TextView txtQtd;
private ListView listViewFuncionario;
BancoDeDados bancoDeDados = new BancoDeDados(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(" Diretoria Mulamba ");
this.btnInserir = findViewById(R.id.btnInserir);
this.btnListar = findViewById(R.id.btnListar);
this.btnExcluir = findViewById(R.id.btnExcluir);
this.btnLer = findViewById(R.id.btnLer);
this.btnLimpar = findViewById(R.id.btnLimpar);
this.btnAlterar = findViewById(R.id.btnAlterar);
this.editId = findViewById(R.id.editId);
this.editNome = findViewById(R.id.editNome);
this.editCargo = findViewById(R.id.editCargo);
this.editSetor = findViewById(R.id.editSetor);
this.editSalario = findViewById(R.id.editSalario);
this.listViewFuncionario = findViewById(R.id.listViewFuncionario);
this.txtQtd = findViewById(R.id.txtQtd);
this.btnLimpar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
limpaCampos ( );
}
});
AtualizaQtd ();
}
public void setBtnnInserir(View view) {
if (editId.getText().toString().isEmpty() || editNome.getText().toString().isEmpty()) {
Toast.makeText(this, " Campos ID e nome São Obrigatórios ", Toast.LENGTH_SHORT).show();
} else if ((editCargo.getText().toString().isEmpty() || editSetor.getText().toString().isEmpty() || editSalario.getText().toString().isEmpty())
|| !(editCargo.getText().toString().isEmpty() || editSetor.getText().toString().isEmpty() || editSalario.getText().toString().isEmpty())) {
String resultado;
Funcionario funcionario = new Funcionario();
funcionario.setId(Integer.parseInt(editId.getText().toString()));
funcionario.setNome(editNome.getText().toString());
funcionario.setCargo(editCargo.getText().toString());
funcionario.setSetor(editSetor.getText().toString());
funcionario.setSalario(editSalario.getText().toString());
resultado = bancoDeDados.insereFuncionario(funcionario);
Toast.makeText(this, resultado, Toast.LENGTH_SHORT).show();
AtualizaQtd ();
setBtnListar(view);
}
}
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
public void setBtnListar(View view) {
List<Funcionario> funcionarios = bancoDeDados.listaFuncionario();
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
listViewFuncionario.setAdapter(adapter);
for (Funcionario f : funcionarios) {
arrayList.add(f.getId() + " - " + f.getNome() + " " + f.getCargo() + " " + f.getSetor() + " " + f.getSalario());
adapter.notifyDataSetChanged();
AtualizaQtd ();
}
}
public void setBtnExcluir (View view) {
if (editId.getText().toString().isEmpty()) {
Toast.makeText(this, " Insira o ID a ser Excluido! ", Toast.LENGTH_SHORT).show();
} else {
Funcionario funcionario = new Funcionario();
funcionario.setId(Integer.parseInt(editId.getText().toString()));
bancoDeDados.excluiFuncionario(funcionario);
AtualizaQtd ();
setBtnListar(view);
}
}
public void setBtnLer ( View view ) {
Funcionario funcionario = bancoDeDados.consultaFuncionario (Integer.parseInt(editId.getText().toString()));
if (funcionario != null ) {
editId.setText(String.valueOf(funcionario.getId()));
editNome.setText(funcionario.getNome());
editCargo.setText(funcionario.getCargo());
editSetor.setText(funcionario.getSetor());
editSalario.setText(funcionario.getSalario());
}
}
void limpaCampos ( ) {
editId.setText("");
editNome.setText("");
editCargo.setText("");
editSetor.setText("");
editSalario.setText("");
}
public void setBtnAlterar(View view) {
if (editId.getText().toString().isEmpty() ) {
Toast.makeText(this, " Informe o ID para alterar od dados ", Toast.LENGTH_SHORT).show();
} else if ((editNome.getText().toString().isEmpty() || editCargo.getText().toString().isEmpty() || editSetor.getText().toString().isEmpty() || editSalario.getText().toString().isEmpty())
|| !(editNome.getText().toString().isEmpty() || editCargo.getText().toString().isEmpty() || editSetor.getText().toString().isEmpty() || editSalario.getText().toString().isEmpty())) {
Funcionario funcionario = new Funcionario();
funcionario.setId(Integer.parseInt(editId.getText().toString()));
funcionario.setNome(editNome.getText().toString());
funcionario.setCargo(editCargo.getText().toString());
funcionario.setSetor(editSetor.getText().toString());
funcionario.setSalario(editSalario.getText().toString());
bancoDeDados.alteraFuncionario(funcionario);
}
}
public void AtualizaQtd (){
int qtdFuncionario = bancoDeDados.consultaQtd ();
this.txtQtd.setText(String.valueOf(qtdFuncionario));
}
}
|
package com.metaco.api.contracts;
import com.google.gson.annotations.SerializedName;
public class HistoryCriteria {
@SerializedName("from")
public Integer from;
@SerializedName("to")
private Integer to;
@SerializedName("freq")
private String freq;
@SerializedName("orderAsc")
private Boolean orderAsc;
public HistoryCriteria(Integer from, Integer to, String freq, Boolean orderAsc) {
this.from = from;
this.to = to;
this.freq = freq;
this.orderAsc = orderAsc;
}
public long getFrom() {
return from;
}
public void setFrom(Integer from) {
this.from = from;
}
public long getTo() {
return to;
}
public void setTo(Integer to) {
this.to = to;
}
public String getFreq() {
return freq;
}
public void setFreq(String freq) {
this.freq = freq;
}
public Boolean getOrderAsc() {
return orderAsc;
}
public void setOrderAsc(Boolean orderAsc) {
this.orderAsc = orderAsc;
}
}
|
package com.ymhd.mifen.myself;
import com.example.mifen.R;
import com.ymhd.mifen.adapter.MyGridViewAdapterforcollection_hsitory;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class collection extends Activity {
private GridView gv;
private MyGridViewAdapterforcollection_hsitory mygvadapter;
private Integer[] imgs = { R.drawable.img14, R.drawable.img15, R.drawable.img16, R.drawable.img17, R.drawable.img18,
R.drawable.img19 };
private String[] str = { "BF风夹棉外套棉衣", "时尚混搭针织毛衣", "加厚拉链纯色小脚裤", "羊羔毛内里长款宽松棉衣", "BF风夹棉外套棉衣", "时尚混搭针织衫毛衣" };
private SharedPreferences sp;
SharedPreferences.Editor editor;
private TextView tv_changge, tv_delete;
private ImageView im_delete,myself_collection_history_back;
private LinearLayout myself_collection_history_delete;
private boolean type = false;
private CheckBox collection_history_select_all;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.myself_collection_history);
init();
}
public void init() {
initid();
tv_changge.setText("我的收藏");
sp = getSharedPreferences("checktype", Context.MODE_PRIVATE);
editor = sp.edit();
mygvadapter = new MyGridViewAdapterforcollection_hsitory(getApplicationContext(), imgs, str, gv);
gv.setAdapter(mygvadapter);
gv.setSelector(new ColorDrawable(Color.TRANSPARENT));
gv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
myself_collection_history_delete.setVisibility(View.VISIBLE);
tv_delete.setVisibility(View.VISIBLE);
im_delete.setVisibility(View.GONE);
editor.putBoolean("yes", true);
editor.commit();
type = true;
mygvadapter.notifyDataSetChanged();
return false;
}
});
myself_collection_history_back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
collection_history_select_all.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
editor.putBoolean("allcheck_collection_history", true);
editor.putBoolean("type_select", true);
} else {
editor.putBoolean("allcheck_collection_history", false);
editor.putBoolean("type_select", false);
for (int i = 0; i < str.length; i++) {
Log.e("11", ""+i);
editor.putBoolean("collection"+i, false);
}
}
editor.commit();
mygvadapter.notifyDataSetChanged();
}
});
}
public void initid() {
tv_changge = (TextView) findViewById(R.id.textChangge);
myself_collection_history_delete = (LinearLayout) findViewById(R.id.myself_collection_history_delete_lin);
gv = (GridView) findViewById(R.id.myself_collection_grivideview);
tv_delete = (TextView) findViewById(R.id.myself_collection_history_delete_titletv);
im_delete = (ImageView) findViewById(R.id.myself_collection_history_delete_titleim);
collection_history_select_all = (CheckBox) findViewById(R.id.collection_history_select_all);
myself_collection_history_back = (ImageView) findViewById(R.id.myself_collection_history_back);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (type) {
myself_collection_history_delete.setVisibility(View.GONE);
tv_delete.setVisibility(View.GONE);
im_delete.setVisibility(View.VISIBLE);
editor.putBoolean("yes", false);
editor.commit();
mygvadapter.notifyDataSetChanged();
type = false;
} else {
editor.clear();
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}
|
package StackCalculator.Command;
import StackCalculator.ConfigParser;
import StackCalculator.Exceptions.CommandNotFound;
import StackCalculator.Exceptions.WrongConfigFileFormat;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CommandFactory implements ICommandFactory {
private static final String CONFIG_FILE_NAME = "src/main/resources/cfg.txt";
private static Logger logger = Logger.getLogger(CommandFactory.class.getName());
private Map<String, ICommand> commandsList;
private volatile static CommandFactory instance = null;
public static CommandFactory getInstance() throws NoSuchMethodException, IOException, InstantiationException, WrongConfigFileFormat, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
if(instance == null) {
synchronized (CommandFactory.class) {
if(instance == null) {
instance = new CommandFactory();
}
}
}
return instance;
}
public CommandFactory() throws IOException, WrongConfigFileFormat, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
commandsList = new HashMap<String, ICommand>();
Map<String, String> tmp = ConfigParser.ConvertConfigFileToMap(CONFIG_FILE_NAME);
for(Map.Entry<String, String> entry : tmp.entrySet()) {
System.out.println("\'" + entry.getValue() + "\'");
ICommand command = (ICommand)(Class.forName(entry.getValue()).getDeclaredConstructor().newInstance());
commandsList.put(entry.getKey(), command);
}
}
@Override
public ICommand CreateCommand(String name, String parameters) throws CommandNotFound {
ICommand command = commandsList.get(name);
if(command == null) {
logger.log(Level.SEVERE, "Command " + name + " not found!");
throw new CommandNotFound("Command " + name + " not found!");
}
command.putArgs(parameters);
return command;
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s): ActiveEon Team - http://www.activeeon.com
*
* ################################################################
* $$ACTIVEEON_CONTRIBUTOR$$
*/
package org.ow2.proactive.scheduler.ext.common.util;
import java.io.*;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
/**
* Utility class which performs some IO work
*
* @author The ProActive Team
*/
public class IOTools {
private static String nl = System.getProperty("line.separator");
public static ProcessResult blockingGetProcessResult(Process process) {
final InputStream is = process.getInputStream();
final InputStream es = process.getErrorStream();
final ArrayList<String> out_lines = new ArrayList<String>();
final ArrayList<String> err_lines = new ArrayList<String>();
Thread t1 = new Thread(new Runnable() {
public void run() {
ArrayList<String> linesTemp = getContentAsList(is);
out_lines.addAll(linesTemp);
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
ArrayList<String> linesTemp = getContentAsList(es);
err_lines.addAll(linesTemp);
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
int retValue = 0;
try {
retValue = process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return new ProcessResult(retValue, out_lines.toArray(new String[0]), err_lines.toArray(new String[0]));
}
public static String generateHash(File file) throws NoSuchAlgorithmException, FileNotFoundException,
IOException {
if (!file.exists() || !file.canRead()) {
throw new IOException("File doesn't exist : " + file);
}
MessageDigest md = MessageDigest.getInstance("SHA"); // SHA or MD5
String hash = "";
byte[] data = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(data);
fis.close();
md.update(data); // Reads it all at one go. Might be better to chunk it.
byte[] digest = md.digest();
for (int i = 0; i < digest.length; i++) {
String hex = Integer.toHexString(digest[i]);
if (hex.length() == 1)
hex = "0" + hex;
hex = hex.substring(hex.length() - 2);
hash += hex;
}
return hash;
}
public static String generateHash(String bigString) throws NoSuchAlgorithmException,
FileNotFoundException, IOException {
MessageDigest md = MessageDigest.getInstance("SHA"); // SHA or MD5
String hash = "";
char[] data = new char[bigString.length()];
StringReader fis = new StringReader(bigString);
fis.read(data);
fis.close();
byte[] input = toByteArray(data);
md.update(input); // Reads it all at one go. Might be better to chunk it.
byte[] digest = md.digest();
for (int i = 0; i < digest.length; i++) {
String hex = Integer.toHexString(digest[i]);
if (hex.length() == 1)
hex = "0" + hex;
hex = hex.substring(hex.length() - 2);
hash += hex;
}
return hash;
}
public static byte[] toByteArray(char[] array) {
return toByteArray(array, Charset.defaultCharset());
}
public static byte[] toByteArray(char[] array, Charset charset) {
CharBuffer cbuf = CharBuffer.wrap(array);
ByteBuffer bbuf = charset.encode(cbuf);
return bbuf.array();
}
/**
* Return the content read through the given text input stream as a list of file
*
* @param is input stream to read
* @return content as list of strings
*/
public static ArrayList<String> getContentAsList(final InputStream is) {
final ArrayList<String> lines = new ArrayList<String>();
final BufferedReader d = new BufferedReader(new InputStreamReader(new BufferedInputStream(is)));
String line = null;
try {
line = d.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}
while (line != null) {
lines.add(line);
try {
line = d.readLine();
} catch (IOException e) {
e.printStackTrace();
line = null;
}
}
try {
is.close();
} catch (IOException e) {
}
return lines;
}
public static class RedirectionThread implements Runnable, Serializable {
/** */
private static final long serialVersionUID = 31L;
private InputStream is;
private OutputStream os;
private PrintStream out;
private BufferedReader br;
public RedirectionThread(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
this.out = new PrintStream(new BufferedOutputStream(os));
this.br = new BufferedReader(new InputStreamReader(new BufferedInputStream(is)));
}
public void run() {
String s;
try {
while ((s = br.readLine()) != null) {
synchronized (out) {
out.println(s);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void setOutputStream(OutputStream os) {
synchronized (out) {
out = new PrintStream(new BufferedOutputStream(os));
}
}
}
/**
* An utility class (Thread) which collects the output from a process and prints it on the JVM's standard output
*
* @author The ProActive Team
*/
public static class LoggingThread implements Runnable, Serializable {
/** */
private static final long serialVersionUID = 31L;
private String appendMessage;
/** */
public Boolean goon = true;
public Boolean patternFound = false;
private PrintStream out;
private PrintStream err;
private Process p;
private BufferedReader brout;
private BufferedReader brerr;
private boolean lastline_err = false;
private String startpattern;
private String stoppattern;
private String patternToFind;
private static String HOSTNAME;
static {
try {
HOSTNAME = java.net.InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
}
}
/** */
public ArrayList<String> output = new ArrayList<String>();
private PrintStream debugStream;
/**
* Create a new instance of LoggingThread.
*/
public LoggingThread() {
}
/**
* Create a new instance of LoggingThread.
*
* @param p
* @param appendMessage
* @param out
*/
public LoggingThread(Process p, String appendMessage, PrintStream out, PrintStream err,
String startpattern, String stoppattern, String patternToFind) {
this(p, appendMessage, out, err, null, startpattern, stoppattern, patternToFind);
}
public LoggingThread(Process p, String appendMessage, PrintStream out, PrintStream err,
PrintStream ds, String startpattern, String stoppattern, String patternToFind) {
this.brout = new BufferedReader(new InputStreamReader(p.getInputStream()));
this.brerr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
this.appendMessage = appendMessage;
this.out = out;
this.err = err;
this.debugStream = ds;
this.startpattern = startpattern;
this.stoppattern = stoppattern;
this.patternToFind = patternToFind;
this.p = p;
}
/**
* Create a new instance of LoggingThread.
*
* @param p
* @param appendMessage
* @param out
*/
public LoggingThread(Process p, String appendMessage, PrintStream out, PrintStream err, PrintStream ds) {
this(p, appendMessage, out, err, ds, null, null, null);
}
public LoggingThread(Process p) {
this.brout = new BufferedReader(new InputStreamReader(p.getInputStream()));
this.brerr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
this.out = null;
this.err = null;
this.appendMessage = null;
this.p = p;
}
private String getLineOrDie() {
String answer = null;
try {
while (goon) {
if (readyout()) {
answer = brout.readLine();
lastline_err = false;
return answer;
} else if (readyerr()) {
answer = brerr.readLine();
lastline_err = true;
return answer;
} else {
try {
p.exitValue();
return null;
} catch (IllegalThreadStateException ex) {
//Expected behaviour
}
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
goon = false;
}
}
} catch (IOException e) {
return null;
} finally {
if (patternToFind != null) {
if (answer != null && answer.contains(patternToFind)) {
patternFound = true;
}
}
}
return null;
}
private boolean readyout() throws IOException {
synchronized (brout) {
return brout.ready();
}
}
private boolean readyerr() throws IOException {
// We use only brout in locks
synchronized (brout) {
return brerr.ready();
}
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
String line = null;
boolean first_line = true;
boolean last_line = false;
if (out != null) {
while ((line = getLineOrDie()) != null && goon) {
synchronized (out) {
if (first_line && line.trim().length() > 0) {
if ((startpattern != null) && (line.contains(startpattern))) {
// we eat everything until the startpattern, if provided
startpattern = null;
continue;
} else if (startpattern != null) {
continue;
}
first_line = false;
printLine(line);
} else if (!first_line) {
if ((stoppattern != null) && (line.contains(stoppattern))) {
// at the stoppattern, we exit
goon = false;
} else {
printLine(line);
}
}
}
}
} else
while ((line = getLineOrDie()) != null && goon) {
}
try {
brout.close();
} catch (IOException e) {
// SCHEDULING-1296 not necessary to print the Exception but we need two try catch blocks
}
try {
brerr.close();
} catch (IOException e) {
}
}
private void printLine(String line) {
if (debugStream == null) {
if (lastline_err) {
err.println("[ " + HOSTNAME + " ] " + line);
err.flush();
} else {
out.println("[ " + HOSTNAME + " ] " + line);
out.flush();
}
} else {
if (lastline_err) {
err.println("[ " + HOSTNAME + " " + new java.util.Date() + " ]" + appendMessage + line);
err.flush();
} else {
out.println("[ " + HOSTNAME + " " + new java.util.Date() + " ]" + appendMessage + line);
out.flush();
}
debugStream.println("[ " + new java.util.Date() + " ]" + appendMessage + line);
debugStream.flush();
}
}
public void closeStream() {
synchronized (out) {
try {
out.close();
err.close();
} catch (Exception e) {
}
}
}
public void setOutStream(PrintStream out, PrintStream err, PrintStream ds) {
synchronized (this.out) {
try {
this.out.close();
this.err.close();
} catch (Exception e) {
}
if (this.debugStream != null) {
try {
this.debugStream.close();
} catch (Exception e) {
}
}
this.out = out;
this.err = err;
this.debugStream = ds;
}
}
public void setOutStream(PrintStream out, PrintStream err) {
setOutStream(out, err, null);
}
public void setProcess(Process p) {
synchronized (brout) {
this.brout = new BufferedReader(new InputStreamReader(p.getInputStream()));
this.brerr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
}
}
}
}
|
import java.util.LinkedList;
/**
* This class provides a simple text interface to the connect 4 engine.
*
* @author Jesper Kristensen
* @see ComputerPlayer
*/
public class ConnectFour {
//private boolean normalBoard = true;
private boolean p = true;
private ConnectFourRules cfr;
private LinkedList<ConnectFourListener> listeners;
public ConnectFour(ConnectFourRules cfr) {
this.cfr = cfr;
listeners = new LinkedList<ConnectFourListener>();
}
public void addListener(ConnectFourListener cfl) {
if (!listeners.contains(cfl))
listeners.add(cfl);
}
public void removeListener(ConnectFourListener cfl) {
listeners.remove(cfl);
}
public void newGame() {
if (p) System.out.println("new game");
for (int i=0; i<listeners.size(); i++)
listeners.get(i).newGame();
}
/**
* Informs the listener to update its state according to the played move.
* @param column a number between 0 and 6 indicating where the piece was put.
*/
public boolean put(int column) {
if (p) System.out.println("put " + column + "(num listeners = " + listeners.size() + ")");
if (getRules().getGameVariant() != 3) {
System.out.println("Column " + (column+1) + " played.");
} else {
System.out.println("Column " + ((column&3)+1) + "-" + (char)('A' + (column>>2)) + " played.");
}
switch (column) {
case -3:
quit();
break;
case -2:
newGame();
break;
case -1:
undo();
break;
default:
{
if (!cfr.canPut(column))
return false;
for (int i=0; i<listeners.size(); i++)
listeners.get(i).put(column);
return true;
}
}
return true;
}
/**
* Tells the listener to undo the last played move.
*/
public boolean undo() {
if (!cfr.canUndo())
return false;
if (p) System.out.println("undo");
for (int i=0; i<listeners.size(); i++)
listeners.get(i).undo();
return true;
}
/**
* Tells the listener to undo the last played move.
*/
public void quit() {
if (p) System.out.println("quit");
for (int i=0; i<listeners.size(); i++)
listeners.get(i).quit();
}
public ConnectFourRules getRules() {
return cfr;
}
}
|
package myarraylist;
/**
* Represents basic unsorted array-based list.
*
* @author Letian Sun
* @version Jan. 2, 2015
* @param <E> is of any object type
*/
public class ArrayListUnsorted<E> extends AbstractArrayMyList<E> {
/**
* Constructs a unsorted array list with a default capacity
*/
public ArrayListUnsorted() {
super(DEFAULT_CAPACITY);
}
/**
* Constructs a unsorted array list with a given capacity.
* @param capacity the given capacity
* @throws IllegalArgumentException if capacity <= 0
*/
public ArrayListUnsorted(int capacity) {
super(capacity);
}
/**
* Insert a value into the unsorted array list.
* @see mylistpackage.MyList#insert(java.lang.Object)
* @param value the value to insert into the array list.
*/
public void insert(E value) {
ensureCapacity(size + 1);
elementData[size] = value;
size++;
}
/**
* Remove the first occurrence of an element in unsorted array list.
* @param value the value to remove the first occurrence of.
* @see mylistpackage.MyList#remove(java.lang.Object)
*/
public void remove(E value) {
int index = getIndex(value);
//if the element is in the array, take action.
if (index >= 0) {
elementData[index] = elementData[size - 1];
elementData[size - 1] = null;
size--;
}
}
/**
* Returns the index of value.
* @param value assigned.
* @see mylistpackage.MyList#getIndex(Object)
* @return index of value if in the list, -1 otherwise.
*/
@Override
public int getIndex(E value) {
//Linear search
for (int i = 0; i < size; i++) {
if (elementData[i].equals(value)) {
return i;
}
}
return -1;
}
/**
* Remove a value at a specific index in unsorted array list
* @see mylistpackage.MyList#removeAtIndex(int)
* @param index index of the element to remove
* @throws IndexOutOfBoundsException if index < 0 or index >= size, not a valid index in the list
*/
@Override
public void removeAtIndex(int index) {
checkInBoundsOfArray(index);
elementData[index] = elementData[size-1];
//make element eligible for garbage collection
elementData[size - 1] = null;
size --;
}
/**
* Inserts the given value at the given index with non shifting approach.
* @param index <= size() and index >= 0
* @param value to insert at index
* @see mylistpackage.MyList#insertAtIndex(int, Object)
* @throws IndexOutOfBoundsException if 0 < index > size
*/
@Override
public void insertAtIndex(int index, E value) {
checkOkToInsertAtIndex(index);
ensureCapacity(size + 1);
elementData[size] = elementData[index];
elementData[index] = value;
size++;
}
} |
package com.edu.realestate.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.edu.realestate.model.City;
public class CityDaoJDBC extends AbstractDaoJDBC implements CityDao {
@Override
public void create(City element) {
// TODO Auto-generated method stub
}
@Override
public City read(Integer id) {
City city = null;
try {
Statement st = getConnection().createStatement();
String req = "SELECT * FROM city WHERE id = " + id;
ResultSet rs = st.executeQuery(req);
if (rs.next()) {
city = new City();
city.setId(rs.getInt("id"));
city.setName(rs.getString("name"));
city.setPostcode(rs.getString("postcode"));
city.setLongitude(rs.getDouble("longitude"));
city.setLatitude(rs.getDouble("latitude"));
}
} catch (SQLException e) {
System.out.println("CityDaoJDBC error : " + e.getLocalizedMessage());
}
return city;
}
@Override
public void update(City element) {
// TODO Auto-generated method stub
}
@Override
public void delete(City element) {
// TODO Auto-generated method stub
}
@Override
public List<City> listMatching(String comparator, boolean exact) {
List<City> list = new ArrayList<>();
try {
Statement st = getConnection().createStatement();
String where = "WHERE ";
if (comparator.matches("[0-9]+")) {
where += "postcode LIKE '" + comparator + "%'";
} else {
if (!exact)
where += "name LIKE '%" + comparator + "%'";
else
where += "name = '" + comparator + "'";
}
ResultSet rs = st.executeQuery("SELECT * FROM city "+ where + "ORDER BY name");
while (rs.next()) {
City city = new City();
city.setId(rs.getInt("id"));
city.setName(rs.getString("name"));
city.setPostcode(rs.getString("postcode"));
city.setLongitude(rs.getDouble("longitude"));
city.setLatitude(rs.getDouble("latitude"));
list.add(city);
}
} catch (SQLException e) {
System.out.println("CityDaoJDBC error : " + e.getLocalizedMessage());
}
return list;
}
@Override
public List<City> listAll() {
List<City> list = new ArrayList<>();
try {
Statement st = getConnection().createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM city ORDER BY name");
while (rs.next()) {
City city = new City();
city.setId(rs.getInt("id"));
city.setName(rs.getString("name"));
city.setPostcode(rs.getString("postcode"));
city.setLongitude(rs.getDouble("longitude"));
city.setLatitude(rs.getDouble("latitude"));
list.add(city);
}
} catch (SQLException e) {
System.out.println("CityDaoJDBC error : " + e.getLocalizedMessage());
}
return list;
}
}
|
package fr.unice.polytech.isa.polyevent.cli.framework;
public interface CommandBuilder<T extends Command>
{
String identifier();
default boolean match(String keyword)
{
return identifier().equals(keyword);
}
String describe();
default String help()
{
return describe();
}
T build(Context context);
}
|
package cs414.a5.bawitt.common;
public interface CashPayment {
double getAmountDue() throws java.rmi.RemoteException;
double getChange() throws java.rmi.RemoteException;
} |
package com.gaoshin.stock;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.widget.LinearLayout;
public class MenuView extends LinearLayout {
private MenuGroupList groups;
private ChartBrowser context;
public MenuView(ChartBrowser context) {
super(context);
setId(Math.abs(this.hashCode()));
this.context = context;
setOrientation(HORIZONTAL);
setGravity(Gravity.BOTTOM);
setBackgroundColor(0x80000000);
}
public void setMenus(MenuGroupList groups) {
removeAllViews();
this.groups = groups;
if(groups == null || groups.getItems().size() == 0) {
return;
}
int cols = groups.getItems().size();
DisplayMetrics metrics = context.getApp().getDisplayMetrics();
int width = (int) (metrics.widthPixels / metrics.density);
int colWidth = width / cols;
for(MenuList menuList : groups.getItems()) {
GroupedMenu gm = new GroupedMenu(getContext());
gm.setMenuList(menuList);
LayoutParams lp = new LayoutParams(colWidth, LayoutParams.WRAP_CONTENT);
addView(gm, lp);
}
}
}
|
package com.lti.CaseStudy.ComplaintManagement;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
/**
* Created by busis on 2020-12-08.
*/
public class FileToDataBase {
public static void main(String[] args) {
new FileToDataBase().addDataBase();
}
Connection con=null;
PreparedStatement ps =null;
public void addIntoForeignTable(Set<String> set, String tableName){
try{
con=new Connector().createConnection();
if(tableName.equals("issues"))
ps=con.prepareStatement("Insert into issues values (?,?)");
else if(tableName.equals("responses"))
ps=con.prepareStatement("Insert into responses values (?,?)");
else if(tableName.equals("companies"))
ps=con.prepareStatement("Insert into companies values (?,?)");
else
ps=con.prepareStatement("INSERT INTO products VALUES (?,?)");
int ind=1;
for(String s: set){
ps.setInt(1,ind);
ps.setString(2, s);
ps.executeUpdate();
ind++;
}
} catch (SQLException e) {
System.out.println("6");
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void insertIntoComplaints(String dateReceived, String product, String issue,
String company, String dateSent, String response,
String timelyResponse, int complaintId){
Connection connection=null;
PreparedStatement preparedStatement=null;
try{
connection=new Connector().createConnection();
preparedStatement=connection.prepareStatement("INSERT INTO complaints values (?,?,?,?,?,?,?,?)");
preparedStatement.setString(1,dateReceived);
preparedStatement.setInt(2,new FileToDataBase().getProductId(product));
preparedStatement.setInt(3,new FileToDataBase().getIssueId(issue));
preparedStatement.setInt(4,new FileToDataBase().getCompanyId(company));
preparedStatement.setString(5,dateSent);
preparedStatement.setInt(6,new FileToDataBase().getResponseId(response));
preparedStatement.setString(7,timelyResponse);
preparedStatement.setInt(8, complaintId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.out.println("5");
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public int getResponseId(String response){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try{
connection=new Connector().createConnection();
preparedStatement=connection.prepareStatement("Select responseId from responses where response=?");
preparedStatement.setString(1,response);
resultSet=preparedStatement.executeQuery();
if(resultSet.next()){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet.getInt(1);
}
} catch (SQLException e) {
System.out.println("4");
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public int getProductId(String product){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try{
connection=new Connector().createConnection();
preparedStatement=connection.prepareStatement("Select productId from products where product=?");
preparedStatement.setString(1,product);
resultSet=preparedStatement.executeQuery();
if(resultSet.next()){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("1");
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public int getIssueId(String issue){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try{
connection=new Connector().createConnection();
preparedStatement=connection.prepareStatement("Select issueId from issues where issue=?");
preparedStatement.setString(1,issue);
resultSet=preparedStatement.executeQuery();
if(resultSet.next()){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("2");
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public int getCompanyId(String company){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try{
connection=new Connector().createConnection();
preparedStatement=connection.prepareStatement("Select companyId from companies where company=?");
preparedStatement.setString(1,company);
resultSet=preparedStatement.executeQuery();
if(resultSet.next()){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("3");
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public void addDataBase(){
/*
This is based on optimized table structure
*/
String csvUrl="C:\\Users\\busis\\Desktop\\LTI\\Java Projects\\HelloWorld\\src\\com\\lti\\CaseStudy\\ComplaintManagement\\data.csv";
String line="";
String splitBy=",";
int n=0;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(csvUrl));
Set<String> productSet = new HashSet<String>();
Set<String> responseSet = new HashSet<String>();
Set<String> companySet = new HashSet<String>();
Set<String> issueSet = new HashSet<String>();
while ((line=bufferedReader.readLine())!=null){
String[] entries = line.split(splitBy);
int complaintId = Integer.parseInt(entries[8]);
new FileToDataBase().insertIntoComplaints(entries[0],entries[1],
entries[2],entries[3],entries[4],entries[5],entries[6],complaintId);
if(!productSet.contains(entries[1]))
productSet.add(entries[1]);
if(!responseSet.contains(entries[5]))
responseSet.add(entries[5]);
if(!companySet.contains(entries[3]))
companySet.add(entries[3]);
if(!issueSet.contains(entries[2]))
issueSet.add(entries[2]);
//This is used for making tables of issues, responses, products, companies
}
addIntoForeignTable(companySet,"companies");
addIntoForeignTable(issueSet,"issues");
addIntoForeignTable(productSet,"products");
addIntoForeignTable(responseSet,"responses");
//This is also used for creating foreign tables
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.gome.manager.service;
import java.util.List;
import com.gome.manager.common.Page;
import com.gome.manager.domain.Professor;
/**
* 会议service接口.
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 caowei 新建
* </pre>
*/
public interface MeetingProfessorService {
/**
*
* 分页查询会议列表.
*
* @param page
* 分页信息(封装了查询条件)
* @return
* 分页数据
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 caowei 新建
* </pre>
*/
Page<Professor> findMeetingProfessorListByPage(Page<Professor> p);
int addMeetingProfessor(Professor professor);
Professor findMeetingProfessorById(long parseLong);
int updateMeetingProfessor(Professor professor);
int deleteMeetingProfessorById(Long meetingId);
List<Professor> findMeetingProfessorResume(long parseLong);
int addMeetingProfessorRecode(Professor professor);
int delResume(Long meetingProfessorId);
List<Professor> findMeetingProfessorByMeetId(long parseLong);
}
|
package com.meehoo.biz.core.basic.ro.security;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* @author zc
* @date 2020-12-17
*/
@Setter
@Getter
public class SetDefinesRO {
private String roleId;
private List<String> menuDefineIds;
}
|
package com.cipher.c0753362_mad3125_midterm;
import android.content.Context;
import android.content.SharedPreferences;
public class SatelliteSharedPref {
public static final String isLogin = "isLogin";
public static final String emailId = "EmailID";
static final String PrefName = "Satellite1";
static final int Mode = Context.MODE_PRIVATE;
public static SharedPreferences getPreference(Context context){
return context.getSharedPreferences(PrefName,Mode);
}
public static SharedPreferences.Editor getEditor(Context context){
return getPreference(context).edit();
}
public static void writeString(Context context , String key , String value){
getEditor(context).putString(key,value).apply();
}
public static String readString (Context context , String key , String defaultValue){
return getPreference(context).getString(key,defaultValue);
}
public static void logout(Context context){
getPreference(context).edit().clear().commit();
getPreference(context).edit().apply();
}
}
|
package org.giddap.dreamfactory.topcoder;
/**
* http://community.topcoder.com/stat?c=problem_statement&pm=40&rd=2001
* <p/>
* Problem Statement
* <p/>
* Create a class called StringDup. Given a string made up of ONLY letters and
* digits, determine which character is repeated the most in the string ('A' is
* different than 'a'). If there is a tie, the character which appears first in
* the string (from left to right) should be returned.
* <p/>
* Examples :
* <p/>
* aaiicccnn = c
* aabbccdd = a
* ab2sbf2dj2skl = 2
* <p/>
* Here is the method signature :
* <p/>
* public char getMax(String input);
* <p/>
* We will check to make sure that the input contains only letters and digits (no
* punctuation marks or spaces).
*/
public class StringDup {
public char getMax(String input) {
if (input.length() < 1) {
return '\0';
}
int[] counters = new int[256];
int[] firstApperances = new int[256];
for (int i = 0; i < firstApperances.length; i++) {
firstApperances[i] = -1;
}
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
counters[c] = counters[c] + 1;
if (firstApperances[c] == -1) {
firstApperances[c] = i;
}
}
char maxChar = input.charAt(0);
for (int i = 0; i < counters.length; i++) {
if ((counters[i] > counters[maxChar])) {
maxChar = (char) i;
} else if ((counters[i] == counters[maxChar])) {
if (firstApperances[i] < firstApperances[maxChar]) {
maxChar = (char) i;
}
}
}
return maxChar;
}
}
|
package com.codingchili.authentication.controller;
import com.codingchili.authentication.configuration.AuthContext;
import com.codingchili.authentication.model.*;
import io.vertx.core.Future;
import com.codingchili.core.listener.CoreHandler;
import com.codingchili.core.listener.Request;
import com.codingchili.core.protocol.*;
import com.codingchili.core.security.Account;
import static com.codingchili.common.Strings.*;
import static com.codingchili.core.protocol.Role.PUBLIC;
/**
* @author Robin Duda
* Routing used to register/authenticate accounts.
*/
public class ClientHandler implements CoreHandler {
private final Protocol<ClientLogin> protocol = new Protocol<>();
private final AsyncAccountStore accounts;
private AuthContext context;
public ClientHandler(AuthContext context) {
this.context = context;
accounts = context.getAccountStore();
protocol.authenticator(this::authenticate)
.use(CLIENT_REGISTER, this::register, PUBLIC)
.use(CLIENT_AUTHENTICATE, this::authenticate, PUBLIC)
.use(ID_PING, Request::accept, PUBLIC);
}
@Override
public void handle(Request request) {
protocol.process(new ClientLogin(request));
}
private Future<RoleType> authenticate(Request request) {
Future<RoleType> future = Future.future();
context.verifyClientToken(request.token()).setHandler(verify -> {
if (verify.succeeded()) {
future.complete(Role.USER);
} else {
future.complete(Role.PUBLIC);
}
});
return future;
}
private void register(ClientLogin request) {
accounts.register(register -> {
if (register.succeeded()) {
sendAuthentication(register.result(), request, true);
} else {
request.error(register.cause());
}
}, request.getAccount());
}
private void authenticate(ClientLogin request) {
accounts.authenticate(authentication -> {
if (authentication.succeeded()) {
sendAuthentication(authentication.result(), request, false);
} else {
request.error(authentication.cause());
if (authentication.cause() instanceof AccountPasswordException)
context.onAuthenticationFailure(request.getAccount(), request.remote());
}
}, request.getAccount());
}
private void sendAuthentication(Account account, ClientLogin request, boolean registered) {
context.signClientToken(account.getUsername()).setHandler(sign -> {
request.write(
new ClientAuthentication(
account,
sign.result(),
registered));
if (registered)
context.onRegistered(account.getUsername(), request.remote());
else
context.onAuthenticated(account.getUsername(), request.remote());
});
}
@Override
public String address() {
return NODE_AUTHENTICATION_CLIENTS;
}
} |
package scc.storage;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microsoft.azure.cosmosdb.ConnectionMode;
import com.microsoft.azure.cosmosdb.ConnectionPolicy;
import com.microsoft.azure.cosmosdb.ConsistencyLevel;
import com.microsoft.azure.cosmosdb.Document;
import com.microsoft.azure.cosmosdb.DocumentClientException;
import com.microsoft.azure.cosmosdb.FeedOptions;
import com.microsoft.azure.cosmosdb.FeedResponse;
import com.microsoft.azure.cosmosdb.PartitionKey;
import com.microsoft.azure.cosmosdb.RequestOptions;
import com.microsoft.azure.cosmosdb.ResourceResponse;
import com.microsoft.azure.cosmosdb.internal.directconnectivity.ConflictException;
import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient;
import rx.Observable;
import scc.utils.GSON;
public class CosmosClient {
private static AsyncDocumentClient cosmosClient;
private static String cosmosDatabase;
private CosmosClient() {}
public static AsyncDocumentClient getCosmosClient() {
return cosmosClient;
}
public static String getCosmosDatabase() {
return cosmosDatabase;
}
public static void init(String cosmosDB, String cosmosDbMasterKey, String cosmosDbEndpoint) {
cosmosDatabase = cosmosDB;
ConnectionPolicy connectionPolicy = new ConnectionPolicy();
connectionPolicy.setConnectionMode(ConnectionMode.Direct);
cosmosClient = new AsyncDocumentClient.Builder().withServiceEndpoint(cosmosDbEndpoint)
.withMasterKeyOrResourceToken(cosmosDbMasterKey).withConnectionPolicy(connectionPolicy)
.withConsistencyLevel(ConsistencyLevel.Session).build();
}
@FunctionalInterface
public interface ResponseHandler {
Response execute(ResourceResponse<Document> response);
}
@FunctionalInterface
public interface ErrorHandler {
Response execute(Throwable error);
}
public static String getColllectionLink(String dabase_name, String container_name) {
return String.format("/dbs/%s/colls/%s", dabase_name, container_name);
}
public static String getDocumentLink(String dabase_name, String container_name, String id) {
return String.format("/dbs/%s/colls/%s/docs/%s", dabase_name, container_name, id);
}
public static String insert(String container_name, Object o) throws DocumentClientException {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
Observable<ResourceResponse<Document>> createDocumentObservable = cosmosClient.createDocument(collectionLink, o, null, false);
final CountDownLatch completionLatch = new CountDownLatch(1);
AtomicReference<String> at = new AtomicReference<>();
AtomicReference<DocumentClientException> at2 = new AtomicReference<>();
// Subscribe to Document resource response emitted by the observable
createDocumentObservable
.single() // We know there will be one response
.subscribe(documentResourceResponse -> {
at.set(documentResourceResponse.getResource().getId());
completionLatch.countDown();
}, error -> {
if (error instanceof ConflictException) {
at2.set(new DocumentClientException(Response.Status.CONFLICT.getStatusCode(),
(Exception) error));
} else {
at2.set(new DocumentClientException(500, (Exception) error));
}
error.printStackTrace();
completionLatch.countDown();
});
// Wait till document creation completes
try {
completionLatch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
DocumentClientException e = at2.get();
if (e == null) {
return at.get();
} else {
throw e;
}
}
public static <T> String getByName(String container_name, String name) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Iterator<FeedResponse<Document>> it = cosmosClient.queryDocuments(collectionLink,
"SELECT * FROM " + container_name + " c WHERE c.name = '" + name + "'", queryOptions).toBlocking()
.getIterator();
// NOTE: multiple documents can be returned or none
if (it.hasNext()) {
List<Document> doc = it.next().getResults();
if (doc.size() > 0)
return doc.get(0).toJson();
}
return null;
}
public static <T> T getByNameUnparse(String container_name, String name, Class<T> class_) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Iterator<FeedResponse<Document>> it = cosmosClient.queryDocuments(collectionLink,
"SELECT * FROM " + container_name + " c WHERE c.name = '" + name + "'", queryOptions).toBlocking()
.getIterator();
// NOTE: multiple documents can be returned or none
if (it.hasNext()) {
List<Document> doc = it.next().getResults();
if (doc.size() > 0) {
return GSON.fromJson(doc.get(0).toJson(), class_);
}
}
return null;
}
public static String getById(String container_name, String id) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Iterator<FeedResponse<Document>> it = cosmosClient.queryDocuments(collectionLink,
"SELECT * FROM " + container_name + " c WHERE c.id = '" + id + "'", queryOptions).toBlocking()
.getIterator();
// NOTE: multiple documents can be returned or none
if (it.hasNext()) {
List<Document> doc = it.next().getResults();
if (doc.size() > 0)
return doc.get(0).toJson();
}
return null;
}
public static <T> T getByIdUnparse(String container_name, String id, Class<T> class_) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Iterator<FeedResponse<Document>> it = cosmosClient.queryDocuments(collectionLink,
"SELECT * FROM " + container_name + " c WHERE c.id = '" + id + "'", queryOptions).toBlocking()
.getIterator();
// NOTE: multiple documents can be returned or none
if (it.hasNext()) {
List<Document> doc = it.next().getResults();
if (doc.size() > 0) {
return GSON.fromJson(doc.get(0).toJson(), class_);
}
}
return null;
}
public static <T> List<String> getNewest(String container_name) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Iterator<FeedResponse<Document>> it = cosmosClient.queryDocuments(collectionLink,
"SELECT * FROM " + container_name + " c ORDER BY c.creationTime DESC", queryOptions).toBlocking()
.getIterator();
List<String> list = new LinkedList<String>();
while (it.hasNext()) {
List<String> l = it.next().getResults().stream()
.map(d -> d.toJson()).collect(Collectors.toList());
list.addAll(l);
}
return list;
}
public static List<String> query(String container_name, String query) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Iterator<FeedResponse<Document>> it = cosmosClient
.queryDocuments(collectionLink, String.format(query, container_name), queryOptions).toBlocking()
.getIterator();
List<String> list = new LinkedList<String>();
while (it.hasNext()) {
List<String> l = it.next().getResults().stream().map(d -> d.toJson()).collect(Collectors.toList());
list.addAll(l);
}
return list;
}
public static <T> List<T> queryAndUnparse(String container_name, String query, Class<T> class_) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
String final_query = String.format(query, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Observable<FeedResponse<Document>> queryObservable = cosmosClient.queryDocuments(collectionLink, final_query,
queryOptions);
// Observable to Iterator
Iterator<FeedResponse<Document>> it = queryObservable.toBlocking().getIterator();
List<T> list = new LinkedList<T>();
while (it.hasNext()) {
List<T> l = it.next().getResults().stream().map(d -> GSON.fromJson(d.toJson(), class_))
.collect(Collectors.toList());
list.addAll(l);
}
return list;
}
public static <T> Entry<String,List<T>> queryAndUnparsePaginated(String container_name, String query, String continuationToken, int pageSize, Class<T> class_) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
String final_query = String.format(query, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setMaxItemCount(pageSize);
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
if (continuationToken != null)
queryOptions.setRequestContinuation(continuationToken);
Observable<FeedResponse<Document>> queryObservable = cosmosClient.queryDocuments(collectionLink, final_query, queryOptions);
// Observable to Iterator
Iterator<FeedResponse<Document>> it = queryObservable.toBlocking().getIterator();
List<T> list = new LinkedList<T>();
if(it.hasNext()) {
FeedResponse<Document> page = it.next();
List<T> l = page.getResults().stream().map(d -> GSON.fromJson(d.toJson(), class_))
.collect(Collectors.toList());
list.addAll(l);
continuationToken = page.getResponseContinuation();
}
return new AbstractMap.SimpleEntry<>(continuationToken, list);
}
public static <T> Iterator<FeedResponse<Document>> queryIterator(String container_name, String query) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
String final_query = String.format(query, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Observable<FeedResponse<Document>> queryObservable = cosmosClient.queryDocuments(collectionLink, final_query,
queryOptions);
// Observable to Iterator
Iterator<FeedResponse<Document>> it = queryObservable.toBlocking().getIterator();
return it;
}
public static int delete(String container_name, String query, String partition_key) {
String collectionLink = getColllectionLink(cosmosDatabase, container_name);
String final_query = String.format(query, container_name);
FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true);
queryOptions.setMaxDegreeOfParallelism(-1);
Observable<FeedResponse<Document>> queryObservable = cosmosClient.queryDocuments(collectionLink, final_query, queryOptions);
// Observable to Iterator
Iterator<FeedResponse<Document>> it = queryObservable.toBlocking().getIterator();
int deleted = 0;
while (it.hasNext()) {
List<Document> docs = it.next().getResults();
for(Document d : docs) {
Logger logger = LoggerFactory.getLogger(CosmosClient.class);
logger.info(d.getString("id"));
logger.info(d.getString(partition_key));
if(deleteDocument(container_name, d.getString("id"), d.getString(partition_key)))
deleted++;
}
}
return deleted;
}
public static boolean deleteDocument(String container_name, String id, String partition_key) {
String documentLink = getDocumentLink(cosmosDatabase, container_name, id);
RequestOptions options = new RequestOptions();
options.setPartitionKey(new PartitionKey(partition_key));
Observable<ResourceResponse<Document>> createDocumentObservable = cosmosClient.deleteDocument(documentLink, options);
final CountDownLatch completionLatch = new CountDownLatch(1);
AtomicReference<DocumentClientException> at = new AtomicReference<>();
createDocumentObservable.single() // we know there will be one response
.subscribe(documentResourceResponse -> {
completionLatch.countDown();
}, error -> {
if (error instanceof DocumentClientException)
at.set(new DocumentClientException(Response.Status.NOT_FOUND.getStatusCode(),
(Exception) error));
else
at.set(new DocumentClientException(500, (Exception) error));
completionLatch.countDown();
});
// Wait till document creation completes
try {
completionLatch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
DocumentClientException e = at.get();
if (e != null) {
e.printStackTrace();
return false;
} else
return true;
}
}
|
package com.alibaba.druid.bvt.pool;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.JdbcUtils;
public class TimeBetweenLogStatsMillisTest extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setTimeBetweenLogStatsMillis(1000);
// dataSource.setFilters("log4j");
}
protected void tearDown() throws Exception {
JdbcUtils.close(dataSource);
}
public void test_0() throws Exception {
Assert.assertEquals(true, dataSource.isResetStatEnable());
dataSource.init();
Assert.assertEquals(1000, dataSource.getTimeBetweenLogStatsMillis());
Assert.assertEquals(false, dataSource.isResetStatEnable());
dataSource.resetStat();
Assert.assertEquals(0, dataSource.getResetCount());
dataSource.setConnectionProperties("druid.resetStatEnable=true");
Assert.assertEquals(true, dataSource.isResetStatEnable());
dataSource.setConnectionProperties("druid.resetStatEnable=false");
Assert.assertEquals(false, dataSource.isResetStatEnable());
dataSource.setConnectionProperties("druid.resetStatEnable=xxx");
}
}
|
/* Treerow.java
Purpose:
Description:
History:
Tue Oct 22 14:45:31 2008, Created by Flyworld
Copyright (C) 2008 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zul.api;
/**
* A treerow.
* <p>
* Default {@link #getZclass}: z-treerow (since 5.0.0)
*
* @author tomyeh
* @since 3.5.2
*/
public interface Treerow extends org.zkoss.zul.impl.api.XulElement {
/**
* Returns the {@link Tree} instance containing this element.
*/
public org.zkoss.zul.api.Tree getTreeApi();
/**
* Returns the level this cell is. The root is level 0.
*/
public int getLevel();
/**
* Returns the {@link Treechildren} associated with this {@link Treerow}. In
* other words, it is {@link Treeitem#getTreechildrenApi} of
* {@link #getParent} .
*
* @see org.zkoss.zul.Treechildren#getLinkedTreerow
*/
public org.zkoss.zul.api.Treechildren getLinkedTreechildrenApi();
/** Returns the label of the {@link Treecell} it contains, or null
* if no such cell.
* @since 5.0.8
*/
public String getLabel();
/** Sets the label of the {@link Treecell} it contains.
*
* <p>If treecell are not created, we automatically create it.
*
* <p>Notice that this method will create a treecell automatically
* if they don't exist.
* @since 5.0.8
*/
public void setLabel(String label);
/** Returns the image of the {@link Treecell} it contains, or null
* if no such cell.
* @since 5.0.8
*/
public String getImage();
/** Sets the image of the {@link Treecell} it contains.
*
* <p>If treecell are not created, we automatically create it.
*
* <p>Notice that this method will create a treerow and treecell automatically
* if they don't exist.
* @since 5.0.8
*/
public void setImage(String image);
}
|
package pkgEnum;
//Comments to make the git submission work
public enum ePuzzleViolation {
DupRow, DupCol, DupRegion, InvalidValue, ContainsZero, MissingZero;
}
|
package exception.resources;/**
* Created by DELL on 2018/8/14.
*/
import java.io.IOException;
/**
* user is lwb
**/
public class TryResouces {
public static void main(String[] args){
//BufferedReader br = new BufferedReader();
TryResouces tryResouces = new TryResouces();
//tryResouces.resourcesSuppressedException();
//tryResouces.overrideException();
tryResouces.test();
}
public void resourcesSuppressedException(){
try(
Connection1 connection1 = new Connection1();//try-catch-resource主要就是为了防止finally中抛出异常覆盖也无异常。
Connection2 connection2 = new Connection2()){
throw new NullPointerException("logical ");//这个异常不会被覆盖
} catch (IOException e) {
e.printStackTrace();
}
}
public void overrideException() {
try{
throw new IOException("try");
}catch(Exception e){
e.printStackTrace();
//执行到这里之后,说明上面的try的异常已经被处理过了,如果抛出的异常是catch。
//throw new NullPointerException("catch");
}finally {
System.out.println("finally");
//如果finally抛出异常的话,那么只有finally的异常被抛出去,上面的try和catch的业务异常会被覆盖掉。
// 通常finally中资源关闭的操作,抛出的异常都是关于资源关闭通用异常,对我们进行调试基本上没有什么启示。
//throw new NullPointerException("finally");
}
}
public void test(){
try{
throw new NullPointerException("dddd");
}finally {
System.out.println(" adsfasdfasd ");
}
}
}
|
package com.dexvis.dex.wf;
import java.util.ArrayList;
import java.util.List;
import javafx.stage.Stage;
import com.dexvis.dex.exception.DexException;
import com.dexvis.javafx.scene.control.DexTaskItem;
public class ParallelJob implements DexJob
{
private Stage stage = null;
private List<DexTask> taskList = new ArrayList<DexTask>();
private boolean terminated = false;
public ParallelJob(List<DexTaskItem> itemList)
{
for (DexTaskItem item : itemList)
{
if (item != null)
{
if (item.getTask() != null)
{
DexTask task = item.getTask().get();
if (task != null)
{
taskList.add(task);
}
}
}
}
}
public void terminate()
{
setTerminated(true);
}
public boolean isTerminated()
{
return terminated;
}
public void setTerminated(boolean terminated)
{
this.terminated = terminated;
}
@Override
public DexJobState execute() throws DexException
{
DexJobState status = DexJobState.startState();
DexTaskState state = new DexTaskState();
// Need independent task state for each task.
for (DexTask task : taskList)
{
if (!isTerminated())
{
state = task.execute(state);
}
}
return status;
}
@Override
public DexJobState start() throws DexException
{
DexJobState status = DexJobState.startState();
DexTaskState state = new DexTaskState();
for (DexTask task : taskList)
{
state = task.start(state);
}
return status;
}
@Override
public void setStage(Stage stage) throws DexException
{
this.stage = stage;
}
@Override
public Stage getStage() throws DexException
{
return stage;
}
@Override
public List<DexTask> getTaskList()
{
return taskList;
}
}
|
package co.sblock.events.listeners.block;
import org.apache.commons.lang3.tuple.Pair;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import co.sblock.Sblock;
import co.sblock.effects.Effects;
import co.sblock.effects.effect.BehaviorActive;
import co.sblock.events.listeners.SblockListener;
import co.sblock.machines.Machines;
import co.sblock.machines.type.Machine;
import co.sblock.micromodules.Spectators;
/**
* Listener for BlockBreakEvents.
*
* @author Jikoo
*/
public class BreakListener extends SblockListener {
private final Effects effects;
private final Machines machines;
private final Spectators spectators;
private final BehaviorActive spectatorsDeserveFun;
public BreakListener(Sblock plugin) {
super(plugin);
this.effects = plugin.getModule(Effects.class);
this.machines = plugin.getModule(Machines.class);
this.spectators = plugin.getModule(Spectators.class);
this.spectatorsDeserveFun = (BehaviorActive) effects.getEffect("Unlucky");
}
/**
* The event handler for Machine deconstruction.
*
* @param event the BlockBreakEvent
*/
@EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Pair<Machine, ConfigurationSection> pair = machines.getMachineByBlock(event.getBlock());
if (pair != null) {
event.setCancelled(pair.getLeft().handleBreak(event, pair.getRight()));
return;
}
if (!spectators.canMineOre(event.getPlayer())) {
spectatorsDeserveFun.handleEvent(event, event.getPlayer(), 1);
return;
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onBlockBreakOccurred(BlockBreakEvent event) {
effects.handleEvent(event, event.getPlayer(), false);
effects.handleEvent(event, event.getPlayer(), true);
}
}
|
package com.z.zz.zzz.emu;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.z.zz.zzz.AntiDetector;
import com.z.zz.zzz.utils.L;
import com.z.zz.zzz.utils.U;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.z.zz.zzz.AntiDetector.TAG;
import androidx.core.content.ContextCompat;
public final class EmulatorDetector {
private static final String EMU_PATTERN_FILE_NAME = "emu_pattern.json";
public static int MIN_EMU_FLAGS_THRESHOLD = 3;
private static Property[] PROPERTIES = {};
private static EmuFeature[] EMU_FEATURES = {};
private static String[] EMU_FILES = {};
private static String[] X86_FILES = {};
private static String[] PIPES = {};
private static String[] PHONE_NUMBERS = {};
private static String[] DEVICE_IDS = {};
private static String[] IMSI_IDS = {};
private static String[] BLUETOOTH_PATH = {};
private static String[] QEMU_DRIVERS = {};
private static String[] IPs = {};
private static int MIN_PROPERTIES_THRESHOLD = 5;
private static int MIN_BUILD_THRESHOLD = 4;
private static EmulatorDetector sEmulatorDetector;
private static Context sContext;
private static JSONObject jBuild = new JSONObject();
private static JSONObject jEmu = new JSONObject();
private boolean isDebug;
private List<String> mListPackageName;
private EmulatorDetector(Context context) {
sContext = context;
parseEmuPattern(context);
}
public static EmulatorDetector with(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context must not be null.");
}
if (sEmulatorDetector == null) {
sEmulatorDetector = new EmulatorDetector(context.getApplicationContext());
}
return sEmulatorDetector;
}
public static String dump() {
JSONObject jo = new JSONObject();
U.putJsonSafed(jo, "build_info", getBuildInfo());
U.putJsonSafed(jo, "build_dump", jBuild);
U.putJsonSafed(jo, "emu_dump", jEmu);
return U.formatJson(jo);
}
private static JSONObject getBuildInfo() {
JSONObject jo = new JSONObject();
try {
U.putJsonSafed(jo, "PR", Build.PRODUCT);
U.putJsonSafed(jo, "MA", Build.MANUFACTURER);
U.putJsonSafed(jo, "BR", Build.BRAND);
U.putJsonSafed(jo, "BO", Build.BOARD);
U.putJsonSafed(jo, "DE", Build.DEVICE);
U.putJsonSafed(jo, "MO", Build.MODEL);
U.putJsonSafed(jo, "HW", Build.HARDWARE);
U.putJsonSafed(jo, "BL", Build.BOOTLOADER);
U.putJsonSafed(jo, "FP", Build.FINGERPRINT);
U.putJsonSafed(jo, "SE", U.getBuildSerial(sContext));
} catch (Exception e) {
}
return jo;
}
private void parseEmuPattern(Context context) {
JSONObject jData = null;
InputStream is = null;
try {
is = context.getResources().getAssets().open(EMU_PATTERN_FILE_NAME);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
String content = new String(buffer);
jData = new JSONObject(content);
} catch (Exception e) {
if (isDebug) {
L.e(TAG, "parseEmuPattern error: ", e);
} else {
L.w(TAG, "parseEmuPattern error: " + e);
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
MIN_EMU_FLAGS_THRESHOLD = U.getJsonSafed(jData, "min_emu_flags_threshold");
MIN_BUILD_THRESHOLD = U.getJsonSafed(jData, "min_build_threshold");
IPs = convertJsonToArray(jData, "ips");
QEMU_DRIVERS = convertJsonToArray(jData, "qemu_drivers");
PIPES = convertJsonToArray(jData, "pipes");
X86_FILES = convertJsonToArray(jData, "x86_files");
EMU_FILES = convertJsonToArray(jData, "emu_files");
JSONArray jProperties = U.getJsonSafed(jData, "properties");
PROPERTIES = new Property[jProperties.length()];
for (int i = 0; i < jProperties.length(); i++) {
JSONObject jo = U.getJsonSafed(jProperties, i);
Iterator<String> it = jo.keys();
while (it.hasNext()) {
String key = it.next();
String value = U.getJsonSafed(jo, key);
Property p = new Property(key, value);
PROPERTIES[i] = p;
}
}
MIN_PROPERTIES_THRESHOLD = U.getJsonSafed(jData, "min_properties_threshold");
String[] packages = convertJsonToArray(jData, "packages");
mListPackageName = Arrays.asList(packages);
PHONE_NUMBERS = convertJsonToArray(jData, "phone_numbers");
DEVICE_IDS = convertJsonToArray(jData, "device_id");
IMSI_IDS = convertJsonToArray(jData, "imsi");
BLUETOOTH_PATH = convertJsonToArray(jData, "bluetooth_path");
JSONArray jEmuFeatures = U.getJsonSafed(jData, "emu_features");
EMU_FEATURES = new EmuFeature[jEmuFeatures.length()];
for (int i = 0; i < jEmuFeatures.length(); i++) {
JSONObject jo = U.getJsonSafed(jEmuFeatures, i);
String name = U.getJsonSafed(jo, "name");
String[] filePath = convertJsonToArray(jo, "file_path");
String[] systemProperties = convertJsonToArray(jo, "sys_prop");
Map<String, String> buildProperties = convertJsonToMap(jo, "build_prop");
EmuFeature ef = new EmuFeature(name, filePath, systemProperties, buildProperties);
EMU_FEATURES[i] = ef;
}
log("@@@@@@@@@@@ Parse " + EMU_PATTERN_FILE_NAME + " finished.");
}
private String[] convertJsonToArray(JSONObject data, String name) {
JSONArray ja = U.getJsonSafed(data, name);
if (ja == null) {
return new String[0];
}
String[] content = new String[ja.length()];
for (int i = 0; i < ja.length(); i++) {
content[i] = U.getJsonSafed(ja, i);
}
return content;
}
private Map<String, String> convertJsonToMap(JSONObject data, String name) {
Map<String, String> result = new HashMap<>();
JSONArray ja = U.getJsonSafed(data, name);
if (ja == null) {
return result;
}
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = U.getJsonSafed(ja, i);
Iterator<String> it = jo.keys();
while (it.hasNext()) {
String key = it.next();
String value = U.getJsonSafed(jo, key);
result.put(key, value);
}
}
return result;
}
private void log(String str) {
L.v(TAG, "Emu ---> " + str);
}
private void logW(String str) {
L.w(TAG, "Emu ---> " + str);
}
// 是否能跳转拨号盘
private boolean checkResolveDialAction(Context context) {
String url = "tel:" + "12345678910";
Intent intent = new Intent();
intent.setData(Uri.parse(url));
intent.setAction(Intent.ACTION_DIAL);
if (intent.resolveActivity(context.getPackageManager()) == null) {
log("checkResolveDialAction failed --- Failed to resolve dial action");
U.putJsonSafed(jEmu, "da", 1);
return true;
}
return false;
}
// 是否有蓝牙硬件
private boolean checkBluetoothHardware() {
// 兼容64位ARM处理器
for (String path : BLUETOOTH_PATH) {
if (U.fileExist(path)) {
return false;
}
}
log("checkBluetoothHardware failed --- Not found libbluetooth_jni.so");
U.putJsonSafed(jEmu, "bt", 1);
return true;
}
// 是否有GPS硬件
private boolean checkGPSHardware(Context context) {
LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (mgr == null) {
log("checkGPSHardware failed --- No LocationManager service");
U.putJsonSafed(jEmu, "gp", 1);
return true;
}
List<String> providers = mgr.getAllProviders();
if (providers == null) {
log("checkGPSHardware failed --- No LocationManager providers");
U.putJsonSafed(jEmu, "gp", 1);
return true;
}
boolean containGPS = providers.contains(LocationManager.GPS_PROVIDER);
if (!containGPS) {
log("checkGPSHardware failed --- No GPS provider");
U.putJsonSafed(jEmu, "gp", 1);
return true;
}
return false;
}
// 是否支持多点触控
private boolean checkMultiTouch(Context context) {
boolean hasFeature = context.getPackageManager().hasSystemFeature(
"android.hardware.touchscreen.multitouch");
if (!hasFeature) {
log("checkMultiTouch failed --- No multitouch feature");
U.putJsonSafed(jEmu, "mt", 1);
return true;
}
return false;
}
private boolean checkEmuFeature() {
for (EmuFeature ef : EMU_FEATURES) {
String name = ef.name;
String[] filePath = ef.filePath;
String[] systemProperties = ef.systemProperties;
Map<String, String> buildProperties = ef.buildProperties;
for (String path : filePath) {
if (U.fileExist(path)) {
logW("Check (" + name + ") file {" + path + "} is detected");
U.putJsonSafed(jEmu, "fe", 1);
return true;
}
}
for (String sysProp : systemProperties) {
if (!Build.UNKNOWN.equals(U.getSystemProperties(sysProp))) {
logW("Check (" + name + ") system properties {" + sysProp + "} is detected");
U.putJsonSafed(jEmu, "fe", 1);
return true;
}
}
Set<String> set = buildProperties.keySet();
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String key = it.next();
String value = buildProperties.get(key);
if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
if (U.getSystemProperties(key).toLowerCase().contains(value.toLowerCase())) {
logW("Check (" + name + ") build properties {" + key + "} is detected");
U.putJsonSafed(jEmu, "fe", 1);
return true;
}
}
}
}
return false;
}
// CPU信息
private boolean checkCpuInfo() {
String cpu = getCPUInfo();
if (!TextUtils.isEmpty(cpu)) {
if (cpu.toLowerCase().contains("intel") || cpu.toLowerCase().contains("amd")) {
logW("Check CpuInfo {" + cpu + "} is detected");
U.putJsonSafed(jEmu, "ci", 1);
return true;
}
}
return false;
}
// 设备版本
private boolean checkDeviceInfo() {
String device = getDeviceInfo();
if (!TextUtils.isEmpty(device)) {
if (device.toLowerCase().contains("qemu")
|| device.toLowerCase().contains("tencent")
|| device.toLowerCase().contains("ttvm")
|| device.toLowerCase().contains("tiantian")) {
logW("Check DeviceInfo {" + device + "} is detected");
U.putJsonSafed(jEmu, "di", 1);
return true;
}
}
return false;
}
private String getCPUInfo() {
String name = "";
InputStreamReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader("/proc/cpuinfo");
br = new BufferedReader(fr);
String line;
while (true) {
line = br.readLine();
if (line == null) {
break;
}
String[] info = line.split(":\\s+", 2);
if (info.length >= 2) {
String k = info[0].trim();
String v = info[1].trim();
if ("Hardware".equalsIgnoreCase(k)) {
name = v;
} else if ("model name".equalsIgnoreCase(k)) {
name = v;
}
}
}
} catch (Exception e) {
if (isDebug) {
L.e(TAG, "getCPUInfo error: ", e);
} else {
L.w(TAG, "getCPUInfo error: " + e);
}
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
}
}
}
return name;
}
private String getDeviceInfo() {
String result = "";
ProcessBuilder cmd;
Process process = null;
InputStream in = null;
try {
String[] args = {"/system/bin/cat", "/proc/version"};
cmd = new ProcessBuilder(args);
process = cmd.start();
in = process.getInputStream();
byte[] re = new byte[256];
while (in.read(re) != -1) {
result = result + new String(re);
}
} catch (Exception e) {
if (isDebug) {
L.e(TAG, "getDeviceInfo error: ", e);
} else {
L.w(TAG, "getDeviceInfo error: " + e);
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (process != null) {
process.destroy();
}
}
return result.trim();
}
// Build属性
private boolean checkBuildProperty() {
jBuild = new JSONObject();
int flags = 0;
// FINGERPRINT
String fingerprint = Build.FINGERPRINT;
if (!TextUtils.isEmpty(fingerprint)) {
if (fingerprint.toLowerCase().contains("generic")
|| fingerprint.toLowerCase().contains("test-keys")) {
U.putJsonSafed(jBuild, "fp", 1);
flags++;
}
}
// MODEL
String model = Build.MODEL;
if (!TextUtils.isEmpty(model)) {
if (model.toLowerCase().contains("google_sdk")
|| model.toLowerCase().contains("emulator")
|| model.contains("Android SDK built for x86")) {
U.putJsonSafed(jBuild, "mo", 1);
flags++;
}
}
// BRAND
String brand = Build.BRAND;
if (!TextUtils.isEmpty(brand)) {
if (brand.toLowerCase().contains("generic") || brand.toLowerCase().contains("android")) {
U.putJsonSafed(jBuild, "br", 1);
flags++;
}
}
// DEVICE
String device = Build.DEVICE;
if (!TextUtils.isEmpty(device)) {
if (device.toLowerCase().contains("generic")) {
U.putJsonSafed(jBuild, "de", 1);
flags++;
}
}
// HARDWARE
String hardware = Build.HARDWARE;
if (!TextUtils.isEmpty(hardware)) {
if (hardware.equalsIgnoreCase("goldfish")) {
U.putJsonSafed(jBuild, "hw", 1);
flags++;
}
}
// PRODUCT
String product = Build.PRODUCT;
if (!TextUtils.isEmpty(product)) {
if (product.equalsIgnoreCase("google_sdk")
|| product.equalsIgnoreCase("sdk_x86")) {
U.putJsonSafed(jBuild, "pr", 1);
flags++;
}
}
// BOARD
String board = Build.BOARD;
if (!TextUtils.isEmpty(board)) {
if (board.equalsIgnoreCase(Build.UNKNOWN)) {
U.putJsonSafed(jBuild, "bo", 1);
flags++;
}
}
// SERIAL
String serial = U.getBuildSerial(sContext);
L.i(TAG, ">>> Build.SERIAL: " + serial + ", SDK_INT: " + Build.VERSION.SDK_INT);
if (!TextUtils.isEmpty(serial)) {
if (serial.toLowerCase().contains("android") || serial.toLowerCase().contains("emulator")) {
U.putJsonSafed(jBuild, "se", 1);
flags++;
}
}
log("checkBuildProperty(): " + flags + " (thresholds: " + MIN_BUILD_THRESHOLD + ")");
if (flags > 0) {
U.putJsonSafed(jBuild, "fl", flags);
}
if (AntiDetector.getDefault().mData != null) {
AntiDetector.getDefault().mData.put("emu_build", jBuild.toString());
}
if (flags >= MIN_BUILD_THRESHOLD) {
U.putJsonSafed(jEmu, "bd", 1);
return true;
}
return false;
}
public boolean detect() {
jEmu = new JSONObject();
boolean result = doCheckEmu(sContext);
if (AntiDetector.getDefault().mData != null) {
AntiDetector.getDefault().mData.put("emu_snapshot", jEmu.toString());
}
return result;
}
public EmulatorDetector setDebug(boolean debug) {
isDebug = debug;
return this;
}
private boolean doCheckEmu(Context context) {
boolean result = false;
if (isDebug) {
JSONObject jo = executeGetProp();
L.v(TAG, "call executeGetProp(): " + U.formatJson((jo)));
}
if (checkEmuFeature()) {
if (isDebug) {
result = true;
} else {
return true;
}
}
if (checkCpuInfo()) {
if (isDebug) {
result = true;
} else {
return true;
}
}
if (checkDeviceInfo()) {
if (isDebug) {
result = true;
} else {
return true;
}
}
if (checkAdvanced()) {
if (isDebug) {
result = true;
} else {
return true;
}
}
int flags = 0;
if (checkBuildProperty()) {
flags++;
}
if (checkResolveDialAction(context)) {
flags++;
}
if (checkBluetoothHardware()) {
flags++;
}
if (checkGPSHardware(context)) {
flags++;
}
if (checkMultiTouch(context)) {
flags++;
}
log("CheckEmu flags: " + flags + " (thresholds: " + MIN_EMU_FLAGS_THRESHOLD + ")");
if (flags > 0) {
U.putJsonSafed(jEmu, "fl", flags);
}
if (flags >= MIN_EMU_FLAGS_THRESHOLD) {
if (isDebug) {
result = true;
} else {
return true;
}
}
if (isDebug) {
return result;
} else {
return false;
}
}
private boolean checkAdvanced() {
if (isDebug) {
boolean isTelePhony = checkTelephony();
boolean isIp = checkIp();
boolean isPackageName = checkPackageName();
boolean isEmuFile = checkFiles(EMU_FILES);
boolean isPipe = checkFiles(PIPES);
boolean isX86File = checkQEmuProps() && checkFiles(X86_FILES);
boolean isQEmuDrivers = checkQEmuDrivers();
return isTelePhony || isIp || isPackageName || isEmuFile || isPipe || isX86File || isQEmuDrivers;
} else {
return checkTelephony()
|| checkIp()
|| checkPackageName()
|| checkFiles(EMU_FILES)
|| checkFiles(PIPES)
|| (checkQEmuProps() && checkFiles(X86_FILES))
|| checkQEmuDrivers();
}
}
private boolean checkPackageName() {
if (mListPackageName.isEmpty()) {
return false;
}
PackageManager packageManager = sContext.getPackageManager();
for (String pkgName : mListPackageName) {
Intent tryIntent = packageManager.getLaunchIntentForPackage(pkgName);
if (tryIntent != null) {
List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(tryIntent,
PackageManager.MATCH_DEFAULT_ONLY);
if (!resolveInfos.isEmpty()) {
U.putJsonSafed(jEmu, "pg", 1);
return true;
}
}
}
return false;
}
private boolean checkTelephony() {
if (isDebug) {
boolean isPhoneNumber = checkPhoneNumber();
boolean isDeviceId = checkDeviceId();
boolean isImsi = checkImsi();
boolean isOperatorNameAndroid = checkOperatorNameAndroid();
return isPhoneNumber || isDeviceId || isImsi || isOperatorNameAndroid;
} else {
return checkPhoneNumber()
|| checkDeviceId()
|| checkImsi()
|| checkOperatorNameAndroid();
}
}
@SuppressLint("MissingPermission")
private boolean checkPhoneNumber() {
try {
TelephonyManager telephonyManager = (TelephonyManager) sContext.getSystemService(
Context.TELEPHONY_SERVICE);
String phoneNumber = telephonyManager.getLine1Number();
for (String known_number : PHONE_NUMBERS) {
if (known_number.equalsIgnoreCase(phoneNumber)) {
logW("Check PhoneNumber {" + known_number + "} is detected");
U.putJsonSafed(jEmu, "pn", 1);
return true;
}
}
} catch (Throwable th) {
th.printStackTrace();
}
return false;
}
@SuppressLint("MissingPermission")
private boolean checkDeviceId() {
try {
TelephonyManager telephonyManager = (TelephonyManager) sContext.getSystemService(
Context.TELEPHONY_SERVICE);
String deviceId = telephonyManager.getDeviceId();
for (String known_deviceId : DEVICE_IDS) {
if (known_deviceId.equalsIgnoreCase(deviceId)) {
logW("Check DeviceId {" + known_deviceId + "} is detected");
U.putJsonSafed(jEmu, "de", 1);
return true;
}
}
} catch (Throwable th) {
th.printStackTrace();
}
return false;
}
@SuppressLint("MissingPermission")
private boolean checkImsi() {
try {
TelephonyManager telephonyManager = (TelephonyManager) sContext.getSystemService(
Context.TELEPHONY_SERVICE);
String imsi = telephonyManager.getSubscriberId();
for (String known_imsi : IMSI_IDS) {
if (known_imsi.equalsIgnoreCase(imsi)) {
logW("Check IMSI {" + known_imsi + "} is detected");
U.putJsonSafed(jEmu, "im", 1);
return true;
}
}
} catch (Throwable th) {
th.printStackTrace();
}
return false;
}
private boolean checkOperatorNameAndroid() {
String operatorName = ((TelephonyManager) sContext.getSystemService(Context.TELEPHONY_SERVICE))
.getNetworkOperatorName();
if (operatorName.equalsIgnoreCase("android")) {
logW("Check Operator {" + operatorName + "} is detected");
U.putJsonSafed(jEmu, "no", 1);
return true;
}
return false;
}
private boolean checkQEmuDrivers() {
for (File drivers_file : new File[]{new File("/proc/tty/drivers"),
new File("/proc/cpuinfo")}) {
if (drivers_file.exists() && drivers_file.canRead()) {
byte[] data = new byte[1024];
InputStream is = null;
try {
is = new FileInputStream(drivers_file);
is.read(data);
String driver_data = new String(data);
for (String known_qemu_driver : QEMU_DRIVERS) {
if (driver_data.contains(known_qemu_driver)) {
logW(">>> Check QEmu Drivers {" + known_qemu_driver + "} is detected");
U.putJsonSafed(jEmu, "qd", known_qemu_driver);
return true;
}
}
} catch (Exception e) {
if (isDebug) {
L.e(TAG, "checkQEmuDrivers error: ", e);
} else {
L.w(TAG, "checkQEmuDrivers error: " + e);
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
}
return false;
}
private boolean checkFiles(String[] targets) {
for (String file : targets) {
if (U.fileExist(file)) {
logW(">>> Check file {" + file + "} is detected");
U.putJsonSafed(jEmu, "fd", 1);
return true;
}
}
return false;
}
private boolean checkQEmuProps() {
int found_props = 0;
for (Property property : PROPERTIES) {
String property_value = U.getSystemProperties(property.name);
if (TextUtils.isEmpty(property.seek_value) && !Build.UNKNOWN.equals(property_value)) {
logW(">>> Check QEmu Properties {" + property + "} is detected");
found_props++;
}
if (!TextUtils.isEmpty(property.seek_value) && property_value.contains(property.seek_value)) {
logW(">>> Check QEmu Properties {" + property + "} is detected");
found_props++;
}
}
log("checkQEmuProps(): " + found_props + " (thresholds: " + MIN_PROPERTIES_THRESHOLD + ")");
if (found_props >= MIN_PROPERTIES_THRESHOLD) {
U.putJsonSafed(jEmu, "qp", found_props);
return true;
}
return false;
}
private boolean checkIp() {
String[] args = {"/system/bin/netcfg"};
InputStream in = null;
Process process = null;
StringBuilder sb = new StringBuilder();
try {
ProcessBuilder pb = new ProcessBuilder(args);
pb.directory(new File("/system/bin/"));
pb.redirectErrorStream(true);
process = pb.start();
in = process.getInputStream();
byte[] re = new byte[1024];
while (in.read(re) != -1) {
sb.append(new String(re));
}
} catch (Exception e) {
if (isDebug) {
L.e(TAG, "checkIp error: ", e);
} else {
L.w(TAG, "checkIp error: " + e);
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (process != null) {
process.destroy();
}
}
String netData = sb.toString();
if (!TextUtils.isEmpty(netData)) {
log(">>> netcfg data -> " + netData);
String[] array = netData.split("\n");
for (String ip : IPs) {
for (String lan : array) {
if ((lan.contains("wlan0") || lan.contains("tunl0") || lan.contains("eth0"))
&& lan.contains(ip)) {
logW(">>> Check IP {" + ip + "} is detected");
U.putJsonSafed(jEmu, "ip", 1);
return true;
}
}
}
}
return false;
}
private JSONObject executeGetProp() {
JSONObject jProps = new JSONObject();
try {
String regs = "([\\]\\[])";
Pattern pattern = Pattern.compile(regs);
String[] strCmd = new String[]{"getprop"};
List<String> execResult = U.executeCommand(strCmd);
JSONArray ja = new JSONArray();
U.putJsonSafed(jProps, "props", ja);
int i = 0;
for (String cmd : execResult) {
String[] line = cmd.split(":");
Matcher matcher0 = pattern.matcher(line[0]);
line[0] = matcher0.replaceAll("").trim();
Matcher matcher1 = pattern.matcher(line[1]);
line[1] = matcher1.replaceAll("").trim();
JSONObject jo = new JSONObject();
U.putJsonSafed(jo, "name", line[0]);
U.putJsonSafed(jo, "value", line[1]);
U.putJsonSafed(ja, i++, jo);
}
return jProps;
} catch (Exception e) {
if (isDebug) {
L.e(TAG, "executeGetProp error: ", e);
} else {
L.w(TAG, "executeGetProp error: " + e);
}
}
return jProps;
}
private boolean isSupportTelePhony() {
PackageManager packageManager = sContext.getPackageManager();
return packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}
class Property {
String name;
String seek_value;
Property(String name, String seek_value) {
this.name = name;
this.seek_value = seek_value;
}
@Override
public String toString() {
return new StringBuilder()
.append("[")
.append(name)
.append(": ")
.append(seek_value)
.append("]")
.toString();
}
}
class EmuFeature {
String name;
String[] filePath;
String[] systemProperties;
Map<String, String> buildProperties;
EmuFeature(String name, String[] filePath, String[] systemProperties,
Map<String, String> buildProperties) {
this.name = name;
this.filePath = filePath;
this.systemProperties = systemProperties;
this.buildProperties = buildProperties;
}
@Override
public String toString() {
return new StringBuilder()
.append("[")
.append(name)
.append(" | ")
.append(Arrays.asList(filePath))
.append(" | ")
.append(Arrays.asList(systemProperties))
.append(" | ")
.append(buildProperties)
.append("]")
.toString();
}
}
}
|
package com.tfg.evelyn.electroroute_v10;
/*
* Copyright (C) 2015 Google Inc. 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.
*/
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.support.v4.content.ContextCompat;
import android.support.v4.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private static final String tag = "myloginfo";
/* GPS Constant Permission */
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 12;
private double lat,lon;
private String name,tipo,dir,des,imagen;
private float rat;
private int cont;
private String action = "SEARCH";
private AlertDialog alert = null;
Marker lastOpened = null;
ArrayList<PlaceAsObject> placesList = new ArrayList<>();
private LoadPlaceActivity places;
boolean nuevo_sitio_creado;
LatLng actualLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//Get the the places from BBDD
places = new LoadPlaceActivity(this);
places.runLoadPlacesActivity();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
nuevo_sitio_creado = false;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
//mMap.addMarker(new MarkerOptions().position(location).title("Marker"));
if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(MapsActivity.this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COARSE_LOCATION);
}
mMap.setMyLocationEnabled(true);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
mMap.animateCamera(zoom);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
LocationService locationService = LocationService.getLocationManager(MapsActivity.this);
if (locationService.canGetLocation()) {
lat = locationService.getLatitude();
lon = locationService.getLongitude();
} else {
locationService.showSettingsAlert();
}
//if ((location.getLatitude() != lat) || (location.getLongitude()!=lon)){
CameraUpdate cam = CameraUpdateFactory.newLatLng(new LatLng(lat, lon));
mMap.moveCamera(cam);
// }
actualLocation= new LatLng(lat, lon);
places.runLoadPlacesActivity();
addNearPlaces(places.getPlacesList());
}
});
// mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng latLng) {
Log.i(tag, latLng.toString());
crearSitio(latLng.latitude, latLng.longitude);
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
// Check if there is an open info window
if (lastOpened != null) {
// Close the info window
lastOpened.hideInfoWindow();
// Is the marker the same marker that was already open
if (lastOpened.equals(marker)) {
// Nullify the lastOpened object
lastOpened = null;
// Return so that the info window isn't opened again
return true;
}
}
getInfoContents(marker.getPosition().latitude, marker.getPosition().longitude);
// Open the info window for the marker
//marker.showInfoWindow();
Intent i = new Intent(MapsActivity.this,ShowInfoMarker.class);
i.putExtra("EXTRA_LATITUDE", marker.getPosition().latitude);
i.putExtra("EXTRA_LONGITUDE", marker.getPosition().longitude);
i.putExtra("EXTRA_TIPO", tipo);
i.putExtra("EXTRA_NAME", name);
i.putExtra("EXTRA_DIR", dir);
i.putExtra("EXTRA_DES", des);
i.putExtra("EXTRA_RTNG", rat);
i.putExtra("EXTRA_CONT", cont);
i.putExtra("EXTRA_LAT", lat);
i.putExtra("EXTRA_LON", lon);
startActivity(i);
// Re-assign the last opened such that we can close it later
lastOpened = marker;
// Event was handled by our code do not launch default behaviour.
return true;
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode)
{
case MY_PERMISSION_ACCESS_COARSE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
} else {
// permission denied
}
}
break;
case MY_PERMISSION_ACCESS_FINE_LOCATION : {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
} else {
// permission denied
}
break;
}
}
}
private void addNearPlaces(ArrayList<PlaceAsObject> placesList){
Log.i("****LUGARES 2 **", String.format("Place: " + placesList.size()));
for (PlaceAsObject place : placesList){
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(place.getLat(), place.getLon()))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_green_car))
.title(place.getName().toString())
.snippet("Direccion:" + place.getDirection()));
}
Log.i("****LUGARES **", "TERMINO EL ADDNEAR");
}
private void crearSitio(final double la, final double lo) {
// Use the Builder class for convenient dialog construction
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.create_place)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(MapsActivity.this, CreatePlaceActivity.class);
i.putExtra("EXTRA_LATITUDE", la);
i.putExtra("EXTRA_LONGITUDE", lo);
startActivity(i);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
dialog.cancel();
}
});
// Create the AlertDialog object and return it
nuevo_sitio_creado = true;
alert= builder.create();
alert.show();
}
public void getInfoContents(double lat, double lng) {
// Getting the position from the marker
Log.i("****MARKER****", String.format("MARKER: " + lat + " " + lng));
Log.i("**LIST PLACE **", String.format("Place: " + placesList.size()));
// Setting the info
placesList = places.getPlacesList();
for (PlaceAsObject place : placesList) {
Log.i("****LIST PLACE****", String.format("PLACE: " + place));
if ((place.getLat() == lat) && (place.getLon() == lng)) {
tipo = "Tipo: " + place.getType();
name = place.getName();
dir = "Dirección: " + place.getDirection();
des = "Descripción: " + place.getDescription();
imagen = place.getImage();
rat= place.getRating();
cont = place.getContador();
}
}
}
}
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.com) 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 org.wso2.appcloud.pingdom.service.util;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.appcloud.pingdom.service.HeartbeatServiceException;
import java.io.IOException;
import java.sql.*;
import java.util.HashSet;
import java.util.Set;
public class Utils {
private static final Logger log = LoggerFactory.getLogger(Utils.class);
public static Connection getDatabaseConnection(String dbURL, String dbUser, String dbUserPassword)
throws HeartbeatServiceException {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dbURL, dbUser, dbUserPassword);
} catch (SQLException e) {
String errorMsg = "Failed to get database connection to database:" + dbURL;
log.error(errorMsg, e);
throw new HeartbeatServiceException(errorMsg, e);
} catch (ClassNotFoundException e) {
String errorMsg = "Failed to load jdbc driver class.";
log.error(errorMsg, e);
throw new HeartbeatServiceException(errorMsg, e);
}
return connection;
}
public static Set<String> getApplicationLaunchURLs(String dbURL, String dbUser, String dbUserPassword)
throws HeartbeatServiceException {
Set<String> applicationURLs = new HashSet<>();
Connection dbConnection = getDatabaseConnection(dbURL, dbUser, dbUserPassword);
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = dbConnection.prepareStatement("SELECT * FROM APP_CLOUD_LAUNCH_URLS");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
applicationURLs.add(resultSet.getString("LAUNCH_URL"));
}
} catch (SQLException e) {
String msg = "Error while retrieving application launch URLs from database.";
log.error(msg, e);
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
log.error("Failed to close database connection properly.", e);
}
}
return applicationURLs;
}
public static boolean isApplicationHealthy(String launchURL) throws HeartbeatServiceException {
boolean isApplicationHealthy = true;
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(launchURL);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
isApplicationHealthy = false;
byte[] responseBody = method.getResponseBody();
log.error(
"Failed to get 200 ok response from url:" + launchURL + " due to " + new String(responseBody));
}
} catch (IOException e) {
isApplicationHealthy = false;
log.error("Failed to invoke url:" + launchURL + " and get proper response.", e);
} finally {
method.releaseConnection();
}
return isApplicationHealthy;
}
}
|
package seedu.project.logic.commands;
import static java.util.Objects.requireNonNull;
import seedu.project.commons.core.Messages;
import seedu.project.logic.CommandHistory;
import seedu.project.logic.LogicManager;
import seedu.project.logic.commands.exceptions.CommandException;
import seedu.project.model.Model;
/**
* Lists all unique tags and their tasks to the user.
*/
public class ListTagCommand extends Command {
public static final String COMMAND_ALIAS = "lt";
public static final String COMMAND_WORD = "listtag";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Shows a list of all available tags prefix and its related tasks. " + "Example: " + COMMAND_WORD;
@Override
public CommandResult execute(Model model, CommandHistory history) throws CommandException {
requireNonNull(model);
if (!LogicManager.getState()) {
throw new CommandException(String.format(Messages.MESSAGE_GO_TO_TASK_LEVEL, COMMAND_WORD));
}
String filteredTags = model.getTagWithTaskList();
return new CommandResult(filteredTags);
}
}
|
package com.pelephone_mobile.mypelephone.network.rest.pojos;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by Gali.Issachar on 06/01/14.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class CurrentInvoiceStateItem extends Pojo {
// to map to the property in json
@JsonProperty("responseError")
public ResponseErrorItem responseError;
// to map to the property in json
@JsonProperty("accountStatementIncludingTax")
public float accountStatementIncludingTax;
// to map to the property in json
@JsonProperty("remainderToCycle")
public int remainderToCycle;
}
|
package com.cyj.common.base;
/**
* @Description
* @Author cyj
* @Date 17/4/6
* @Version 1.0
*/
public class NewsBaseResponse<T> {
public T _embedded;
public T get_embedded() {
return _embedded;
}
public void set_embedded(T _embedded) {
this._embedded = _embedded;
}
}
|
package com.partnertap.cache;
import com.partnertap.cache.service.ServiceConfig;
import com.partnertap.cache.config.PartnertapCacheConfig;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.util.TimeZone;
@SpringBootApplication
@ComponentScan(basePackages = {"com.partnertap.rest.controller"})
@Import({ServiceConfig.class, PartnertapCacheConfig.class})
public class PartnertapCacheApplication {
public static void main(String[] args) {
SpringApplication.run(PartnertapCacheApplication.class, args);
}
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
// builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.modules(new JodaModule());
builder.failOnUnknownProperties(false);
builder.timeZone(TimeZone.getDefault());
builder.failOnUnknownProperties(false);
return builder;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-520
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.01.02 at 02:31:37 PM EST
//
package org.imo.gisis.xml.lrit.ddp._2008;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import org.imo.gisis.xml.lrit.types._2008.PolygonType;
/**
* <p>Java class for contractingGovernmentType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="contractingGovernmentType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Name">
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="isoCode" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}iso3166-1Alpha3CodeType" />
* </extension>
* </simpleContent>
* </complexType>
* </element>
* <element name="NationalPointsOfContact">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ContactPoint" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}contactPointType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="DataCentreInfo" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}dataCentreInfoType"/>
* <element name="ASPInfo" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}aspInfoType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="SARServices">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="SARService" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}sarServiceType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="Ports">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Port" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}portType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="PortFacilities">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="PortFacility" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}portFacilityType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="Places">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Place" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}placeType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="InternalWaters">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Polygon" type="{http://gisis.imo.org/XML/LRIT/types/2008}polygonType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="TerritorialSea">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Polygon" type="{http://gisis.imo.org/XML/LRIT/types/2008}polygonType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="SeawardAreaOf1000NM">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Polygon" type="{http://gisis.imo.org/XML/LRIT/types/2008}polygonType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="CustomCoastalAreas">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Polygon" type="{http://gisis.imo.org/XML/LRIT/types/2008}polygonType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="lritID" use="required" type="{http://gisis.imo.org/XML/LRIT/types/2008}contractingGovernmentLRITIDType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "contractingGovernmentType", propOrder = {
"name",
"nationalPointsOfContact",
"dataCentreInfo",
"aspInfo",
"sarServices",
"ports",
"portFacilities",
"places",
"internalWaters",
"territorialSea",
"seawardAreaOf1000NM",
"customCoastalAreas"
})
@XmlSeeAlso({
TerritoryType.class
})
public class ContractingGovernmentType {
@XmlElement(name = "Name", required = true)
protected ContractingGovernmentType.Name name;
@XmlElement(name = "NationalPointsOfContact", required = true)
protected ContractingGovernmentType.NationalPointsOfContact nationalPointsOfContact;
@XmlElement(name = "DataCentreInfo", required = true)
protected DataCentreInfoType dataCentreInfo;
@XmlElement(name = "ASPInfo")
protected List<AspInfoType> aspInfo;
@XmlElement(name = "SARServices", required = true)
protected ContractingGovernmentType.SARServices sarServices;
@XmlElement(name = "Ports", required = true)
protected ContractingGovernmentType.Ports ports;
@XmlElement(name = "PortFacilities", required = true)
protected ContractingGovernmentType.PortFacilities portFacilities;
@XmlElement(name = "Places", required = true)
protected ContractingGovernmentType.Places places;
@XmlElement(name = "InternalWaters", required = true)
protected ContractingGovernmentType.InternalWaters internalWaters;
@XmlElement(name = "TerritorialSea", required = true)
protected ContractingGovernmentType.TerritorialSea territorialSea;
@XmlElement(name = "SeawardAreaOf1000NM", required = true)
protected ContractingGovernmentType.SeawardAreaOf1000NM seawardAreaOf1000NM;
@XmlElement(name = "CustomCoastalAreas", required = true)
protected ContractingGovernmentType.CustomCoastalAreas customCoastalAreas;
@XmlAttribute(required = true)
protected String lritID;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.Name }
*
*/
public ContractingGovernmentType.Name getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.Name }
*
*/
public void setName(ContractingGovernmentType.Name value) {
this.name = value;
}
/**
* Gets the value of the nationalPointsOfContact property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.NationalPointsOfContact }
*
*/
public ContractingGovernmentType.NationalPointsOfContact getNationalPointsOfContact() {
return nationalPointsOfContact;
}
/**
* Sets the value of the nationalPointsOfContact property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.NationalPointsOfContact }
*
*/
public void setNationalPointsOfContact(ContractingGovernmentType.NationalPointsOfContact value) {
this.nationalPointsOfContact = value;
}
/**
* Gets the value of the dataCentreInfo property.
*
* @return
* possible object is
* {@link DataCentreInfoType }
*
*/
public DataCentreInfoType getDataCentreInfo() {
return dataCentreInfo;
}
/**
* Sets the value of the dataCentreInfo property.
*
* @param value
* allowed object is
* {@link DataCentreInfoType }
*
*/
public void setDataCentreInfo(DataCentreInfoType value) {
this.dataCentreInfo = value;
}
/**
* Gets the value of the aspInfo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the aspInfo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getASPInfo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AspInfoType }
*
*
*/
public List<AspInfoType> getASPInfo() {
if (aspInfo == null) {
aspInfo = new ArrayList<AspInfoType>();
}
return this.aspInfo;
}
/**
* Gets the value of the sarServices property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.SARServices }
*
*/
public ContractingGovernmentType.SARServices getSARServices() {
return sarServices;
}
/**
* Sets the value of the sarServices property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.SARServices }
*
*/
public void setSARServices(ContractingGovernmentType.SARServices value) {
this.sarServices = value;
}
/**
* Gets the value of the ports property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.Ports }
*
*/
public ContractingGovernmentType.Ports getPorts() {
return ports;
}
/**
* Sets the value of the ports property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.Ports }
*
*/
public void setPorts(ContractingGovernmentType.Ports value) {
this.ports = value;
}
/**
* Gets the value of the portFacilities property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.PortFacilities }
*
*/
public ContractingGovernmentType.PortFacilities getPortFacilities() {
return portFacilities;
}
/**
* Sets the value of the portFacilities property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.PortFacilities }
*
*/
public void setPortFacilities(ContractingGovernmentType.PortFacilities value) {
this.portFacilities = value;
}
/**
* Gets the value of the places property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.Places }
*
*/
public ContractingGovernmentType.Places getPlaces() {
return places;
}
/**
* Sets the value of the places property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.Places }
*
*/
public void setPlaces(ContractingGovernmentType.Places value) {
this.places = value;
}
/**
* Gets the value of the internalWaters property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.InternalWaters }
*
*/
public ContractingGovernmentType.InternalWaters getInternalWaters() {
return internalWaters;
}
/**
* Sets the value of the internalWaters property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.InternalWaters }
*
*/
public void setInternalWaters(ContractingGovernmentType.InternalWaters value) {
this.internalWaters = value;
}
/**
* Gets the value of the territorialSea property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.TerritorialSea }
*
*/
public ContractingGovernmentType.TerritorialSea getTerritorialSea() {
return territorialSea;
}
/**
* Sets the value of the territorialSea property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.TerritorialSea }
*
*/
public void setTerritorialSea(ContractingGovernmentType.TerritorialSea value) {
this.territorialSea = value;
}
/**
* Gets the value of the seawardAreaOf1000NM property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.SeawardAreaOf1000NM }
*
*/
public ContractingGovernmentType.SeawardAreaOf1000NM getSeawardAreaOf1000NM() {
return seawardAreaOf1000NM;
}
/**
* Sets the value of the seawardAreaOf1000NM property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.SeawardAreaOf1000NM }
*
*/
public void setSeawardAreaOf1000NM(ContractingGovernmentType.SeawardAreaOf1000NM value) {
this.seawardAreaOf1000NM = value;
}
/**
* Gets the value of the customCoastalAreas property.
*
* @return
* possible object is
* {@link ContractingGovernmentType.CustomCoastalAreas }
*
*/
public ContractingGovernmentType.CustomCoastalAreas getCustomCoastalAreas() {
return customCoastalAreas;
}
/**
* Sets the value of the customCoastalAreas property.
*
* @param value
* allowed object is
* {@link ContractingGovernmentType.CustomCoastalAreas }
*
*/
public void setCustomCoastalAreas(ContractingGovernmentType.CustomCoastalAreas value) {
this.customCoastalAreas = value;
}
/**
* Gets the value of the lritID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLritID() {
return lritID;
}
/**
* Sets the value of the lritID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLritID(String value) {
this.lritID = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Polygon" type="{http://gisis.imo.org/XML/LRIT/types/2008}polygonType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"polygon"
})
public static class CustomCoastalAreas {
@XmlElement(name = "Polygon")
protected List<PolygonType> polygon;
/**
* Gets the value of the polygon property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the polygon property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPolygon().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PolygonType }
*
*
*/
public List<PolygonType> getPolygon() {
if (polygon == null) {
polygon = new ArrayList<PolygonType>();
}
return this.polygon;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Polygon" type="{http://gisis.imo.org/XML/LRIT/types/2008}polygonType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"polygon"
})
public static class InternalWaters {
@XmlElement(name = "Polygon")
protected List<PolygonType> polygon;
/**
* Gets the value of the polygon property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the polygon property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPolygon().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PolygonType }
*
*
*/
public List<PolygonType> getPolygon() {
if (polygon == null) {
polygon = new ArrayList<PolygonType>();
}
return this.polygon;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="isoCode" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}iso3166-1Alpha3CodeType" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
public static class Name {
@XmlValue
protected String value;
@XmlAttribute
protected String isoCode;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the isoCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIsoCode() {
return isoCode;
}
/**
* Sets the value of the isoCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIsoCode(String value) {
this.isoCode = value;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ContactPoint" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}contactPointType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"contactPoint"
})
public static class NationalPointsOfContact {
@XmlElement(name = "ContactPoint")
protected List<ContactPointType> contactPoint;
/**
* Gets the value of the contactPoint property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the contactPoint property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContactPoint().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ContactPointType }
*
*
*/
public List<ContactPointType> getContactPoint() {
if (contactPoint == null) {
contactPoint = new ArrayList<ContactPointType>();
}
return this.contactPoint;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Place" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}placeType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"place"
})
public static class Places {
@XmlElement(name = "Place")
protected List<PlaceType> place;
/**
* Gets the value of the place property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the place property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPlace().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PlaceType }
*
*
*/
public List<PlaceType> getPlace() {
if (place == null) {
place = new ArrayList<PlaceType>();
}
return this.place;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="PortFacility" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}portFacilityType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"portFacility"
})
public static class PortFacilities {
@XmlElement(name = "PortFacility")
protected List<PortFacilityType> portFacility;
/**
* Gets the value of the portFacility property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the portFacility property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPortFacility().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PortFacilityType }
*
*
*/
public List<PortFacilityType> getPortFacility() {
if (portFacility == null) {
portFacility = new ArrayList<PortFacilityType>();
}
return this.portFacility;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Port" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}portType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"port"
})
public static class Ports {
@XmlElement(name = "Port")
protected List<PortType> port;
/**
* Gets the value of the port property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the port property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPort().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PortType }
*
*
*/
public List<PortType> getPort() {
if (port == null) {
port = new ArrayList<PortType>();
}
return this.port;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="SARService" type="{http://gisis.imo.org/XML/LRIT/ddp/2008}sarServiceType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"sarService"
})
public static class SARServices {
@XmlElement(name = "SARService")
protected List<SarServiceType> sarService;
/**
* Gets the value of the sarService property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the sarService property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSARService().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SarServiceType }
*
*
*/
public List<SarServiceType> getSARService() {
if (sarService == null) {
sarService = new ArrayList<SarServiceType>();
}
return this.sarService;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Polygon" type="{http://gisis.imo.org/XML/LRIT/types/2008}polygonType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"polygon"
})
public static class SeawardAreaOf1000NM {
@XmlElement(name = "Polygon")
protected List<PolygonType> polygon;
/**
* Gets the value of the polygon property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the polygon property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPolygon().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PolygonType }
*
*
*/
public List<PolygonType> getPolygon() {
if (polygon == null) {
polygon = new ArrayList<PolygonType>();
}
return this.polygon;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Polygon" type="{http://gisis.imo.org/XML/LRIT/types/2008}polygonType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"polygon"
})
public static class TerritorialSea {
@XmlElement(name = "Polygon")
protected List<PolygonType> polygon;
/**
* Gets the value of the polygon property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the polygon property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPolygon().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PolygonType }
*
*
*/
public List<PolygonType> getPolygon() {
if (polygon == null) {
polygon = new ArrayList<PolygonType>();
}
return this.polygon;
}
}
}
|
package com.example.Web.Model.dto;
import com.example.Web.Model.Uloga;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
@Getter
@Setter
@AllArgsConstructor
public class RegistracijaDTO {
private String korisnickoIme;
private String ime;
private String prezime;
private String lozinka;
private String telefon;
private String email;
private Date datumRodjenja;
private Uloga uloga;
public RegistracijaDTO(){}
}
|
package day4;
import java.io.IOException;
class NF{
void ageCheck(int age) throws Exception{
if(age > 18)
System.out.println("Eligible to vote!!!");
else
throw new NumberFormatException("You are not eligible to vote!!!");
}
void n() throws IOException {
System.out.println("Device error found!");
}
}
public class ThrowsExample {
public static void main(String[] args){
NF n = new NF();
try {
n.ageCheck(13);
n.n();
}catch(Exception e) {
System.out.println(e);
}finally {}
}
}
|
import java.util.Scanner;
import java.io.IOException;
class Result {
public static long mod(long n){
final long MOD = 1000000009;
if(n >= MOD)
return n % MOD;
if(n < 0)
return ((n % MOD) + MOD) % MOD;
return n;
}
public static long[] naive(long[] x, long[] y, int n){
long[] c = new long[2*n - 1];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
c[i+j] += mod(x[i] * y[j]);
}
}
return c;
}
public static long[] smellCosmos(long[] a, long[] b, int n) {
//initialize variables
long[] aHI = new long[n/2];
long[] aLO = new long[n/2];
long[] bHI = new long[n/2];
long[] bLO = new long[n/2];
long[] c = new long[2*n - 1];
long[] d1 = new long[n/2];
long[] d2 = new long[n/2];
//Naive algorithm is more efficient when n < 64
if(n <= 64) {
return naive(a, b, n);
//Karatsuba is more efficient when n >= 64
}else{
//Populate aLO and bLO
for(int i = 0; i < n/2; i++) {
aLO[i] = a[i];
bLO[i] = b[i];
}
//Populate aHI and bHI
for(int i = n/2; i < n; i++) {
aHI[i-n/2] = a[i];
bHI[i-n/2] = b[i];
}
//Populate d1 and d2
for(int i = 0; i < n/2; i++) {
d1[i] = mod(aLO[i] + aHI[i]);
d2[i] = mod(bLO[i] + bHI[i]);
}
//recursive calls
long[] cMID = smellCosmos(d1, d2, n/2);
long[] cLO = smellCosmos(aLO, bLO, n/2);
long[] cHI = smellCosmos(aHI, bHI, n/2);
for(int i = 0; i < n-1; i++) {
c[i] = cLO[i];
}
c[n-1] = 0;
for(int i = 0; i < n-1; i++) {
c[n+i] = cHI[i];
}
for(int i = 0; i < n-1; i++) {
c[n/2 + i] += mod(cMID[i] - (cLO[i] + cHI[i]));
}
return c;
}
}
}
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt() + 1;
long[] a = new long[n];
long[] b = new long[n];
for (int i = 0; i < n; i++) {
a[i] = input.nextLong();
}
for (int i = 0; i < n; i++) {
b[i] = input.nextLong();
}
long[] result = Result.smellCosmos(a, b, n);
for(int i = 0; i < result.length; i++) {
System.out.print(Result.mod(Result.mod(result[i])) + " ");
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.inbio.ara.eao.format.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.inbio.ara.eao.format.*;
import javax.ejb.Stateless;
import org.inbio.ara.eao.BaseEAOImpl;
import org.inbio.ara.dto.format.ReportLayoutDTO;
import org.inbio.ara.persistence.format.ReportLayout;
/**
*
* @author pcorrales
*/
@Stateless
public class ReportLayoutEAOImpl extends BaseEAOImpl<ReportLayout,Long> implements ReportLayoutEAOLocal{
public List<ReportLayoutDTO> getAllReportLayoutByFuncionality(Long funcionalityTypeId) {
try{
Query query = em.createQuery("select new org.inbio.ara.dto.format.ReportLayoutDTO(i.reportLayoutKeyWord,i.reportLayoutId)" +
" from ReportLayout as i");
return query.getResultList();
}
catch(Exception e){System.out.println(e);return new ArrayList<ReportLayoutDTO>();}
}
}
|
package cn.jiucaituan.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.jiucaituan.web.entity.Hello;
import cn.jiucaituan.web.service.HelloService;
@Controller
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping(value = "/hello/{name}")
public String hello(ModelMap map, @PathVariable("name") String name) {
Hello hello = helloService.getHello(name);
map.put("hello", hello);
return "hello";
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.orm.repository;
import xyz.noark.core.annotation.PlayerId;
import xyz.noark.core.annotation.orm.Id;
import xyz.noark.orm.cache.DataCache;
import xyz.noark.orm.cache.MultiDataCacheImpl;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
/**
* 封装了一套缓存机制的ORM数据访问层.
* <p>
* 应用于一种情况:<br>
* 1.有{@link PlayerId}注解并且和{@link Id}注解标识不同属性的实体类. <br>
* 可以理解为,一个角色可以有多条记录数据的类.<br>
*
* @param <T> 实体类
* @param <K> 实体类的主键
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
public class MultiCacheRepository<T, K extends Serializable> extends AbstractCacheRepository<T, K> {
/**
* 从缓存中删除指定Id的对象.
*
* @param playerId 玩家Id
* @param entityId 缓存对象的Id
*/
public void cacheDelete(Serializable playerId, K entityId) {
T result = dataCache.load(playerId, entityId);
dataCache.delete(result);
asyncWriteService.delete(entityMapping, result);
}
/**
* 删除角色模块缓存里的所有数据.
*
* @param playerId 角色Id
*/
public void cacheDeleteAll(Serializable playerId) {
List<T> result = dataCache.deleteAll(playerId);
asyncWriteService.deleteAll(entityMapping, result);
}
/**
* 从角色缓存中根据实体Id获取对象.
*
* @param playerId 角色Id
* @param entityId 实体Id
* @return 实体对象.
*/
public Optional<T> cacheLoad(Serializable playerId, K entityId) {
return Optional.ofNullable(dataCache.load(playerId, entityId));
}
/**
* 从角色缓存中根据实体Id获取对象.
*
* @param playerId 角色Id
* @param entityId 实体Id
* @return 实体对象.
*/
public T cacheGet(Serializable playerId, K entityId) {
return dataCache.load(playerId, entityId);
}
/**
* 从角色缓存中根据过滤器获取对象.
*
* @param playerId 角色Id
* @param filter 条件过滤器
* @return 实体对象.
*/
public T cacheGet(Serializable playerId, Predicate<T> filter) {
return this.cacheLoad(playerId, filter).orElse(null);
}
/**
* 从角色缓存中根据过滤器获取对象.
*
* @param playerId 角色Id
* @param filter 条件过滤器
* @return 实体对象.
*/
public Optional<T> cacheLoad(Serializable playerId, Predicate<T> filter) {
return Optional.ofNullable(dataCache.load(playerId, filter));
}
/**
* 统计角色缓存中符合过滤条件的对象总数。
*
* @param playerId 角色Id
* @param filter 条件过滤器
* @return 符合过滤条件的对象总数。
*/
public long cacheCount(Serializable playerId, Predicate<T> filter) {
return dataCache.count(playerId, filter);
}
/**
* 从角色缓存中获取一个模块所有缓存数据.
*
* @param playerId 角色Id
* @return 一个模块所有缓存数据.
*/
public List<T> cacheLoadAll(Serializable playerId) {
return dataCache.loadAll(playerId);
}
/**
* 从缓存中获取符合过虑器的需求的对象.
*
* @param playerId 角色Id
* @param filter 过虑器
* @return 符合过虑器的需求的对象列表.
*/
public List<T> cacheLoadAll(Serializable playerId, Predicate<T> filter) {
return dataCache.loadAll(playerId, filter);
}
@Override
protected DataCache<T, K> buildDataCache(int offlineInterval) {
return new MultiDataCacheImpl<>(this, offlineInterval);
}
} |
import java.util.*;
public class CF {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
HashMap<String,String> map=new HashMap<>();
for(int i=0;i<m;i++)
{
String s1=sc.next();
String s2=sc.next();
map.put(s1,s1.length()>s2.length()?s2:s1);
}
for(int i=0;i<n;i++)
{
System.out.print(map.get(sc.next())+" ");
}
}
}
|
package com.arthur.bishi.xiecheng0415;
import java.util.Scanner;
/**
* @title: No2
* @Author ArthurJi
* @Date: 2021/4/15 18:57
* @Version 1.0
*/
public class No2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int root = scanner.nextInt();
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
String[] split = s.split(",");
}
}
}
|
package com.algaworks.algamoney.api.logic.bean;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AddressDTO {
private String street;
private String number;
private String complement;
private String cp;
private String city;
private String state;
}
|
package com.checklist.interfaces;
public interface OnTaskSelectedListener {
void onTaskSelected(String id);
}
|
package com.stk123.common.db;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import com.stk123.common.db.util.DBUtil;
public class Database {
private String dbConnectionName = null;
private String databaseName = null;
private String schema = null;
private Map<String,Table> tables = new HashMap<String,Table>();
private Database(String dbConnectionName){
this.dbConnectionName = dbConnectionName;
}
public static Database getInstance(){
return Database.getInstance(null);
}
public static Database getInstance(String dbConnection) {
return new Database(dbConnection);
}
public Table getTable(String tableName){
Table instance = null;
String tableNameUpper = tableName.trim().toUpperCase();
if((instance = tables.get(tableNameUpper)) != null){
return instance;
}
instance = new Table(tableNameUpper,this);
tables.put(tableNameUpper, instance);
return instance;
}
/*public void setTable(Table table){
tables.put(table.getName(), table);
}*/
public String getDBConnectionName(){
return this.dbConnectionName;
}
public String getDatabaseName(){
if(databaseName == null)
databaseName = getCurrentDatabaseName();
return databaseName;
}
public String getSchema(){
if(schema == null)
schema = getCurrentSchema();
return schema;
}
public Connection getDBConnection() throws Exception {
//System.out.println("table="+this.getName()+",getDBConnectionName()=========="+getDBConnectionName());
return DBUtil.getConnection(getDBConnectionName());
}
private String getCurrentSchema() {
DatabaseMetaData dm;
try {
dm = this.getDBConnection().getMetaData();
return dm.getUserName();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String getCurrentDatabaseName() {
DatabaseMetaData dm;
try {
dm = this.getDBConnection().getMetaData();
return dm.getDatabaseProductName();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
package utilities;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.ArrayList;
import java.util.List;
public class ArrayListConverter {
public <T> ObservableList<T> objectListToObservableList(List<T> objectList) {
ObservableList<T> observableList = FXCollections.observableArrayList();
try{
for (T obj :
objectList) {
observableList.add(obj);
}
return observableList;}
catch (NullPointerException e){
throw new NullPointerException();
}
}
}
|
package com.allure.service.framework.security;
import lombok.NonNull;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
/**
* Created by yang_shoulai on 7/20/2017.
*/
public class UserContextAuthenticationToken extends AbstractAuthenticationToken {
@NonNull
private UserContext userContext;
public UserContextAuthenticationToken(UserContext userContext, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.userContext = userContext;
this.setAuthenticated(true);
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getPrincipal() {
return userContext;
}
}
|
package com.gxtc.huchuan.ui.circle.circleInfo;
import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.helper.ImageHelper;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.FileUtil;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.LogUtil;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.commlibrary.utils.WindowUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.MyApplication;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.bean.CircleBean;
import com.gxtc.huchuan.bean.CircleMemberBean;
import com.gxtc.huchuan.bean.UploadFileBean;
import com.gxtc.huchuan.bean.UploadResult;
import com.gxtc.huchuan.bean.event.EventCircleIntro;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.helper.RxTaskHelper;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.LoadHelper;
import com.gxtc.huchuan.http.service.MineApi;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.utils.AndroidBug5497Workaround;
import com.gxtc.huchuan.utils.DialogUtil;
import com.gxtc.huchuan.utils.JumpPermissionManagement;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.FunctionOptions;
import com.luck.picture.lib.model.PictureConfig;
import org.greenrobot.eventbus.Subscribe;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.OnClick;
import cn.edu.zafu.coreprogress.listener.impl.UIProgressListener;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
import top.zibin.luban.Luban;
/**
* 编辑圈子资料
*/
public class CircleEditActivity extends BaseTitleActivity implements View.OnClickListener,
CircleInfoContract.View, PictureConfig.OnSelectResultCallback {
public static final int REQUEST_CODE_CIRCLE_FACE = 10000;
@BindView(R.id.headArea) RelativeLayout layoutHead;
@BindView(R.id.headBackButton) ImageButton btnBack;
@BindView(R.id.headRightButton) Button btnHeadRight;
@BindView(R.id.tv_intro) TextView tvIntro;
@BindView(R.id.headTitle) TextView tvTitle;
@BindView(R.id.edit_name) TextView editName;
@BindView(R.id.img_header_bg) ImageView imgHeaderBg;
@BindView(R.id.img_icon) ImageView imgIcon;
@BindView(R.id.img_camera) ImageView imgCamera;
@BindView(R.id.tv_label_chang_face) TextView tvLabelChangeFace;
@BindView(R.id.rl_chang_face) RelativeLayout rlChangeFace;
private int mGroupID; //圈子Id
private int isMy; //是否是圈主,只有圈主和管理员才能修改资料,只有圈主才能删除圈子,其他成员(包括管理员)都只能退出圈子
private int mMenberType; //成员类型。0:普通用户,1:管理员,2:圈主
private boolean isHead;
private CircleBean bean;
private String mGroupName; //圈子名称
private ArrayList<String> pathList;
private CircleInfoContract.Presenter mPresenter;
private String cover;
private String backgCover;
private HashMap<String, Object> map;
private android.support.v7.app.AlertDialog mAlertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circle_edit);
AndroidBug5497Workaround.assistActivity(this);
}
@Override
public void initView() {
bean = (CircleBean) getIntent().getSerializableExtra(Constant.INTENT_DATA);
if (bean != null) {
mGroupID = bean.getId();
mGroupName = bean.getName();
mMenberType = bean.getMemberType();
isMy = bean.getIsMy();
}
//普通用户 不能编辑圈子资料
if (mMenberType == 0) {
tvTitle.setText(getString(R.string.title_check_circle_info));
tvTitle.setText(getString(R.string.title_circle_info));
btnHeadRight.setVisibility(View.GONE);
tvLabelChangeFace.setVisibility(View.GONE);
tvIntro.setCompoundDrawables(null, null, null, null);
//管理员 可以编辑圈子资料
} else if (mMenberType == 1) {
tvTitle.setText(getString(R.string.title_circle_edit));
btnHeadRight.setVisibility(View.VISIBLE);
btnHeadRight.setTextColor(getResources().getColor(R.color.white));
btnHeadRight.setText("完成");
btnHeadRight.setOnClickListener(this);
rlChangeFace.setOnClickListener(this);
imgHeaderBg.setOnClickListener(this);
tvIntro.setOnClickListener(this);
//圈主 可以编辑圈子资料并删除圈子
} else {
tvTitle.setText(getString(R.string.title_circle_edit));
btnHeadRight.setVisibility(View.VISIBLE);
btnHeadRight.setTextColor(getResources().getColor(R.color.white));
btnHeadRight.setText("完成");
btnHeadRight.setOnClickListener(this);
rlChangeFace.setOnClickListener(this);
imgHeaderBg.setOnClickListener(this);
tvIntro.setOnClickListener(this);
}
setActionBarTopPadding(layoutHead, true);
layoutHead.setBackgroundColor(getResources().getColor(R.color.transparent));
tvTitle.setTextColor(getResources().getColor(R.color.white));
btnBack.setVisibility(View.VISIBLE);
btnBack.setOnClickListener(this);
btnBack.setImageResource(R.drawable.navigation_icon_back_white);
cover = bean.getCover();
imgCamera.setVisibility(View.GONE);
editName.setText(bean.getName());
tvIntro.setText(bean.getContent());
ImageHelper.loadImage(CircleEditActivity.this, imgIcon, bean.getCover());
if(TextUtils.isEmpty(bean.getBackgCover())){
ImageHelper.loadImage(CircleEditActivity.this, imgHeaderBg, bean.getCover());
}else{
backgCover = bean.getBackgCover();
ImageHelper.loadImage(CircleEditActivity.this, imgHeaderBg, bean.getBackgCover());
}
}
@Override
public void initData() {
new CircleInfoPresenter(this);
EventBusUtil.register(this);
map = new HashMap<>();
mSubscriptions = new CompositeSubscription();
//mPresenter.getCircleInfo(UserManager.getInstance().getToken(), mGroupID);
}
@OnClick({R.id.headBackButton, R.id.headRightButton})
@Override
public void onClick(View v) {
WindowUtil.closeInputMethod(this);
switch (v.getId()) {
case R.id.headBackButton:
finish();
break;
//完成
case R.id.headRightButton:
editComplete();
break;
//换圈子头像
case R.id.rl_chang_face:
isHead = true;
chooseImg();
break;
//换圈子背景
case R.id.img_header_bg:
isHead = false;
chooseImg();
break;
//简介
case R.id.tv_intro:
gotoIntro();
break;
}
}
private void editComplete() {
map.put("token", UserManager.getInstance().getToken());
map.put("id", mGroupID);
map.put("groupName", mGroupName);
if (!(TextUtils.isEmpty(cover))) {
map.put("cover", cover);
}
if (!(TextUtils.isEmpty(backgCover))) {
map.put("backgCover", backgCover);
}
if (!(TextUtils.isEmpty(tvIntro.getText().toString()))) {
map.put("content", tvIntro.getText().toString());
}
mPresenter.editCircleInfo(map);
}
//选择照片
private void chooseImg() {
String[] pers = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
performRequestPermissions("此应用需要读取相机和存储权限", pers, REQUEST_CODE_CIRCLE_FACE,
new PermissionsResultListener() {
@Override
public void onPermissionGranted() {
FunctionOptions options =
new FunctionOptions.Builder()
.setType(FunctionConfig.TYPE_IMAGE)
.setSelectMode(FunctionConfig.MODE_SINGLE)
.setImageSpanCount(3)
.setEnableQualityCompress(false) //是否启质量压缩
.setEnablePixelCompress(false) //是否启用像素压缩
.setEnablePreview(true) // 是否打开预览选项
.setShowCamera(true)
.setPreviewVideo(true)
.setIsCrop(true)
.setAspectRatio(1, 1)
.create();
PictureConfig.getInstance().init(options).openPhoto(CircleEditActivity.this, CircleEditActivity.this);
}
@Override
public void onPermissionDenied() {
mAlertDialog = DialogUtil.showDeportDialog(CircleEditActivity.this, false, null, getString(R.string.pre_scan_notice_msg),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v.getId() == R.id.tv_dialog_confirm){
JumpPermissionManagement.GoToSetting(CircleEditActivity.this);
}
mAlertDialog.dismiss();
}
});
}
});
}
private void gotoIntro() {
GotoUtil.goToActivity(this, InputIntroActivity.class, 0, bean);
}
private CompositeSubscription mSubscriptions;
private void uploadingFile(String path){
//将图片进行压缩
final File file = new File(path);
Subscription sub =
Luban.get(MyApplication.getInstance()).load(file) //传人要压缩的图片
.putGear(Luban.THIRD_GEAR) //设定压缩档次,默认三挡
.asObservable()
.subscribeOn(Schedulers.io())
.map(new Func1<File, File>() {
@Override
public File call(File compressFile) {
return FileUtil.getSize(file) > Constant.COMPRESS_VALUE ? compressFile : file;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<File>() {
@Override
public void call(File uploadFile) {
LoadHelper.uploadFile(LoadHelper.UP_TYPE_IMAGE,
new LoadHelper.UploadCallback() {
@Override
public void onUploadSuccess(UploadResult result) {
showUploadingSuccess(result.getUrl());
}
@Override
public void onUploadFailed(String errorCode, String msg) {
ToastUtil.showShort(CircleEditActivity.this, msg);
}
}, null, uploadFile);
}
});
mSubscriptions.add(sub);
}
@Override
public void tokenOverdue() {
GotoUtil.goToActivity(this, LoginAndRegisteActivity.class);
}
@Override
public void showMemberList(List<CircleMemberBean> datas) {}
@Override
public void showRefreshFinish(List<CircleMemberBean> datas) {}
@Override
public void showLoadMore(List<CircleMemberBean> datas) {}
@Override
public void showNoMore() {}
@Override
public void showCompressSuccess(File file) {
mPresenter.uploadingFile(file);
}
@Override
public void showCompressFailure() {
ToastUtil.showShort(this, "压缩图片失败");
}
//上传图片成功
@Override
public void showUploadingSuccess(String url) {
if(isHead){
cover = url;
imgCamera.setVisibility(View.GONE);
ImageHelper.loadImage(CircleEditActivity.this, imgIcon, cover);
}else{
backgCover = url;
ImageHelper.loadImage(CircleEditActivity.this, imgHeaderBg, backgCover);
}
}
@Override
public void showCircleInfo(CircleBean bean) {
}
@Override
public void showEditCircle(Object o) {
ToastUtil.showShort(this, getString(R.string.modify_success));
//延迟400毫秒在弹窗
Subscription showSub = Observable.timer(400, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
mAlertDialog = DialogUtil.showDeportDialog(CircleEditActivity.this, false, null, "修改资料已提交,审核后才更新", new View.OnClickListener() {
@Override
public void onClick(View v) {
mAlertDialog.dismiss();
}
});
}
});
RxTaskHelper.getInstance().addTask(this,showSub);
// EventBusUtil.postStickyEvent(new EventImgBean(cover));
}
//---------------- 在圈子成员管理用到的
@Override
public void removeMember(CircleMemberBean circleMemberBean) {
}
@Override
public void transCircle(CircleMemberBean circleMemberBean) {
}
@Override
public void showChangeMemberTpye(CircleMemberBean circleMemberBean) {
}
//---------------- 在圈子成员管理用到的
@Override
public void setPresenter(CircleInfoContract.Presenter presenter) {
this.mPresenter = presenter;
}
@Override
public void showLoad() {
getBaseLoadingView().showLoading();
}
@Override
public void showLoadFinish() {
getBaseLoadingView().hideLoading();
}
@Override
public void showEmpty() {
}
@Override
public void showReLoad() {
}
@Override
public void showError(String info) {
ToastUtil.showShort(this, info);
}
@Override
public void showNetError() {
ToastUtil.showShort(this, getString(R.string.empty_net_error));
}
//圈子介绍
@Subscribe()
public void onEvent(EventCircleIntro bean) {
bean.setIntro(bean.getIntro());
tvIntro.setText(bean.getIntro());
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.destroy();
EventBusUtil.unregister(this);
RxTaskHelper.getInstance().cancelTask(this);
mAlertDialog = null;
}
@Override
public void onSelectSuccess(List<LocalMedia> resultList) {
}
@Override
public void onSelectSuccess(LocalMedia media) {
uploadingFile(media.getPath());
}
}
|
package model.data.rewardData;
import component.DAO;
public class PayJudgeData{
// Component
private DAO dao;
// Constructor
public PayJudgeData() {this.dao = new DAO("Payjudge", "payjudgeID", new Object[] {null, "", "", ""});}
// Getter & Setter
public String getPayJudge() {return this.dao.getString("payJudge");}
public String getJudgementEvidence() {return this.dao.getString("evidence");}
public String getRelatedLaw() {return this.dao.getString("relatedLaw");}
public void setPayJudge(String payJudge) {this.dao.update("payJudge", payJudge);}
public void setJudgementEvidence(String evidence) {this.dao.update("evidence", evidence);}
public void setRelatedLaw(String relatedLaw) {this.dao.update("relatedLaw", relatedLaw);}
}
|
package com.tsuro.tile.tiletypes;
import com.google.gson.annotations.SerializedName;
import com.tsuro.tile.ITile;
import com.tsuro.tile.Location;
import com.tsuro.tile.Path;
import com.tsuro.tile.TsuroTile;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.NonNull;
/**
* Represents a Tile Index as a Java Object.
*/
@AllArgsConstructor
public class TileIndex implements Comparable<TileIndex> {
@NonNull
public List<List<Location>> edges;
@SerializedName("tile#")
public int tileIndex;
@Override
public int compareTo(@NonNull TileIndex tileIndex) {
return Integer.compare(this.tileIndex, tileIndex.tileIndex);
}
/**
* Turns an instance of a {@link TileIndex} into a {@link ITile}
*
* @return a Tile with the edges in edges
*/
ITile turnToTile() {
return new TsuroTile(edges.stream().map(a -> new Path(a.get(0), a.get(1))).collect(
Collectors.toList()));
}
}
|
package com.atguigu.java4;
import org.junit.Test;
/*
抛 :throw
格式 : throw 异常类的对象;
*/
public class ThrowTest {
@Test
public void test(){
//编译时异常 : 必须处理
try {
setAge(-5);
} catch (MyException e) {
e.printStackTrace();
}
System.out.println("程序结束");
}
/**
* 年纪必须大于0
* @param age
* @throws Exception
*/
public void setAge(int age) throws MyException{
if(age > 0){
//直接赋值
}else{
//创建的是运行时类的异常对象 (调用者可以不用处理该异常,但是发生异常后直接会终止程序的运行)
// throw new NullPointerException("年纪不能小于0");
//创建的是编译时异常(一般情况下都是编译时异常) : 必须得处理异常
//(向上抛该异常,那调用者调用该方法时就必须处理这个异常(相当于通知了调用者可能会有异常发生))
throw new MyException("不能小于0");
}
}
}
|
//package com.socialteinc.socialate;
//
//import android.support.annotation.NonNull;
//import android.support.test.espresso.contrib.RecyclerViewActions;
//import android.support.test.rule.ActivityTestRule;
//import android.util.Log;
//import com.google.android.gms.tasks.OnCompleteListener;
//import com.google.android.gms.tasks.Task;
//import com.google.firebase.FirebaseApp;
//import com.google.firebase.auth.AuthResult;
//import com.google.firebase.auth.FirebaseAuth;
//import com.google.firebase.database.DatabaseReference;
//import com.google.firebase.database.FirebaseDatabase;
//import org.junit.Before;
//import org.junit.Rule;
//import org.junit.Test;
//
//import static android.support.test.espresso.Espresso.onView;
//import static android.support.test.espresso.action.ViewActions.click;
//import static android.support.test.espresso.assertion.ViewAssertions.matches;
//import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
//import static android.support.test.espresso.matcher.ViewMatchers.withId;
//
//public class ViewEntertainmentTest1 {
//
// private FirebaseAuth mAuth;
//
// @Rule
// public ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class);
//
// @Before
// public void login(){
// FirebaseApp.initializeApp(rule.getActivity());
// mAuth = FirebaseAuth.getInstance();
//
// mAuth.signInWithEmailAndPassword("musa@gmail.com", "password")
// .addOnCompleteListener(rule.getActivity(), new OnCompleteListener<AuthResult>() {
// @Override
// public void onComplete(@NonNull Task<AuthResult> task) {
// if (task.isSuccessful()) {
// // Sign in success, update UI with the signed-in user's information
// } else {
// // If sign in fails, display a message to the user.
// Log.w("login activity", "signInWithEmail:failure", task.getException());
//
// }
// }
// });
// }
//
// @Test
// public void recyclerViewTest() throws InterruptedException{
// login();
// Thread.sleep(4000);
// onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.scrollToPosition(3));
// //onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.scrollToHolder(...));
// }
//
// @Test
// public void isDisplayedTest() throws InterruptedException {
// Thread.sleep(15000);
// onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition(3, click()));
// Thread.sleep(3000);
// onView(withId(R.id.ViewAddedAreaOwnerText)).check(matches(isDisplayed()));
// onView(withId(R.id.ViewAddedAreaAddressText)).check(matches(isDisplayed()));
// onView(withId(R.id.ViewAddedAreaDescText)).check(matches(isDisplayed()));
// onView(withId(R.id.ViewAddedAreaImageView)).check(matches(isDisplayed()));
// }
//
//// @Test
//// public void commentsTest() throws InterruptedException{
//// Thread.sleep(9000);
//// onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition(3,click()));
////
//// Thread.sleep(3000);
//// onView(withId(R.id.displayNameTextView)).check(matches(isDisplayed()));
//// onView(withId(R.id.describeEditText)).check(matches(isDisplayed()));
//// onView(withId(R.id.fullNameTextView)).check(matches(isDisplayed()));
//// onView(withId(R.id.imageView2)).check(matches(isDisplayed()));
//// }
//
// @Test
// public void likeTest() throws InterruptedException {
// Thread.sleep(15000);
// onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition(3,click()));
// onView(withId(R.id.likeFloatingActionButton)).perform(click());
// Thread.sleep(4000);
// }
//
// @Test
// public void viewAuthorTest() throws InterruptedException {
// Thread.sleep(15000);
// onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition(3,click()));
//
// Thread.sleep(4000);
// }
//
// @Test
// public void NavigationTest() throws InterruptedException{
// Thread.sleep(15000);
// onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition(0,click()));
// onView(withId(R.id.navigationImageView)).check(matches(isDisplayed()));
// onView(withId(R.id.navigationImageView)).perform(click());
//
// Thread.sleep(9000);
// //onView(withId(R.id.comment_recyclerView)).perform(RecyclerViewActions.scrollToPosition(2));
//// onView(withId(R.id.commentorNameTextView)).check(matches(isDisplayed()));
//// onView(withId(R.id.commentorProfileImageView)).check(matches(isDisplayed()));
//// onView(withId(R.id.commentMultiAutoCompleteTextView)).check(matches(isDisplayed()));
//// onView(withId(R.id.dateTextView)).check(matches(isDisplayed()));
//// onView(withId(R.id.likeTextView)).check(matches(isDisplayed()));
//// onView(withId(R.id.likeCommentCounterTextView)).check(matches(isDisplayed()));
//// Thread.sleep(4000);
// }
//
//}
|
package lde;
/**
*
* @author Iago Nogueira <sguergachi at gmail.com>
* @param <E>
*/
public interface ILde<E> {
public void add(E item, int pos);
public void add( E array[] );
public void addInicio(E item);
public void addFim(E item);
public E remove(int pos);
public E removeInicio();
public E removeFim();
public boolean busca(E item);
public int tamanho();
public boolean isEmpyt();
public void print();
}
|
package com.codigo.smartstore.webapi.domain;
public interface IQualifier {
/**
* Odczytuje wartość kodu
*
* @return
*/
public String getCode();
/**
* Odczytuje opis wartości kodu
*
* @return
*/
public String getDescription();
}
|
package airhockeygame;
import gameassets.Globals;
import maingui.StartScreen;
import javax.swing.SwingUtilities;
public class AirHockeyGame {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Start the game
SwingUtilities.invokeLater(() -> Globals.startScreen.setVisible(true));
// Show current active threads
System.err.println("Threads Running: " + Thread.activeCount());
}
}
|
//Java default API controls
import javafx.collections.ObservableList;
import java.util.InputMismatchException;
import javafx.scene.layout.GridPane;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
public class Board extends GridPane{
public static final int SquareSize = 65;
public static final int COLUMNS = 8;
public static final int ROWS = 8;
public static final int SIZE = COLUMNS * ROWS;
private Coordinate coordinate;
private BoardSquare square;
private Chessman chessman;
public Board() throws InputMismatchException{
super();
setExceptionWay();
//Create every 64 board spots
//@Params treeMap(Key, Value) --Key = Integer -> Board coordinate position
// --Value = BoardSquare -> Squart Coordinated
//@Params BoardSquare(Coordinate, Chessman)
//@Params Coordinate(i) --i = board coordinate position "(Matrix)Vector"
for(int i = 0; i < SIZE; i ++){
chessman = Game.UnboxChessmen(i);
coordinate = new Coordinate(i);
square = new BoardSquare(coordinate, chessman);
square.setOnAction(e -> squareCatch(e));
square.setMinSize(SquareSize, SquareSize);
square.SquareTransparent();
square.setImg();
super.add(square, coordinate.getColumn(), coordinate.getRow());
}
//Set grid settings
coordinate = new Coordinate(0);
//setGridLinesVisible(true);
setAlignment(Pos.CENTER);
setPadding(new Insets(1));
setHgap(1.3);
setVgap(1.3);
}
//Catch onAction event
public void squareCatch(ActionEvent e) throws InputMismatchException{
BoardSquare square = (BoardSquare) e.getSource();
if(Game.getProgramCounter() == 0 || Game.getProgramCounter() == 2)
square.SquareSelect();
Game.setOnBoard(onBoard());
Game.setPointer(square);
}
//Get all BoardSquares occupied
private GridPane onBoard(){
GridPane grid = new GridPane();
//Copy containing grid on super class
ObservableList<Node> childrens = super.getChildren();
//Iterate grid finding positions and which is filled
for (Node node : childrens){
if(node instanceof BoardSquare){
BoardSquare osquare = (BoardSquare) node;
square = new BoardSquare(osquare.getCoordinate(), osquare.getChessman());
grid.add(square, square.getCoordinate().getColumn(), square.getCoordinate().getRow());
}
}
//Set grid settings
//grid.setGridLinesVisible(true);
grid.setAlignment(Pos.CENTER);
grid.setPadding(new Insets(1));
grid.setHgap(1.3);
grid.setVgap(1.3);
return grid;
}
//Set where (Screen-> Game)Exception should be treated
public static void setExceptionWay(){
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
}
} |
package me.ewriter.art_chapter2.manager;
import android.os.IBinder;
import me.ewriter.art_chapter2.aidl.IBookManager;
/**
* Created by Zubin on 2016/6/22.
*/
public class BookManager {
private IBookManager mBookManager;
private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
if (mBookManager == null)
return;;
mBookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
mBookManager = null;
// TODO: 2016/6/22 这里重新绑定远程Service
}
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.