text
stringlengths 10
2.72M
|
|---|
package day15methodcreation;
import java.util.Scanner;
public class MethodCreation03 {
public static void main(String[] args) {
// bsit hesap makinasi
// Kullanicidan yapacagi islemi islem ssembolu ile secmesini saglayan
//Kulllancidan iki sayi girmesini isteyelim
//giriken iki sayi ve secilen isleme gore dogru sonucu ekran yaz
Scanner scan = new Scanner(System.in);
System.out.println("+,-,*,: islemlerinden birini seciniz");
char islem = scan.next().charAt(0);
System.out.println("islem yapmak icin ikki sayi giriniz");
double num1 = scan.nextDouble();
double num2 = scan.nextDouble();
hesapMakinasi(islem,num1,num2);
scan.close();
}
public static void hesapMakinasi(char islem, double num1, double num2) {
switch(islem) {
case '+':
System.out.println(num1 + "+" + num2 + "=" +(num1+num2));
break;
case 'x':
System.out.println(num1 + "x" + num2 + "=" +(num1*num2));
break;
case '-':
System.out.println(num1 + "-" + num2 + "=" +(num1-num2));
break;
case ':':
System.out.println(num1 + ":" + num2 + "=" +(num1/num2));
break;
default:
System.out.println("+,-,x,: disinda bir islem secmeyiniz");
}
}
}
|
package org.kt3k.straw.plugin;
import org.kt3k.straw.StrawPlugin;
public class OptionsMenuPlugin extends StrawPlugin {
@Override
public String getName() {
return "optionsMenu";
}
}
|
package com.diozero.internal.provider.builtin.i2c;
/*-
* #%L
* Organisation: diozero
* Project: diozero - Core
* Filename: I2cRetryTest.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class I2cRetryTest {
private static final int OK = 0;
private static final int ERROR = -1;
private static final int EAGAIN = -11;
private static final int ETIMEDOUT = -110;
private static final int EREMOTEIO = -121;
private int numRetries = 3;
@Test
public void testOk() {
int rc = EAGAIN;
int i;
for (i = 0; i < numRetries && (rc == EAGAIN || rc == ETIMEDOUT || rc == EREMOTEIO); i++) {
rc = OK;
}
Assertions.assertEquals(1, i);
Assertions.assertEquals(OK, rc);
}
@Test
public void testError() {
int rc = EAGAIN;
int i;
for (i = 0; i < numRetries && (rc == EAGAIN || rc == ETIMEDOUT || rc == EREMOTEIO); i++) {
rc = ERROR;
}
Assertions.assertEquals(1, i);
Assertions.assertEquals(ERROR, rc);
}
@Test
public void testRetryThenOk() {
int rc = EAGAIN;
int i;
for (i = 0; i < numRetries && (rc == EAGAIN || rc == ETIMEDOUT || rc == EREMOTEIO); i++) {
rc = nativeOperation(i, true);
switch (i) {
case 0:
Assertions.assertEquals(EAGAIN, rc);
break;
case 1:
Assertions.assertEquals(ETIMEDOUT, rc);
break;
default:
Assertions.assertEquals(OK, rc);
}
}
Assertions.assertEquals(numRetries, i);
Assertions.assertEquals(OK, rc);
}
@Test
public void testRetryExceeded() {
int rc = EAGAIN;
int i;
for (i = 0; i < numRetries && (rc == EAGAIN || rc == ETIMEDOUT || rc == EREMOTEIO); i++) {
rc = EAGAIN;
}
Assertions.assertEquals(numRetries, i);
Assertions.assertEquals(EAGAIN, rc);
}
@Test
public void testRetryThenError() {
int rc = EAGAIN;
int i;
for (i = 0; i < numRetries && (rc == EAGAIN || rc == ETIMEDOUT || rc == EREMOTEIO); i++) {
rc = nativeOperation(i, false);
switch (i) {
case 0:
Assertions.assertEquals(EAGAIN, rc);
break;
case 1:
Assertions.assertEquals(ETIMEDOUT, rc);
break;
default:
Assertions.assertEquals(ERROR, rc);
}
}
Assertions.assertEquals(numRetries, i);
Assertions.assertEquals(ERROR, rc);
}
private static int nativeOperation(int retryNum, boolean result) {
switch (retryNum) {
case 0:
return EAGAIN;
case 1:
return ETIMEDOUT;
default:
return result ? OK : ERROR;
}
}
}
|
/*
* Copyright 2012 Kulikov Dmitriy
* Copyright 2017 Nikita Shakarun
*
* 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 javax.microedition.util;
/**
* Элемент связного списка.
*
* @param <E> что он содержит
*/
public class LinkedEntry<E> {
private LinkedEntry<E> prev;
private LinkedEntry<E> next;
private E element;
/**
* Присвоить элементу значение.
*
* @param element новое значение
*/
public void setElement(E element) {
this.element = element;
}
/**
* @return текущее значение элемента
*/
public E getElement() {
return element;
}
/**
* @return элемент, предшествующий данному; или null, если такого элемента нет
*/
public LinkedEntry<E> prevEntry() {
return prev;
}
/**
* @return элемент, следующий за данным; null, если такого элемента нет
*/
public LinkedEntry<E> nextEntry() {
return next;
}
/**
* Изъять этот элемент из списка.
* Смежные элементы при этом соединяются между собой.
*/
public void remove() {
if (prev != null) {
prev.next = next; // следующий за предыдущим = следующий за этим
}
if (next != null) {
next.prev = prev; // предшествующий следующему = предшествующий этому
}
prev = null;
next = null;
}
/**
* Восстановить двунаправленность связей для этого элемента.
* <p>
* То есть, если перед нами кто-то есть, то мы стоим за ним;
* если кто-то есть после нас, то мы стоим перед ним.
*/
private void updateLinks() {
if (prev != null) {
prev.next = this;
}
if (next != null) {
next.prev = this;
}
}
/**
* Вставить этот элемент перед указанным.
* Предполагается, что указанный элемент входит в состав некоторого списка.
*
* @param entry
*/
public void insertBefore(LinkedEntry<E> entry) {
remove(); // элемент не можеть быть одновременно в двух местах в списке
prev = entry.prev; // предыдущий для указанного - теперь наш предыдущий
next = entry; // сам указанный - теперь наш следующий
updateLinks(); // доносим эти изменения до наших новых соседей
}
/**
* Вставить этот элемент после указанного.
* Предполагается, что указанный элемент входит в состав некоторого списка.
*
* @param entry
*/
public void insertAfter(LinkedEntry<E> entry) {
remove(); // элемент не можеть быть одновременно в двух местах в списке
prev = entry; // сам указанный - теперь наш предыдущий
next = entry.next; // следующий для указанного - теперь наш следующий
updateLinks(); // доносим эти изменения до наших новых соседей
}
}
|
package com.tencent.mm.g.a;
import android.content.Context;
import android.os.Bundle;
import com.tencent.mm.protocal.c.wl;
import com.tencent.mm.protocal.c.wn;
import java.util.ArrayList;
public final class kp$a {
public String bUR;
public String bUS;
public boolean bUT = false;
public Bundle bUU;
public int bUV = 0;
public int bUW = 0;
public ArrayList bUX;
public boolean bUY = true;
public wn bUZ;
public Context context;
public wl field_favProto;
public long field_localId = 0;
public String path;
public int type = 0;
}
|
//Exercise 4-F.
public class MathUtil
{
public static void main(String[] args)
{
printDifference(-4, 5);
printAbsValue(-45);
printDifference(1000, 4000000);
}
private static void printDifference(int a, int b)
{
int difference = a - b;
System.out.println("The values of a and b are: " + a + " and " + b);
System.out.println("This difference between a and b is: " + difference);
System.out.println();
printAbsValue(difference);
}
private static void printAbsValue(int c)
{
int absoluteValue = Math.abs(c);
System.out.println("The value of c is: " + c);
System.out.println("The absolute value of c is: " + absoluteValue);
System.out.println();
}
}
|
package com.anibal.educational.rest_service.comps.service.impl;
import java.io.File;
import java.io.InputStream;
import com.anibal.educational.rest_service.comps.service.FileManagingException;
import com.anibal.educational.rest_service.comps.service.FileManagingService;
import com.anibal.educational.rest_service.comps.service.TicketUserAuteticationException;
import com.anibal.educational.rest_service.comps.service.TicketUserException;
import com.anibal.educational.rest_service.comps.service.TicketUserService;
import com.anibal.educational.rest_service.comps.service.mail.MailContent;
import com.anibal.educational.rest_service.comps.service.mail.MailService;
import com.anibal.educational.rest_service.comps.service.mail.MailServiceImpl;
import com.anibal.educational.rest_service.comps.util.RestServiceConstant;
import com.anibal.educational.rest_service.comps.util.RestServiceUtil;
import com.anibal.educational.rest_service.domain.TicketUser;
import com.odhoman.api.utilities.config.AbstractConfig;
import com.odhoman.api.utilities.dao.AbstractAbmDAO;
import com.odhoman.api.utilities.dao.DAOException;
import com.odhoman.api.utilities.dao.ItemNotFoundException;
public class TicketUserServiceImpl extends AbstractService implements TicketUserService {
private AbstractAbmDAO<TicketUser, TicketUser> dao;
private FileManagingService fileService;
public TicketUserServiceImpl(AbstractAbmDAO<TicketUser, TicketUser> dao, FileManagingService fileService) {
super();
this.dao = dao;
this.fileService = fileService;
}
public TicketUserServiceImpl(AbstractAbmDAO<TicketUser, TicketUser> dao, FileManagingService fileService, AbstractConfig config) {
super(config);
this.dao = dao;
this.fileService = fileService;
}
public TicketUser getUser(Long userId) throws TicketUserException {
TicketUser user = null;
logger.debug("TicketUserServiceImplImpl - getUser: iniciando");
TicketUser filter = new TicketUser();
filter.setUserId(userId);
try {
user = dao.getItem(filter);
} catch (DAOException e) {
logger.error("TicketUserServiceImplImpl - getUser: ocurrio un error al querer obtener el usuario", e);
throw new TicketUserException(e);
}
logger.debug("TicketUserServiceImplImpl - getUser: finalizando");
user.setUserPassword(null);
return user;
}
public void updateUser(Long id, TicketUser user) throws TicketUserException {
logger.debug("TicketUserServiceImplImpl - updateUser: iniciando");
TicketUser filter = new TicketUser();
filter.setUserId(id);
try {
dao.changeItem(filter, user);
} catch (DAOException e) {
throw new TicketUserException(e);
}
logger.debug("TicketUserServiceImplImpl - updateUser: finalizando");
}
public void deleteUser(Long userId) throws TicketUserException {
logger.debug("TicketUserServiceImplImpl - deleteUser: iniciando");
TicketUser filter = new TicketUser();
filter.setUserId(userId);
try {
dao.deleteItem(filter);
} catch (DAOException e) {
throw new TicketUserException(e);
}
logger.debug("TicketUserServiceImplImpl - deleteUser: finalizando");
}
public TicketUser createUser(TicketUser user) throws TicketUserException {
logger.debug("TicketUserServiceImplImpl - createUser: iniciando");
TicketUser filter = new TicketUser();
filter.setUserId(user.getUserId());
try {
dao.addItem(user);
} catch (DAOException e) {
throw new TicketUserException(e);
}
logger.debug("TicketUserServiceImplImpl - createUser: finalizando");
return user;
}
public void createUserImage(Long userId, InputStream inputStream, String fileName) throws TicketUserException {
logger.debug("TicketUserServiceImplImpl - createUserImage: iniciando");
TicketUser user = new TicketUser();
String folderPath = config.getProperty(RestServiceConstant.APP_FILE_SYSTEM_USER_FOLDER_DIR);
logger.debug("TicketUserServiceImplImpl - se guarda la imagen " + fileName + " del usuario id " + userId);
try {
fileService.handleUpload(inputStream, folderPath, fileName);
} catch (FileManagingException e) {
logger.error("TicketUserServiceImplImpl - no se pudo guarda la imagen " + fileName + " del usuario id "
+ userId);
throw new TicketUserException(e);
}
logger.debug("TicketUserServiceImplImpl - se actualizan los datos del usuario");
user.setImageId(userId);
user.setPathImage(folderPath + fileName);
updateUser(userId, user);
logger.debug("TicketUserServiceImplImpl - createUserImage: finalizando");
}
public File getUserImage(Long userId) throws TicketUserException {
logger.debug("TicketUserServiceImplImpl - getUserImage: iniciando");
File file = null;
TicketUser user = getUser(userId);
try {
file = fileService.handleDownload(user.getPathImage());
if (file == null || !file.exists()) {
logger.error("No existe la imagen solicitada en el path " + user.getPathImage());
throw new TicketUserException("No existe la imagen solicitada");
}
} catch (FileManagingException e) {
throw new TicketUserException("No se pudo obtener la imagen del usuario");
}
logger.debug("TicketUserServiceImplImpl - getUserImage: finalizando");
return file;
}
public TicketUser performAuthentication(String userName, String pass) throws TicketUserException {
TicketUser user = null;
if(userName==null || userName.isEmpty() || pass==null || pass.isEmpty()){
logger.warn("TicketUserServiceImplImpl - performAuthentication: Credenciales incorrectas");
throw new TicketUserAuteticationException("Credenciales incompletas");
}
logger.debug("TicketUserServiceImplImpl - performAuthentication: iniciando");
TicketUser filter = new TicketUser();
filter.setUserName(userName);
try {
user = dao.getItem(filter);
} catch (ItemNotFoundException e) {
logger.warn("TicketUserServiceImplImpl - performAuthentication: Credenciales incorrectas",e);
throw new TicketUserAuteticationException("Credenciales incorrectas");
} catch (DAOException e) {
logger.error("TicketUserServiceImplImpl - performAuthentication: ocurrio un error al realizar la autenticacion", e);
throw new TicketUserException(e);
}
String userPass = user.getUserPassword();
if(userPass==null || userPass.isEmpty() || !userPass.equals(pass)){
logger.warn("TicketUserServiceImplImpl - performAuthentication: Credenciales incorrectas");
throw new TicketUserAuteticationException("Credenciales incorrectas");
}
logger.debug("TicketUserServiceImplImpl - performAuthentication: finalizando");
user.setUserPassword(null);
return user;
}
public void performForgotPass(String userName) throws TicketUserException {
TicketUser user;
MailContent mc;
TicketUser filter = new TicketUser();
filter.setUserName(userName);
try {
user = dao.getItem(filter);
} catch (ItemNotFoundException e) {
logger.warn("TicketUserServiceImplImpl - performForgotPass: No existe el usuario "+userName,e);
throw new TicketUserAuteticationException("No existe el usuario "+userName);
} catch (DAOException e) {
logger.error("TicketUserServiceImplImpl - performForgotPass: ocurrio un error al querer buscar el usuario "+userName, e);
throw new TicketUserException(e);
}
mc = new MailContent(
config.getProperty(RestServiceConstant.APP_EMAIL_MESSAGE_SUBJECT),
config.getProperty(RestServiceConstant.APP_EMAIL_MESSAGE_BODY) + user.getUserPassword(),
user.getUserEmail(), config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_FROM));
MailService ms = new MailServiceImpl();
try {
ms.sendMail(mc, RestServiceUtil.createConfiguratorSmtpMailing(config));
} catch (Exception e) {
throw new TicketUserException(e);
}
}
}
|
package fall2018.csc2017.matchingcards;
import android.util.Log;
import java.io.Serializable;
import java.lang.reflect.Field;
import fall2018.csc2017.R;
import fall2018.csc2017.common.Token;
/**
* A Card in a Matching Cards game.
*/
public class Card extends Token implements Serializable {
/**
* This Cards unique id.
*/
private int id;
/**
* Whether or not this Card is face down.
*/
private boolean faceDown;
/**
* Whether or not this Card has been matched during a Matching Cards game.
*/
private boolean matched;
/**
* A Card with a background id. Sets each new Card to be facing down and unmatched.
* Sets the 'back' of the Cards to all be the same.
*
* @param backgroundId the background id of the Card to create
*/
Card(int backgroundId) {
super(backgroundId + 1);
this.id = backgroundId + 1;
this.faceDown = true;
this.matched = false;
this.background = R.drawable.card_0;
}
/**
* Return the id of this Card.
*
* @return the integer which belongs to this Card
*/
public int getId() {
return id;
}
/**
* Returns whether or not this Card is face up or face down.
*
* @return Whether or not this Card is faceDown
*/
boolean isFaceDown() {
return faceDown;
}
/**
* Set this Card to be face up, or face down, depending on its current state.
* Changes the image resource to be displayed on this Card.
*/
void flip() {
this.faceDown = !this.faceDown;
String uri = "card_" + this.id;
try {
Class res = R.drawable.class;
Field field = res.getField(uri);
background = faceDown ? R.drawable.card_0 : field.getInt(null);
} catch (IllegalAccessException e) {
Log.e("DrawableAccess", "Failed to get resource by id", e);
} catch (NoSuchFieldException e) {
Log.e("DrawableAccess", "No such image", e);
}
}
/**
* Return whether or not this Card has been matched with another.
*
* @return If this Card has been matched
*/
boolean isMatched() {
return matched;
}
/**
* Set this Cards matched status to be true.
*/
void setMatched() {
this.matched = true;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Card)) {
return false;
}
Card obj = (Card) o;
return obj.id == this.id;
}
}
|
package edu.utexas.cs345.jdblisp;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* SpecialFormEntry
* @author Jonathan Bernard (jdbernard@gmail.com)
* Enhanced by Carine Iskander (carine_iskander@mail.utexas.edu) & Pia Chakrabarti (piachakra@mail.utexas.edu)
*/
public abstract class SpecialFormEntry extends FormEntry {
boolean inletd = false;
protected LISPRuntime environment;
public SpecialFormEntry(Symbol name, LISPRuntime environment,
HelpTopic helpinfo) {
super(name, helpinfo);
this.environment = environment;
}
public abstract SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException;
@Override
public String display(String offset) {
return offset + "Special Form Entry: " + symbol.toString();
}
@Override
public String toString() {
return "<SPECIAL-FORM (" + symbol.toString() + ") >";
}
public boolean setLetD(boolean l)
{
inletd = l;
return inletd;
}
public boolean getLetD()
{
return inletd;
}
static final Symbol LTE = new Symbol("<=");
static final Symbol LT = new Symbol("<");
static final Symbol NUMEQ = new Symbol("=");
static final Symbol NUMNOTEQ = new Symbol("/=");
static final Symbol GT = new Symbol(">");
static final Symbol GTE = new Symbol(">=");
static final Symbol DIV = new Symbol("/");
static final Symbol DIF = new Symbol("-");
static final Symbol MUL = new Symbol("*");
static final Symbol SUM = new Symbol("+");
static final Symbol QUESTION = new Symbol("NULL?");
static final Symbol ISSYMBOL = new Symbol("SYMBOL?");
static final Symbol ISATOM = new Symbol("ATOM?");
static final Symbol ISNUM = new Symbol("NUM?");
static final Symbol ISLIST = new Symbol("LIST?");
static final Symbol CAR = new Symbol("CAR");
static final Symbol CADR = new Symbol("CADR");
static final Symbol LAST = new Symbol("LAST");
static final Symbol CDR = new Symbol("CDR");
static final Symbol EQUALS = new Symbol("EQUALS");
static final Symbol CONS = new Symbol("CONS");
static final Symbol DEFUN = new Symbol("DEFUN");
static final Symbol DEFPARAMETER = new Symbol("DEFPARAMETER");
static final Symbol DEFVAR = new Symbol("DEFVAR");
static final Symbol ENABLEDEBUGAST = new Symbol("ENABLE-DEBUG-AST");
static final Symbol FUNCTION = new Symbol("FUNCTION");
static final Symbol FUNCALL = new Symbol("FUNCALL");
static final Symbol GETF = new Symbol("GETF");
static final Symbol HELP = new Symbol("HELP");
static final Symbol IF = new Symbol("IF");
static final Symbol LABELS = new Symbol("LABELS");
static final Symbol LAMBDA = new Symbol("LAMBDA");
static final Symbol LET = new Symbol("LET");
static final Symbol LETD = new Symbol("LETD");
static final Symbol LET_STAR = new Symbol("LET*");
static final Symbol LETREC = new Symbol("LETREC");
static final Symbol LIST = new Symbol("LIST");
static final Symbol MOD = new Symbol("MOD");
static final Symbol QUOTE = new Symbol("QUOTE");
static final Symbol PROGN = new Symbol("PROGN");
static final Symbol REM = new Symbol("REM");
static final Symbol SETQ = new Symbol("SETQ");
static final Symbol TRACE = new Symbol("TRACE");
static final Symbol QUIT = new Symbol("QUIT");
// ------------------------
// SPECIAL FORMS DEFINITION
// ------------------------
// JDB-Lisp includes on-line help for all of its special forms. See the
// help strings for documentation of the individual special forms.
/**
* TODO
*/
public static void defineSpecialForms(LISPRuntime environment) {
// ---
// LTE
// ---
final SpecialFormEntry LTE = new SpecialFormEntry(
SpecialFormEntry.LTE, environment,
new FormHelpTopic("<=", "Less than or equal to",
"(<= <number>*) => <result>",
"The value of <= is true if the numbers are in monotonically "
+ "nondecreasing order; otherwise it is false.",
"number", "a real",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
Num current;
Num next;
// System.out.println("1");
// check that there is at least one argument
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument required.");
// get first number
current = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// advance to next argument
arguments = arguments.cdr;
while(arguments != null) {
// get next number
next = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// current > next, return false
if (current.compareTo(next) > 0) return SExp.NIL;
// next becomes current
current = next;
// advance to next argument
arguments = arguments.cdr;
}
// all are nondecreasing, return true
return SExp.T;
}
};
// --
// LT
// --
final SpecialFormEntry LT = new SpecialFormEntry(
SpecialFormEntry.LT, environment,
new FormHelpTopic("<", "Less than",
"(< <number>*) => <result>",
"The value of < is true if the numbers are in monotonically "
+ "increasing order; otherwise it is false.",
"number", "a real",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
Num current;
Num next;
// System.out.println("2");
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
// get first number
current = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// advance to next argument
arguments = arguments.cdr;
while(arguments != null) {
// get next number
next = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// current >= next, return false
if (current.compareTo(next) >= 0) return SExp.NIL;
// next becomes current
current = next;
// advance to next argument
arguments = arguments.cdr;
}
// all are increasing, return true
return SExp.T;
}
};
// ---------
// NUMEQ (=)
// ---------
final SpecialFormEntry NUMEQ = new SpecialFormEntry(
SpecialFormEntry.NUMEQ, environment,
new FormHelpTopic("=", "Equal to",
"(= <number>*) => <result>",
"The value of = is true if all numbers are the same in value.",
"number", "a number",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
Num current;
Num next;
// System.out.println("3");
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
// get first number
current = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// advance to next argument
arguments = arguments.cdr;
while(arguments != null) {
// get next number
next = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// current != next, return false
if (current.compareTo(next) != 0) return SExp.NIL;
// next becomes current
current = next;
// advance to next argument
arguments = arguments.cdr;
}
// all are equal, return true
return SExp.T;
}
};
// -------------
// NUMNOTEQ (/=)
// -------------
final SpecialFormEntry NUMNOTEQ = new SpecialFormEntry(
SpecialFormEntry.NUMNOTEQ, environment,
new FormHelpTopic("/=", "Not equal to",
"(/= <number>*) => <result>",
"The value of /= is true if no two numbers are the same in value.",
"number", "a number",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
Num current;
Num next;
// System.out.println("4");
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
// get first number
current = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// advance to next argument
arguments = arguments.cdr;
while(arguments != null) {
// get next number
next = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// current == next, return false
if (current.compareTo(next) == 0) return SExp.NIL;
// next becomes current
current = next;
// advance to next argument
arguments = arguments.cdr;
}
// all are non-equal, return true
return SExp.T;
}
};
// --
// GT
// --
final SpecialFormEntry GT = new SpecialFormEntry(
SpecialFormEntry.GT, environment,
new FormHelpTopic(">", "Greater than",
"(> <number>*) => <result>",
"The value of > is true if the numbers are in monotonically "
+ "decreasing order; otherwise it is false.",
"number", "a number",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
Num current;
Num next;
// System.out.println("5");
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
// get first number
current = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// advance to next argument
arguments = arguments.cdr;
while(arguments != null) {
// get next number
next = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// current <= next, return false
if (current.compareTo(next) <= 0) return SExp.NIL;
// next becomes current
current = next;
// advance to next argument
arguments = arguments.cdr;
}
// all are decreasing, return true
return SExp.T;
}
};
// ---
// GTE
// ---
final SpecialFormEntry GTE = new SpecialFormEntry(
SpecialFormEntry.GTE, environment,
new FormHelpTopic(">=", "Greater than or equal to",
"(>= <number>*) => <result>",
"The value of > is true if the numbers are in monotonically "
+ "non-increasing order; otherwise it is false.",
"number", "a number",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
Num current;
Num next;
// System.out.println("6");
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
// get first number
current = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// advance to next argument
arguments = arguments.cdr;
while(arguments != null) {
// get next number
next = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
// current < next, return false
if (current.compareTo(next) < 0) return SExp.NIL;
// next becomes current
current = next;
// advance to next argument
arguments = arguments.cdr;
}
// all are non-increasing, return true
return SExp.T;
}
};
// ---
// DIV
// fixed by Pia Chakrabarti & Carine Iskander
// ---
final SpecialFormEntry DIV = new SpecialFormEntry(
SpecialFormEntry.DIV, environment,
new FormHelpTopic("/", "Divide several expressions.",
"(- divisor) | (- dividend <divisor_1> [... <divisor_n>])",
"Perform division. If there is only one argument passed "
+ "then result = 1/ arg. If multiple arguments are passed"
+ " then result = arg_1 / arg_2 / ... / args_n, computed "
+ "from left to right. In general, expressions are "
+ "evaluated before being bound to function parameters. "
+ "The expressions passed to / must evaluate to numbers.",
"dividend", "In the case of multiple arguments to /, this is "
+ "the number which is diveded.",
"divisor_1 ... divisor_n", "Divisors are the numbers dividing "
+ "the dividend and may be any expression that evaluates "
+ "to a number."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
Num dividend = new Num("1");
Num firstArg;
Num answer = new Num("1");;
// System.out.println("7");
// System.out.println("arguments " + arguments);
// System.out.println("symbol table" + symbolTable.toString());
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
ArrayList<Num> argarray = new ArrayList<Num>();
do{
argarray.add(TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable)));
arguments = arguments.cdr;
}while(arguments != null);
if(argarray.size() == 1)
answer = dividend.divideBy(argarray.get(0));
// System.out.println("answer when dividing by 1" + answer);
if(argarray.size() == 2){
dividend = argarray.get(0);
answer = dividend.divideBy(argarray.get(1));}
// System.out.println("answer" + answer);
if(argarray.size() > 2){
int numdivs = argarray.size() -1 ;
while(numdivs > 0)
{
dividend = argarray.get(0);
answer = dividend.divideBy(argarray.get(1));
argarray.remove(1);
argarray.set(0, answer);
numdivs--;
}
}
return answer;
}
};
// ---
// DIF
// ---
final SpecialFormEntry DIF = new SpecialFormEntry(
SpecialFormEntry.DIF, environment,
new FormHelpTopic("-", "Subtract several expressions.",
"(- subtrahend) | (- <minuend> <subtrahend_1> [... <subtrahend_n>])",
"Perform a subtraction. If there is only one argument passed "
+ "then result = 0 - arg. If multiple arguments are passed"
+ " then result = arg_1 - arg_2 - ... - args_n. In "
+ "general, expressions are evaluated before being bound "
+ " to function parameters. The expressions passed to - "
+ "must evaluate to numbers.",
"minuend", "In the case of multiple arguments to -, this is "
+ "the number from which the others are subtracted.",
"subtrahend_1 ... subtrahend_n", "Subtrahends are numbers "
+ "subtracted from the minuend and may be any expression "
+ "that evaluates to a number."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("8");
// System.out.println(symbolTable.toString());
Num difference = new Num("0");
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
// case: only one argument: 0 - arg
difference = difference.subtract(TypeUtil.attemptCast(
Num.class,
arguments.car.eval(symbolTable)));
// System.out.println("outside " + arguments.car.eval(symbolTable));
arguments = arguments.cdr;
if (arguments == null) return difference;
// case: (- x y1 ... yn)
difference = difference.negate();
// variable number of arguments [0..inf)
while (arguments != null) {
difference = difference.subtract(TypeUtil.attemptCast(Num.class,arguments.car.eval(symbolTable)));
// System.out.println("in while " + arguments.car.eval(symbolTable));
arguments = arguments.cdr;
}
// System.out.println("DIFFERENCE "+ difference);
return difference;
}
};
// ---
// MUL
// ---
final SpecialFormEntry MUL = new SpecialFormEntry(
SpecialFormEntry.MUL, environment,
new FormHelpTopic("*", "Multiply several expressions.",
"(+ [<multiplicand_1> ... <multiplicand_n>])",
"Compute the product of the zero or more expressions passed"
+ "as arguments. In general, expressions are evaluated "
+ "before being bound to function parameters. The"
+ " expressions passed to multiply must evaluate to numbers.",
"multiplicand_1 ... multiplicand_n", "Multiplicands may be "
+ "any expression that evaluates to a number."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("9");
Num product = new Num("1");
// variable number of arguments [0..inf)
while (arguments != null) {
product = product.multiply(TypeUtil.attemptCast(
Num.class, arguments.car.eval(symbolTable)));
arguments = arguments.cdr;
}
return product;
}
};
// ---
// SUM
// ---
final SpecialFormEntry SUM = new SpecialFormEntry(
SpecialFormEntry.SUM, environment,
new FormHelpTopic("+", "Sum several expressions.",
"(+ [<addend_1> ... <addend_n>])",
"Compute the summation of the zero or more expressions passed"
+ "as arguments. In general, expressions are evaluated "
+ "before being bound to function parameters. The"
+ " expressions passed to sum must evaluate to numbers.",
"addend_1 ... addend_n", "Addends may be any expression that "
+ "evaluates to a number."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("10");
// System.out.println( symbolTable.toString());
Num sum = new Num("0");
// variable number of arguments [0..inf)
while (arguments != null) {
// System.out.println("arguments in sum " + arguments.car.eval(symbolTable));
sum = sum.add(TypeUtil.attemptCast(
Num.class,arguments.car.eval(symbolTable)));
// System.out.println("in sum while " + arguments.car.eval(symbolTable));
arguments = arguments.cdr;
}
// System.out.println("SUM " + sum);
return sum;
}
};
// ---
// NULList
// ---
final SpecialFormEntry QUESTION = new SpecialFormEntry(
SpecialFormEntry.QUESTION , environment,
new FormHelpTopic("null?", "checks if list is null",
"(car <List>) => <SExp>",
"Creates a new Sexp whose value is the same as the first element of <List> ",
"List", "a list",
"car", "an sexp"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("11");
SExp list;
list = arguments.car.eval(symbolTable);
if(list.toString().equals("NIL"))
return SExp.T;
else
return SExp.NIL;
}
};
// ---
// ISSymbol
// added by Pia Chakrabarti and Carine Iskander
// ---
final SpecialFormEntry ISSYMBOL = new SpecialFormEntry(
SpecialFormEntry.ISSYMBOL , environment,
new FormHelpTopic("symbol?", "checks if is symbol",
"(<symbol>*) => result",
"Is true if symbol, else nil",
"symbol", "a symbol",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("12");
SExp symbol;
symbol = arguments.car.eval(symbolTable);
if(symbol instanceof Symbol)
return SExp.T;
else
return SExp.NIL;
}
};
// ---
// ISNum
// added by Pia Chakrabarti and Carine Iskander
// ---
final SpecialFormEntry ISNUM = new SpecialFormEntry(
SpecialFormEntry.ISNUM , environment,
new FormHelpTopic("num?", "checks if num",
"(<num>*) => result",
"Is true if num, else nil",
"num", "a num",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("13");
SExp num;
num = arguments.car.eval(symbolTable);
if(num instanceof Num)
return SExp.T;
else
return SExp.NIL;
}
};
// ---
// ISAtom
// added by Pia Chakrabarti and Carine Iskander
// ---
final SpecialFormEntry ISATOM = new SpecialFormEntry(
SpecialFormEntry.ISATOM , environment,
new FormHelpTopic("atom?", "checks if atomic",
"(<atom>*) => result",
"Is true if atom, else nil",
"atom", "an atom",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("14");
SExp atom;
atom = arguments.car.eval(symbolTable);
if(atom instanceof Num || atom instanceof Symbol)
return SExp.T;
else
return SExp.NIL;
}
};
// ISList
//added by Pia Chakrabarti & Carine Iskander
// ---
final SpecialFormEntry ISLIST = new SpecialFormEntry(
SpecialFormEntry.ISLIST , environment,
new FormHelpTopic("list?", "checks if list",
"(<list>*) => result",
"Is true if list, else nil",
"list", "a list",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("15");
SExp list;
list = arguments.car.eval(symbolTable);
if(list instanceof List)
return SExp.T;
else
return SExp.NIL;
}
};
// ---
// LAST
// added by Pia Chakrabarti & Carine Iskander
// ---
final SpecialFormEntry LAST = new SpecialFormEntry(
SpecialFormEntry.LAST, environment,
new FormHelpTopic("LAST", "gets last element of a list",
"(last <List>) => <SExp>",
"Creates a new Sexp whose value is the same as the last element of <List> ",
"List", "a list",
"last", "an sexp"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("16");
SExp object;
List list = null;
Car car;
Cdr cdr;
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(), 1);
// get the object
object = arguments.car.eval(symbolTable);
if(object instanceof List)
{
list = (List)object;
car = new Car(list.seq.car);
cdr = new Cdr(list.seq.cdr);
while(list != null)
{
if(list.seq.cdr == null)
break;
list = new List(list.seq.cdr);
car = new Car(list.seq.car);
}
//return list.seq.car;
return car.sexp;
}
//throw new NullException();
return null;
}
};
// ---
// EQUALS
// added by Pia Chakrabarti & Carine Iskander
// ---
final SpecialFormEntry EQUALS = new SpecialFormEntry(
SpecialFormEntry.EQUALS, environment,
new FormHelpTopic("EQUALS", "checks to see if Sexp are equal",
"(<Sexp>) => <result>",
"Returns T if equal, else returns nil",
"Sexp", "an sexp",
"result", "a boolean"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("17");
SExp object1;
SExp objectsub1;
SExp objectsub2;
List list1 = null;
List listsub2 = null;
List listsub1 = null;
Car car1;
Cdr cdr1;
Car car2;
Cdr cdr2;
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(), 1);
// get the object
object1 = arguments.car.eval(symbolTable);
if(object1 instanceof List)
{
list1 = (List)object1;
objectsub1 = list1.seq.car;
list1 = new List(list1.seq.cdr);
objectsub2 = list1.seq.car;
if(objectsub1 instanceof List && objectsub2 instanceof List)
{
listsub1 = (List) objectsub1;
listsub2 = (List) objectsub2;
//check for same length
do
{
car1 = new Car(listsub1.seq.car);
car2 = new Car(listsub2.seq.car);
if(!car1.toString().equals(car2.toString()))
{
return SExp.NIL; //for now?
}
if(listsub1.seq.cdr != null && listsub2.seq.cdr != null)
{
listsub1 = new List(listsub1.seq.cdr);
listsub2 = new List(listsub2.seq.cdr);
}
else if(listsub1.seq.cdr == null && listsub2.seq.cdr != null)
{
return SExp.NIL;
}
else if(listsub1.seq.cdr != null && listsub2.seq.cdr == null)
{
return SExp.NIL;
}
else
{
break;
}
}while(true);
return SExp.T;
}
if(objectsub1 instanceof Num && objectsub2 instanceof Num)
{
Num num1 = (Num)objectsub1;
Num num2 = (Num)objectsub2;
if(!num1.toString().equals(num2.toString()))
return SExp.NIL;
else
return SExp.T;
}
if(objectsub1 instanceof Symbol && objectsub2 instanceof Symbol)
{
Symbol s1 = (Symbol)objectsub1;
Symbol s2 = (Symbol)objectsub2;
if(!s1.toString().equals(s2.toString()))
return SExp.NIL;
else
return SExp.T;
}
}
//otherwise return false
return SExp.NIL;
}
};
// ---
// CADR
// added by Pia Chakrabarti & Carine Iskander
// ---
final SpecialFormEntry CADR = new SpecialFormEntry(
SpecialFormEntry.CADR, environment,
new FormHelpTopic("CADR", "get second element of list",
"(list <List>) => <SExp>",
"Creates a new Sexp whose value is the same as the second element of <List> ",
"List", "a list",
"SExp", "an sexp"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("18");
SExp object;
List list = null;
Car car;
Cdr cdr;
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(), 1);
// get the object
object = arguments.car.eval(symbolTable);
if(object instanceof List)
{
list = (List)object;
car = new Car(list.seq.car);
cdr = new Cdr(list.seq.cdr);
if(list.seq.cdr != null)
{
list = new List(list.seq.cdr);
car = new Car(list.seq.car);
return car.sexp;
}
}
//throw new NullException();
return null;
}
};
// ---
// CAR
// ---
final SpecialFormEntry CAR = new SpecialFormEntry(
SpecialFormEntry.CAR, environment,
new FormHelpTopic("CAR", "get first element of a list",
"(car <List>) => <SExp>",
"Creates a new Sexp whose value is the same as the first element of <List> ",
"List", "a list",
"car", "an sexp"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("19");
SExp object;
List list = null;
Car car;
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(), 1);
// get the object
object = arguments.car.eval(symbolTable);
if(object instanceof List) {
list = (List)object;
car = new Car(list.seq.car);
//return list.seq.car;
return car.sexp;
}
// TODO: else throw error
return null;
}
};
// ---
// CDR
// ---
final SpecialFormEntry CDR = new SpecialFormEntry(
SpecialFormEntry.CDR, environment,
new FormHelpTopic("CDR", "get first element of a list",
"(cdr <List>) => <SExp>",
"Creates a new Sexp whose value is the same as the first element of <List> ",
"List", "a list",
"cdr", "an sexp"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("20");
SExp object;
List list = null;
Cdr cdr;
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(), 1);
// get the object
object = arguments.car.eval(symbolTable);
if(object instanceof List) {
list = (List)object;
List s = new List(list.seq.cdr);
cdr = new Cdr(s);
//return list.seq.car;
return cdr.sexp;
}
return null;
}
};
// ----
// CONS
// ----
final SpecialFormEntry CONS = new SpecialFormEntry(
SpecialFormEntry.CONS, environment,
new FormHelpTopic("CONS", "create a cons",
"(cons <object-1> <object-2>) => <cons>",
"Creates a fresh cons, the car of which is object-1 and the "
+ "cdr of which is object-2.",
"object-1", "an object",
"object-2", "an object",
"cons", "a cons"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
SExp object1, object2;
Cons cons;
// System.out.println("21");
if (arguments == null || arguments.cdr == null)
throw new InvalidArgumentQuantityException(toString(), 2);
// get the two objects
object1 = arguments.car.eval(symbolTable);
object2 = arguments.cdr.car.eval(symbolTable);
if (object2 instanceof List) cons = new Cons(object1, (List) object2);
else cons = new Cons(object1, object2);
return new List(cons);
}
};
// -----
// DEFUN
// -----
final SpecialFormEntry DEFUN = new SpecialFormEntry(
SpecialFormEntry.DEFUN, environment,
new FormHelpTopic("DEFUN", "Define a (global) function.",
"(defun <name> (<param-list>) <func-body>)",
"Create a function binding. This will replace any existing binding.",
"name", "the symbol to bind to the function definition, "
+ "not evaluated.",
"param-list", "a list of symbols that will be bound in the "
+ "function scope to the arguments passed to the function.",
"func-body", "an sexpression evaluated when the function is "
+ "called."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
Symbol functionName;
ArrayList<Symbol> parameters = new ArrayList<Symbol>();
SExp body;
//System.out.println("at 22");
// check for the correct number of arguments
if (arguments == null)
throw new InvalidArgumentQuantityException(
toString(), 3, 0);
if (arguments.length() != 3)
throw new InvalidArgumentQuantityException(
toString(), 3, arguments.length());
// TODO: check to see if a function for this symbol exists
// and warn if so
// first argument: Symbol for function name
functionName = TypeUtil.attemptCast(
Symbol.class, arguments.car);
// second argument, parameter list
arguments = arguments.cdr;
assert (arguments != null);
// read parameters
Seq paramSeq = TypeUtil.attemptCast(
List.class, arguments.car).seq;
while (paramSeq != null) {
parameters.add(TypeUtil.attemptCast(
Symbol.class, paramSeq.car));
paramSeq = paramSeq.cdr;
}
// third argument: function body
arguments = arguments.cdr;
assert (arguments != null);
// TODO: necessary? if (!(arguments.car instanceof List))
body = arguments.car;
environment.globalSymbolTable.bind(functionName,
new FunctionEntry(functionName,
parameters.toArray(new Symbol[]{}),
body));
return functionName;
}
};
// ------------
// DEFPARAMETER
// ------------
final SpecialFormEntry DEFPARAM = new SpecialFormEntry(
SpecialFormEntry.DEFPARAMETER, environment,
new FormHelpTopic("DEFPARAMETER", "define a dynamic variable",
"(defparameter <name> [<initial-value> [<documentation>]]) => <name>",
"defparameter establishes name as a dynamic variable. "
+ "defparameter unconditionally assigns the initial-value "
+ "to the dynamic variable named name (as opposed to "
+ "defvar, which assigns initial-value (if supplied) to "
+ "the dynamic variable named name only if name is not "
+ "already bound.)",
"name", "a symbol; not evaluated. ",
"initial-value", "a form, always evaluated",
"documentation", "a string; not evaluated."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
//System.out.println("23");
Symbol name;
SExp initValue = null;
HelpTopic helpinfo = null;
if (arguments == null || arguments.length() < 1)
throw new InvalidArgumentQuantityException(
toString(), 1, 0);
// first argument: variable name
name = TypeUtil.attemptCast(Symbol.class, arguments.car);
// second argument: initial value
arguments = arguments.cdr;
if (arguments != null) {
initValue = arguments.car.eval(symbolTable);
// third argument: documentation
arguments = arguments.cdr;
if (arguments != null)
helpinfo = new HelpTopic(name.toString(), "variable",
TypeUtil.attemptCast(
Str.class, arguments.car).value);
}
environment.globalSymbolTable.bind(name,
new VariableEntry(name, initValue, false, helpinfo));
return name;
}
};
// ------
// DEFVAR
// ------
final SpecialFormEntry DEFVAR = new SpecialFormEntry(
SpecialFormEntry.DEFVAR, environment,
new FormHelpTopic("DEFVAR", "define a variable",
"(defvar <name> [<initial-value> [<documentation>]]) => <name>",
"defvar establishes name as a dynamic variable and assigns "
+ "initial-value (if supplied) to the dynamic variable "
+ "named name only if name is not already bound (this is"
+ " in contrast to defparameter, which does not case if "
+ "the name has already been bound. ",
"name", "a symbol; not evaluated. ",
"initial-value", "a form, evaluated only if name is not "
+ "already bound.",
"documentation", "a string; not evaluated."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("24");
Symbol name;
SExp initValue = null;
HelpTopic helpinfo = null;
if (arguments == null || arguments.length() < 1)
throw new InvalidArgumentQuantityException(
toString(), 1, 0);
// first argument: variable name
name = TypeUtil.attemptCast(Symbol.class, arguments.car);
// if this variable is already defined, return without
// setting it
if (symbolTable.lookupVariable(name) != null)
return arguments.car;
return DEFPARAM.call(symbolTable, arguments);
}
};
// ----------------
// ENABLE-DEBUG-AST
// ----------------
final SpecialFormEntry ENABLEDEBUGAST = new SpecialFormEntry(
SpecialFormEntry.ENABLEDEBUGAST, environment,
new FormHelpTopic("ENABLE-DEBUG-AST",
"Enable debug information: abstract syntax tree.",
"(enable-debug-ast [<enable>])",
"When DEBUG-AST is enabled, the runtime environment prints a "
+ "representation of the abstract syntax tree generated "
+ "by the parser for each sexpression it parses.",
"enable", "NIL = disabled, anything else = enabled. No "
+ "argument = enabled."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
if (arguments == null) {
environment.dumpAST = true;
return SExp.NIL;
}
// System.out.println("25");
SExp retVal = arguments.car.eval(symbolTable);
if (retVal != null && retVal != SExp.NIL) environment.dumpAST = true;
else environment.dumpAST = false;
return retVal;
}
};
// --------
// FUNCTION
// --------
final SpecialFormEntry FUNCTION = new SpecialFormEntry(
SpecialFormEntry.FUNCTION, environment,
new FormHelpTopic("FUNCTION", "retrieve a function",
"(function <func-name>) => <function>",
"function returns the function specified by the symbol passed "
+ " as an argument. #'funcname is equivalent to (function "
+ " funcname).",
"func-name", "a symbol naming a function",
"function", "a function"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
FormEntry fe = null;
//System.out.println("27");
if (arguments == null)
throw new InvalidArgumentQuantityException(
toString(), 1, 0);
fe = symbolTable.lookupFunction(TypeUtil.attemptCast(
Symbol.class, arguments.car));
if (fe == null)
{
throw new UndefinedFunctionException((Symbol) arguments.car);
}
return fe;
}
};
// -------
// FUNCALL
// -------
final SpecialFormEntry FUNCALL = new SpecialFormEntry(
SpecialFormEntry.FUNCALL, environment,
new FormHelpTopic("FUNCALL", "make a function call",
"(funcall <function> <arg>*) => <result>",
"funcall applies function to args. If function is a symbol, "
+ "it is coerced to a function as if by finding its "
+ "functional value in the global environment.",
"function", "a function designator",
"arg", "an object",
"results", "the result of the function call"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("28");
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
// first argument: function designator
SExp func = arguments.car.eval(symbolTable);
// System.out.println("func in FUNCALL " + func);
FormEntry fe = null;
arguments = arguments.cdr;
// System.out.println("arguments in FUNCALL " + arguments);
//System.out.println("in funcall " + arguments.toString());
// cast if already a form entry
if (func instanceof FormEntry)
{ fe = (FormEntry) func;
// System.out.println("FUNCALL fun is formentry");
}
// lookup the function if it is a symbol
if (func instanceof Symbol) {
// System.out.println("FUNCALL fun is a symbol");
fe = environment.globalSymbolTable
.lookupFunction((Symbol) func);
if (fe == null)
// System.out.println("FUNCALL fe is null2");
throw new UndefinedFunctionException((Symbol) func);
}
if (fe == null)
{
// System.out.println("FUNCALL fe is null");
throw new TypeException(func, FormEntry.class);
}
if(fe instanceof Lambda)
{
// System.out.println("FE IS AN INSTANCE OF LAMBDA");
// System.out.println("funcall letd " + super.getLetD());
fe.setLetD(super.getLetD());
return fe.call(symbolTable, arguments);
}
// make the function call
else
return fe.call(symbolTable, arguments);
}
};
// ----
// GETF
// ----
final SpecialFormEntry GETF = new SpecialFormEntry(
SpecialFormEntry.GETF, environment,
new FormHelpTopic("GETF", "",
"(getf <plist> <indicator> [<default>]) => <value>",
"getf finds a property on the plist whose property indicator "
+ "is identical to indicator, and returns its "
+ "corresponding property value. If there are multiple "
+ "properties with that property indicator, getf uses the "
+ "first such property. If there is no property with that "
+ "property indicator, default is returned.",
"plist", "a property list.",
"indicator", "an object",
"default", "an object. The default is NIL",
"value", "an object"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
//System.out.println("29");
SExp plistEval;
Seq plistSeq;
SExp indicator;
SExp retVal = SExp.NIL;
if (arguments == null || arguments.length() < 2)
throw new InvalidArgumentQuantityException(
toString(), 2, 0);
// first argument: property list
plistEval = arguments.car.eval(symbolTable);
plistSeq = TypeUtil.attemptCast(List.class, plistEval).seq;
// second argument: indicator
arguments = arguments.cdr;
indicator = arguments.car.eval(symbolTable);
// third argument: default value
arguments = arguments.cdr;
if (arguments != null)
retVal = arguments.car.eval(symbolTable);
while(plistSeq != null) {
// check this value for equality
if (plistSeq.car.equals(indicator))
if (plistSeq.cdr != null)
return plistSeq.cdr.car;
// advance to the next pair (or terminate)
plistSeq = (plistSeq.cdr == null ? null : plistSeq.cdr.cdr);
}
return retVal;
}
};
// ----
// HELP
// ----
final SpecialFormEntry HELP = new SpecialFormEntry(
SpecialFormEntry.HELP, environment,
new FormHelpTopic("HELP",
"Display online help information for a topic.",
"(help [<topic>*])",
null,
"topic",
"either a string representing the topic to lookup or a symbol"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("30");
ArrayList<HelpTopic> topics = new ArrayList<HelpTopic>();
// no arguments: print help for HELP
if (arguments == null)
return this.call(symbolTable,
new Seq(SpecialFormEntry.HELP, null));
while (arguments != null) {
// try to find the topic or function help
if (arguments.car instanceof Str) {
topics.add(HelpTopic.helpTopics.get(
((Str) arguments.car).value));
} else if (arguments.car instanceof Symbol) {
// lookup help for funtion
FormEntry fe = symbolTable.lookupFunction(
(Symbol) arguments.car);
if (fe != null) topics.add(fe.helpinfo);
// lookup help for variable
VariableEntry ve = symbolTable.lookupVariable(
(Symbol) arguments.car);
if (ve != null) topics.add(ve.helpinfo);
}
arguments = arguments.cdr;
}
for (HelpTopic topic : topics)
topic.print(environment.getOutputStream());
return SExp.NIL;
}
};
// --
// IF
// --
final SpecialFormEntry IF = new SpecialFormEntry(
SpecialFormEntry.IF, environment,
new FormHelpTopic("IF",
"conditional code execution",
"(if <test-form> <then-form> [<else-form>]) => result*",
"if allows the execution of a form to be dependent on a "
+ "single test-form. First test-form is evaluated. If "
+ "the result is true, then then-form is selected; "
+ "otherwise else-form is selected. Whichever form is "
+ "selected is then evaluated.",
"test-form", "a form.",
"then-form", "a form.",
"else-form", "a form. The default is nil. ",
"results", "if the test-form yielded true, the values "
+ "returned by the then-form; otherwise, the values "
+ "returned by the else-form."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
//System.out.println("31");
if (arguments == null || arguments.length() < 2)
throw new InvalidArgumentQuantityException(toString(), 2);
// evaluate test form
SExp testResult = arguments.car.eval(symbolTable);
// advance to then-form
arguments = arguments.cdr;
// if false, advance to else-form
if (testResult == null || testResult == SExp.NIL)
arguments = arguments.cdr;
if (arguments == null) return SExp.NIL;
return arguments.car.eval(symbolTable);
}
};
// ------
// LABELS
// ------
final SpecialFormEntry LABELS = new SpecialFormEntry(
SpecialFormEntry.LABELS, environment,
new FormHelpTopic("LABELS", "recursive function definition",
"(labels ((function-name (param*) local-form*)*) form*) => "
+ "result",
"labels defines locally named functions and executes a series "
+ "of forms with these definition bindings. Any number of "
+ "such local functions can be defined. The scope of the "
+ "defined function names for labels encompasses the "
+ "function definitions themselves as well as the body.",
"function-name", "a symbol",
"param", "a symbol",
"local-form", "a form (the list of local-forms is an implicit "
+ "progn.",
"form", "a form (the list of forms is an implicit progn."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
//System.out.println("32");
ArrayList<FormEntry> localFunctions = new ArrayList<FormEntry>();
ArrayList<Symbol> params;
LinkedList<SExp> localForms;
Seq labelsSeq, defunSeq, paramSeq;
SExp funcBody, result = SExp.NIL;
Symbol funcName;
SymbolTable newScope;
if (arguments == null)
throw new InvalidArgumentQuantityException(toString(),
"at least one argument is required.");
labelsSeq = TypeUtil.attemptCast(List.class, arguments.car).seq;
// parse each local function definition
while (labelsSeq != null) {
defunSeq = TypeUtil.attemptCast(List.class,
labelsSeq.car).seq;
if (defunSeq == null || defunSeq.length() < 3)
throw new LispException("Malformed LABELS expression: "
+ "function definition list is incomplete.");
funcName = TypeUtil.attemptCast(Symbol.class, defunSeq.car);
defunSeq = defunSeq.cdr;
paramSeq = TypeUtil.attemptCast(List.class,
defunSeq.car).seq;
defunSeq = defunSeq.cdr;
// capture each parameter to this function
params = new ArrayList<Symbol>();
while (paramSeq != null) {
params.add(TypeUtil.attemptCast(Symbol.class,
paramSeq.car));
paramSeq = paramSeq.cdr;
}
// capture each local form
localForms = new LinkedList<SExp>();
while(defunSeq != null) {
localForms.add(defunSeq.car);
defunSeq = defunSeq.cdr;
}
// create the implicit PROGN
localForms.addFirst(SpecialFormEntry.PROGN);
funcBody = new List(new Seq(
localForms.toArray(new SExp[]{})));
// create the FunctionEntry
localFunctions.add(new FunctionEntry(funcName,
params.toArray(new Symbol[]{}), funcBody));
// next function definition
labelsSeq = labelsSeq.cdr;
}
// create the new scope to include the new function definitions
newScope = new SymbolTable(symbolTable);
for (FormEntry fe : localFunctions)
newScope.bind(fe.symbol, fe);
// advance to the body of the LABELS form, the implicit PROGN
// of forms
arguments = arguments.cdr;
while (arguments != null) {
result = arguments.car.eval(newScope);
arguments = arguments.cdr;
}
return result;
}
};
// ------
// LAMBDA
// ------
final SpecialFormEntry LAMBDA = new SpecialFormEntry(
SpecialFormEntry.LAMBDA, environment,
new FormHelpTopic("LAMDA",
"create an anonymous function over the current lexical closure",
"(lambda <param-list> <form>) => <lambda>",
"",
"param-list", "a list of symbols",
"form", "a form",
"lambda", "a function"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
ArrayList<Symbol> parameters = new ArrayList<Symbol>();
SExp body;
Seq paramSeq;
// System.out.println("33");
// System.out.println("IM IN LAMBDA");
// System.out.println(symbolTable.toString());
if (arguments == null || arguments.length() != 2)
throw new InvalidArgumentQuantityException(toString(), 2);
// first parameter: parameters to the lambda
paramSeq = TypeUtil.attemptCast(List.class, arguments.car).seq;
while (paramSeq != null) {
parameters.add(TypeUtil.attemptCast(
Symbol.class, paramSeq.car));
paramSeq = paramSeq.cdr;
}
// second argument: function body
arguments = arguments.cdr;
//System.out.println("argument " + arguments.toString());
assert (arguments != null);
body = arguments.car;
// System.out.println("getLetD in lambda " + super.getLetD());
// System.out.println("new setLetD in lambda: " + super.setLetD(super.getLetD()));
return new Lambda(parameters.toArray(new Symbol[]{}),
body, symbolTable, super.getLetD());
}
};
// ---
// LET
// ---
final SpecialFormEntry LET = new SpecialFormEntry(
SpecialFormEntry.LET, environment,
new FormHelpTopic("LET", "create new lexical variable bindings",
"(let (([<var> <init-form>])*) <form>*) => <result>",
"let creates new variable bindings and executes a series of "
+ "forms that use these bindings. let performs the "
+ "bindings in parallel (as opposed to let* which does "
+ "them sequentially). The form (let ((var1 init-form-1) "
+ "(var2 init-form-2) ... (varm init-form-m)) form1 form2 "
+ "... formn) first evaluates the expressions init-form-1, "
+ "init-form-2, and so on, in that order, saving the "
+ "resulting values. Then all of the variables varj are "
+ "bound to the corresponding values; each binding is "
+ "lexical. The expressions formk are then evaluated in "
+ "order; the values of all but the last are discarded "
+ "(that is, the body of a let is an implicit progn).",
"var", "a symbol",
"init-form", "a form",
"form", "a form",
"result", "the value returned by the last form"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("34");
// System.out.println(symbolTable.toString());
SymbolTable newScope;
Seq letBinding;
ArrayList<Symbol> symbols = new ArrayList<Symbol>();
ArrayList<SExp> values = new ArrayList<SExp>();
SExp retVal = SExp.NIL;
if (arguments == null || arguments.length() < 1)
throw new InvalidArgumentQuantityException(toString(), 1);
letBinding = TypeUtil.attemptCast(
List.class, arguments.car).seq;
while (letBinding != null) {
// each binding should be a list of a symbol and form
if (!(letBinding.car instanceof List))
throw new LispException("Malformed LET bindings: "
+ letBinding.car.toString());
// get the symbol
Seq binding = TypeUtil.attemptCast(
List.class, letBinding.car).seq;
if (binding == null)
throw new LispException(""); // TODO
symbols.add(TypeUtil.attemptCast(Symbol.class, binding.car));
// get and evaluate the value
binding = binding.cdr;
if (binding == null) values.add(SExp.NIL);
else values.add(binding.car.eval(symbolTable));
// next let binding
letBinding = letBinding.cdr;
}
// perform actual binding in a new scope
newScope = new SymbolTable(symbolTable);
for (int i = 0; i < symbols.size(); ++i){
// System.out.println("taking " + symbols.get(i) + " " + values.get(i) + " in");
newScope.bind(symbols.get(i),
new VariableEntry(symbols.get(i), values.get(i)));
}
/*for(int i = symbols.size(); i > 0; i--)
{
if (i > 1)
newScope.unbind(symbols.get(i -1));
}*/
// evaluate all forms with the new scope
// System.out.println("new scope in let " + newScope.toString());
symbolTable = newScope;
arguments = arguments.cdr;
while (arguments != null) {
retVal = arguments.car.eval(symbolTable);
arguments = arguments.cdr;
}
return retVal;
}
};
// ---
// LETD
// ---
final SpecialFormEntry LETD = new SpecialFormEntry(
SpecialFormEntry.LETD, environment,
new FormHelpTopic("LETD", "create new lexical variable bindings dynamically",
"(letd (([<var> <init-form>])*) <form>*) => <result>",
"letd creates new variable bindings and executes a series of "
+ "forms that use these bindings. let performs the "
+ "bindings in parallel (as opposed to let* which does "
+ "them sequentially). The form (let ((var1 init-form-1) "
+ "(var2 init-form-2) ... (varm init-form-m)) form1 form2 "
+ "... formn) first evaluates the expressions init-form-1, "
+ "init-form-2, and so on, in that order, saving the "
+ "resulting values. Then all of the variables varj are "
+ "bound to the corresponding values; each binding is "
+ "lexical. The expressions formk are then evaluated in "
+ "order; the values of all but the last are discarded "
+ "(that is, the body of a let is an implicit progn).",
"var", "a symbol",
"init-form", "a form",
"form", "a form",
"result", "the value returned by the last form"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
super.setLetD(true);
// System.out.println("I'm in letd 8-) and letd is " + super.getLetD());
// System.out.println("34-2");
// System.out.println(symbolTable.toString());
SymbolTable newScope;
Seq letBinding;
ArrayList<Symbol> symbols = new ArrayList<Symbol>();
ArrayList<SExp> values = new ArrayList<SExp>();
SExp retVal = SExp.NIL;
if (arguments == null || arguments.length() < 1)
throw new InvalidArgumentQuantityException(toString(), 1);
letBinding = TypeUtil.attemptCast(
List.class, arguments.car).seq;
while (letBinding != null) {
// each binding should be a list of a symbol and form
if (!(letBinding.car instanceof List))
throw new LispException("Malformed LET bindings: "
+ letBinding.car.toString());
// get the symbol
Seq binding = TypeUtil.attemptCast(
List.class, letBinding.car).seq;
if (binding == null)
throw new LispException(""); // TODO
symbols.add(TypeUtil.attemptCast(Symbol.class, binding.car));
// get and evaluate the value
binding = binding.cdr;
if (binding == null) values.add(SExp.NIL);
else values.add(binding.car.eval(symbolTable));
// next let binding
letBinding = letBinding.cdr;
}
// perform actual binding in a new scope
newScope = new SymbolTable(symbolTable);
for (int i = 0; i < symbols.size(); ++i){
// System.out.println("taking " + symbols.get(i) + " " + values.get(i) + " in");
newScope.bind(symbols.get(i),
new VariableEntry(symbols.get(i), values.get(i)));
}
/*for(int i = symbols.size(); i > 0; i--)
{
if (i > 1)
newScope.unbind(symbols.get(i -1));
}*/
// evaluate all forms with the new scope
// System.out.println("new scope in let " + newScope.toString());
symbolTable = newScope;
arguments = arguments.cdr;
while (arguments != null) {
retVal = arguments.car.eval(symbolTable);
arguments = arguments.cdr;
}
// System.out.println("before we leave letd " + super.getLetD());
return retVal;
}
};
// ----
// LET*
// ----
final SpecialFormEntry LET_STAR = new SpecialFormEntry(
SpecialFormEntry.LET_STAR, environment,
new FormHelpTopic("LET*", "create new lexical variable bindings",
"(let (([<var> <init-form>])*) <form>*) => <result>",
"let* creates new variable bindings and executes a series of "
+ "forms that use these bindings. let* performs the "
+ "bindings sequentially (as opposed to let which does "
+ "them in parallel). The expression for the init-form of "
+ "a var can refer to vars previously bound in the let*."
+ "The form (let* ((var1 init-form-1) (var2 init-form-2)"
+ " ... (varm init-form-m)) form1 form2 ... formn) first "
+ "evaluates the expression init-form-1, then binds the "
+ "variable var1 to that value; then it evaluates "
+ "init-form-2 and binds var2, and so on. The expressions "
+ "formj are then evaluated in order; the values of all "
+ "but the last are discarded (that is, the body of let* "
+ "is an implicit progn).",
"var", "a symbol",
"init-form", "a form",
"form", "a form",
"result", "the value returned by the last form"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
//System.out.println("35");
SymbolTable newScope;
Seq letBinding;
Symbol var;
SExp initvalue;
SExp retVal = SExp.NIL;
if (arguments == null || arguments.length() < 1)
throw new InvalidArgumentQuantityException(toString(), 1);
letBinding = TypeUtil.attemptCast(
List.class, arguments.car).seq;
// perform actual binding in a new scope
newScope = new SymbolTable(symbolTable);
while (letBinding != null) {
// each binding should be a list of a symbol and form
if (!(letBinding.car instanceof List))
throw new LispException("Malformed LET bindings: "
+ letBinding.car.toString());
// get the symbol
Seq binding = TypeUtil.attemptCast(
List.class, letBinding.car).seq;
if (binding == null)
throw new LispException(""); // TODO
var = TypeUtil.attemptCast(Symbol.class, binding.car);
// get and evaluate the value
// include already bound variables from the let* in the
// scope for this evaluation
binding = binding.cdr;
if (binding == null) initvalue = SExp.NIL;
else initvalue = binding.car.eval(newScope);
//System.out.println("Binding in let* " + var + " to " + initvalue);
newScope.bind(var, new VariableEntry(var, initvalue));
// next let binding
letBinding = letBinding.cdr;
}
// evaluate all forms with the new scope
arguments = arguments.cdr;
while (arguments != null) {
retVal = arguments.car.eval(newScope);
arguments = arguments.cdr;
}
return retVal;
}
};
// ------
// LETREC
// ------
// This is a Scheme function. It exists in CLISP as LABELS. The
// special form in JLisp is provided as an alias for LABELS
// ----
// LIST
// ----
final SpecialFormEntry LIST = new SpecialFormEntry(
SpecialFormEntry.LIST, environment,
new FormHelpTopic("LIST", "create a list",
"(list <object>*) => list",
"list returns a list containing the supplied objects.",
"object", "an object.",
"list", "a list."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
//System.out.println("36");
ArrayList<SExp> values = new ArrayList<SExp>();
Seq retVal = null;
if (arguments == null) return SExp.NIL;
while(arguments != null) {
// eval and push the current object
values.add(arguments.car.eval(symbolTable));
// next object in argument list
arguments = arguments.cdr;
}
for (int i = values.size(); i != 0;)
retVal = new Seq(values.get(--i), retVal);
return new List(retVal);
}
};
// ---
// MOD
// ---
// TODO: this does not follow the Common Lisp standard (which requires
// FLOOR, TRUNCATE, and others to be defined). Fix in future when the
// required functionsa re defined.
final SpecialFormEntry MOD = new SpecialFormEntry(
SpecialFormEntry.MOD, environment,
new FormHelpTopic("MOD", "modulus",
"(mod <number> <divisor>) => <result>",
"mod performs the operation floor on number and divisor and "
+ "returns the remainder of the floor operation. mod is "
+ "the modulus function when number and divisor are "
+ "integers. ",
"number", "a real.",
"divisor", "a real.",
"result", "a real."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("37");
Num dividend, divisor;
if (arguments == null || arguments.length() != 2)
throw new InvalidArgumentQuantityException(toString(), 2);
dividend = TypeUtil.attemptCast(Num.class,
arguments.car.eval(symbolTable));
divisor = TypeUtil.attemptCast(Num.class,
arguments.cdr.car);
return dividend.remainder(divisor);
}
};
// -----
// QUOTE
// -----
final SpecialFormEntry QUOTE = new SpecialFormEntry(
SpecialFormEntry.QUOTE, environment,
new FormHelpTopic("QUOTE", "Return objects unevaluated.",
"(quote <object>) => <object>",
"The quote special operator just returns object. The "
+ "consequences are undefined if literal objects (including "
+ "quoted objects) are destructively modified. ",
"object", "an object; not evaluated."))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
if (arguments == null)
throw new InvalidArgumentQuantityException(
toString(), 1, 0);
//System.out.println("38");
return arguments.car;
}
};
// -----
// PROGN
// -----
final SpecialFormEntry PROGN = new SpecialFormEntry(
SpecialFormEntry.PROGN, environment,
new FormHelpTopic("PROGN",
"evaluate forms in the order they are given",
"(progn <form>*) => <result>*",
"progn evaluates forms, in the order in which they are given. "
+ "The values of each form but the last are discarded. If "
+ "progn appears as a top level form, then all forms "
+ "within that progn are considered by the compiler to be "
+ "top level forms. ",
"form", "a list of forms",
"result", "the value of the last form"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
//System.out.println("39");
SExp result = SExp.NIL;
// evaluate all forms, left to right
while (arguments != null) {
result = arguments.car.eval(symbolTable);
arguments = arguments.cdr;
}
return result;
}
};
// ----
// SETQ
// ----
final SpecialFormEntry SETQ = new SpecialFormEntry(
SpecialFormEntry.SETQ, environment,
new FormHelpTopic("SETQ", "Assigns values to variables.",
"(setq [<name> <form>]*)",
"Assigns values to variables. (setq var1 form1 var2 "
+ "form2 ...) is the simple variable assignment statement "
+ "of Lisp. First form1 is evaluated and the result is "
+ "stored in the variable var1, then form2 is evaluated "
+ "and the result stored in var2, and so forth. setq may "
+ "be used for assignment of both lexical and dynamic "
+ "variables. If any var refers to a binding made by "
+ "symbol-macrolet, then that var is treated as if setf "
+ "(not setq) had been used. ",
"name",
"a symbol naming a variable other than a constant variable",
"form", "a form"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
// System.out.println("40");
Symbol variableName;
SExp variableValue = SExp.NIL;
if (arguments == null || arguments.length() % 2 != 0)
throw new InvalidArgumentQuantityException(toString(),
"there must be a positive, even number of arguments "
+ "(name, value pairs)");
// treat each pair
while (arguments != null) {
// first argument of pair: Symbol for variable name
variableName = TypeUtil.attemptCast(
Symbol.class, arguments.car);
// TODO: check for redifinition of variable and warn or err
// if the variable is a constant
// second argument: variable value
arguments = arguments.cdr;
assert (arguments != null);
variableValue = arguments.car.eval(symbolTable);
symbolTable.rebind(variableName,
new VariableEntry(variableName, variableValue));
arguments = arguments.cdr;
}
return variableValue;
}
};
// -----
// TRACE
// -----
final SpecialFormEntry TRACE = new SpecialFormEntry(
SpecialFormEntry.TRACE, environment,
new FormHelpTopic("TRACE",
"enable trace information for a function",
"(trace <funcname>)",
"Turn on trace information for a function.",
"funcname", "the name of the function to trace"))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
//System.out.println("41");
if (arguments == null || arguments.car == null)
return SExp.NIL;
// only parameter: symbol to trace
Symbol symbol = TypeUtil.attemptCast(
Symbol.class, arguments.car);
FormEntry fe = symbolTable.lookupFunction(symbol);
if (fe == null)
throw new UndefinedFunctionException(symbol);
if (fe instanceof FunctionEntry)
((FunctionEntry) fe).enableTrace(true);
// TODO: else throw error
return SExp.NIL;
}
};
// ----
// QUIT
// ----
final SpecialFormEntry QUIT = new SpecialFormEntry(
SpecialFormEntry.QUIT, environment,
new FormHelpTopic("QUIT", "Exit the interpreter.",
"(quit)",
""))
{
public SExp call(SymbolTable symbolTable, Seq arguments)
throws LispException {
environment.signalStop();
return SExp.NIL;
}
};
environment.globalSymbolTable.bind(LTE.symbol, LTE);
environment.globalSymbolTable.bind(LT.symbol, LT);
environment.globalSymbolTable.bind(NUMEQ.symbol, NUMEQ);
environment.globalSymbolTable.bind(NUMNOTEQ.symbol, NUMNOTEQ);
environment.globalSymbolTable.bind(GT.symbol, GT);
environment.globalSymbolTable.bind(GTE.symbol, GTE);
environment.globalSymbolTable.bind(DIF.symbol, DIF);
environment.globalSymbolTable.bind(DIV.symbol, DIV);
environment.globalSymbolTable.bind(MUL.symbol, MUL);
environment.globalSymbolTable.bind(SUM.symbol, SUM);
environment.globalSymbolTable.bind(QUESTION.symbol, QUESTION);
environment.globalSymbolTable.bind(ISSYMBOL.symbol, ISSYMBOL);
environment.globalSymbolTable.bind(ISNUM.symbol, ISNUM);
environment.globalSymbolTable.bind(ISATOM.symbol, ISATOM);
environment.globalSymbolTable.bind(ISLIST.symbol, ISLIST);
environment.globalSymbolTable.bind(CAR.symbol, CAR);
environment.globalSymbolTable.bind(CDR.symbol, CDR);
environment.globalSymbolTable.bind(EQUALS.symbol, EQUALS);
environment.globalSymbolTable.bind(CADR.symbol, CADR);
environment.globalSymbolTable.bind(CONS.symbol, CONS);
environment.globalSymbolTable.bind(DEFUN.symbol, DEFUN);
environment.globalSymbolTable.bind(DEFPARAM.symbol, DEFPARAM);
environment.globalSymbolTable.bind(DEFVAR.symbol, DEFVAR);
environment.globalSymbolTable.bind(ENABLEDEBUGAST.symbol, ENABLEDEBUGAST);
environment.globalSymbolTable.bind(FUNCALL.symbol, FUNCALL);
environment.globalSymbolTable.bind(FUNCTION.symbol, FUNCTION);
environment.globalSymbolTable.bind(GETF.symbol, GETF);
environment.globalSymbolTable.bind(HELP.symbol, HELP);
environment.globalSymbolTable.bind(IF.symbol, IF);
environment.globalSymbolTable.bind(LABELS.symbol, LABELS);
environment.globalSymbolTable.bind(LAMBDA.symbol, LAMBDA);
environment.globalSymbolTable.bind(LET.symbol, LET);
environment.globalSymbolTable.bind(LETD.symbol, LETD);
environment.globalSymbolTable.bind(LET_STAR.symbol, LET_STAR);
environment.globalSymbolTable.bind(SpecialFormEntry.LETREC, LABELS);
environment.globalSymbolTable.bind(LIST.symbol, LIST);
environment.globalSymbolTable.bind(LAST.symbol, LAST);
environment.globalSymbolTable.bind(MOD.symbol, MOD);
environment.globalSymbolTable.bind(QUOTE.symbol, QUOTE);
environment.globalSymbolTable.bind(PROGN.symbol, PROGN);
environment.globalSymbolTable.bind(SETQ.symbol, SETQ);
environment.globalSymbolTable.bind(TRACE.symbol, TRACE);
environment.globalSymbolTable.bind(QUIT.symbol, QUIT);
}
}
|
package businesscode;
/**
*
* @Filename Demograph.java
*
* @Version $Id: Demograph.java,v 1.0 2014/02/25 09:23:00 $
*
* @Revisions
* Initial Revision
*/
import connect.JDBCMySQLMain;
import gui.Graph;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* <p/>
* The analysis file for determing the results
*
* @author Hasrimrat Paramar
*/
public class ObesityRestaurant {
String query = null;
// Constructor
public ObesityRestaurant() {
query = "SELECT\n" +
" healthStats.county_name as county," +
" healthStats.state as state," +
" healthStats.year as year," +
" healthStats.obesity_rate as obesity," +
" restaurant.count as restraunts " +
"FROM" +
" healthstatistics AS healthStats," +
" restaurant " +
"WHERE" +
" healthStats.county_name = restaurant.county_name " +
"AND healthStats.state = restaurant.state " +
"AND healthStats.year = restaurant.year " +
"AND restaurant.type LIKE\"Fast%\" " +
"GROUP BY" +
" healthStats.county_name," +
" healthStats.state," +
" healthStats.year;";
}
/**
* Query is executed here
*/
public void getResults() {
JDBCMySQLMain connectToDB = new JDBCMySQLMain();
ResultSet resultSet = connectToDB.executeQuery(query);
HashMap<Integer, HashMap> collection = new HashMap<Integer, HashMap>();
List<String> countyStateList = new ArrayList<String>();
HashMap<String, Double> obesityRate11 = new HashMap<String, Double>();
HashMap<String, Integer> numRestaurants11 = new HashMap<String, Integer>();
HashMap<String, Double> obesityRate12 = new HashMap<String, Double>();
HashMap<String, Integer> numRestaurants12 = new HashMap<String, Integer>();
HashMap<String, Double> obesityRate13 = new HashMap<String, Double>();
HashMap<String, Integer> numRestaurants13 = new HashMap<String, Integer>();
try {
while (resultSet.next()) {
int year = resultSet.getInt("year");
String countyState = resultSet.getString("county") + " " + resultSet.getString("state");
double obesity = resultSet.getDouble("obesity");
int restaurants = resultSet.getInt("restraunts");
if (!countyStateList.contains(countyState))
countyStateList.add(countyState);
if (year == 2011) {
obesityRate11.put(countyState, obesity);
numRestaurants11.put(countyState, restaurants);
} else if (year == 2012) {
obesityRate12.put(countyState, obesity);
numRestaurants12.put(countyState, restaurants);
} else if (year == 2013) {
obesityRate13.put(countyState, obesity);
numRestaurants13.put(countyState, restaurants);
}
}
} catch (SQLException exception) {
exception.printStackTrace();
}
collection.put(20111, obesityRate11);
collection.put(20112, numRestaurants11);
collection.put(20121, obesityRate12);
collection.put(20122, numRestaurants12);
collection.put(20131, obesityRate13);
collection.put(20132, numRestaurants13);
calculate(collection, countyStateList);
}
/**
* Analaysis is done here
*
* @param collection
* @param countyStateList
*/
public void calculate(HashMap<Integer, HashMap> collection, List<String> countyStateList) {
double totalObesityPercent = 0;
int totalRestaurants = 0;
HashMap<String, Double> obesityRate11 = (HashMap<String, Double>) collection.get(20111);
HashMap<String, Integer> numRestaurants11 = (HashMap<String, Integer>) collection.get(20112);
HashMap<String, Double> obesityRate12 = (HashMap<String, Double>) collection.get(20121);
HashMap<String, Integer> numRestaurants12 = (HashMap<String, Integer>) collection.get(20122);
HashMap<String, Double> obesityRate13 = (HashMap<String, Double>) collection.get(20131);
HashMap<String, Integer> numRestaurants13 = (HashMap<String, Integer>) collection.get(20132);
int increasing1 = 0;
int decreasing1 = 0;
int incorrectCount1 = 0;
int increasing2 = 0;
int decreasing2 = 0;
int incorrectCount2 = 0;
int increasing3 = 0;
int decreasing3 = 0;
int incorrectCount3 = 0;
for (String countyState : countyStateList) {
if (numRestaurants11.get(countyState) > numRestaurants12.get(countyState)) {
if (obesityRate11.get(countyState) > obesityRate12.get(countyState)) {
increasing1++;
} else {
incorrectCount1++;
}
} else {
if (obesityRate11.get(countyState) < obesityRate12.get(countyState)) {
decreasing1++;
} else {
incorrectCount1++;
}
}
}
for (String countyState : countyStateList) {
if (numRestaurants12.get(countyState) > numRestaurants13.get(countyState)) {
if (obesityRate12.get(countyState) > obesityRate13.get(countyState)) {
increasing2++;
} else {
incorrectCount2++;
}
} else {
if (obesityRate12.get(countyState) < obesityRate13.get(countyState)) {
decreasing2++;
} else {
incorrectCount2++;
}
}
}
for (String countyState : countyStateList) {
if (numRestaurants11.get(countyState) > numRestaurants13.get(countyState)) {
if (obesityRate11.get(countyState) > obesityRate13.get(countyState)) {
increasing1++;
} else {
incorrectCount3++;
}
} else {
if (obesityRate11.get(countyState) < obesityRate13.get(countyState)) {
decreasing3++;
} else {
incorrectCount3++;
}
}
}
System.out.println("Increasing 11-12: " + increasing1);
System.out.println("Decreasing 11-12: " + decreasing1);
System.out.println("Incorrect 11-12: " + incorrectCount1);
System.out.println("");
System.out.println("");
System.out.println("Increasing 12-13: " + increasing2);
System.out.println("Decreasing 12-13: " + decreasing2);
System.out.println("Incorrect 12-13: " + incorrectCount2);
System.out.println("");
System.out.println("");
System.out.println("Increasing 11-13: " + increasing3);
System.out.println("Decreasing 11-13: " + decreasing3);
System.out.println("Incorrect 11-13: " + incorrectCount3);
//FOR GRAPH
ArrayList<Double> list;
list = new ArrayList();
// double increase=increasing1+increasing2+increasing3;
// double decrease=decreasing1+decreasing2+decreasing3;
// double incorrect=incorrectCount1+incorrectCount2+incorrectCount3;
double total1 = increasing1 + decreasing1 + incorrectCount1;
double total2 = increasing2 + decreasing2 + incorrectCount2;
double total3 = increasing3 + decreasing3 + incorrectCount3;
list.add((increasing1 / total1) * 100);
list.add((increasing2 / total2) * 100);
list.add((double) ((increasing3 / total3) * 100));
list.add((decreasing1 / total1) * 100);
list.add((decreasing2 / total2) * 100);
list.add((decreasing3 / total3) * 100);
list.add((incorrectCount1 / total1) * 100);
list.add((incorrectCount2 / total2) * 100);
list.add((incorrectCount3 / total3) * 100);
// System.out.println(list);
ArrayList<String> label;
label = new ArrayList();
label.add("2011-2012");
label.add("2012-2013");
label.add("2011-2013");
ArrayList<String> symbRep;
symbRep = new ArrayList();
symbRep.add("Increasing");
symbRep.add("Decreasing");
symbRep.add("Incorrect");
new Graph().plot(list, 3, label, symbRep, "Obesity Rate and Number of Restaurant(Fast food)");
// new Graph().pie(list,symbRep,this.getClass().getSimpleName());
// new Graph().USAStates(average13);
}
public String getQuery() {
return query;
}
}
|
package com.app.shubhamjhunjhunwala.thebakingapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.app.shubhamjhunjhunwala.thebakingapp.Objects.Dish;
import org.parceler.Parcels;
/**
* Created by shubham on 17/03/18.
*/
public class DetailsActivity extends AppCompatActivity {
public Dish dish;
public boolean twoPaneLayout = false;
public boolean extraDetailsShowing = false;
public TextView previousTextView;
public TextView nextTextView;
public int stepID;
public static DetailsFragment detailsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_activity);
if (savedInstanceState != null) {
dish = Parcels.unwrap(savedInstanceState.getParcelable("Dish"));
twoPaneLayout = savedInstanceState.getBoolean("TwoPane");
extraDetailsShowing = savedInstanceState.getBoolean("ExtraDetailsShowing");
stepID = savedInstanceState.getInt("StepID");
}
if (findViewById(R.id.relative_layout) != null) {
twoPaneLayout = true;
previousTextView = findViewById(R.id.previous_button);
nextTextView = findViewById(R.id.next_button);
if (!extraDetailsShowing) {
previousTextView.setVisibility(View.GONE);
nextTextView.setVisibility(View.GONE);
} else {
detailsFragment.changeAdapterItemSelection(stepID);
previousTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stepID--;
if (stepID >= 0) {
ExtraDetailsFragment extraDetailsFragment = new ExtraDetailsFragment();
extraDetailsFragment.dish = dish;
extraDetailsFragment.stepID = stepID;
extraDetailsFragment.twoPaneLayout = twoPaneLayout;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.extra_details_frame_layout, extraDetailsFragment)
.commit();
detailsFragment.changeAdapterItemSelection(stepID);
} else {
stepID++;
}
}
});
nextTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stepID++;
if (stepID < dish.getSteps().length) {
ExtraDetailsFragment extraDetailsFragment = new ExtraDetailsFragment();
extraDetailsFragment.dish = dish;
extraDetailsFragment.stepID = stepID;
extraDetailsFragment.twoPaneLayout = twoPaneLayout;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.extra_details_frame_layout, extraDetailsFragment)
.commit();
detailsFragment.changeAdapterItemSelection(stepID);
} else {
stepID--;
}
}
});
}
} else {
twoPaneLayout = false;
}
if (savedInstanceState == null) {
detailsFragment = new DetailsFragment();
dish = Parcels.unwrap(getIntent().getParcelableExtra("Dish"));
detailsFragment.dish = dish;
detailsFragment.twoPaneLayout = twoPaneLayout;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.frame_layout, detailsFragment)
.commit();
}
setTitle(dish.getName());
}
public void showExtraDetails(final int id) {
stepID = id;
previousTextView.setVisibility(View.VISIBLE);
nextTextView.setVisibility(View.VISIBLE);
ExtraDetailsFragment extraDetailsFragment = new ExtraDetailsFragment();
extraDetailsFragment.dish = dish;
extraDetailsFragment.stepID = id;
extraDetailsFragment.twoPaneLayout = twoPaneLayout;
FragmentManager fragmentManager = getSupportFragmentManager();
if (!extraDetailsShowing) {
fragmentManager.beginTransaction()
.add(R.id.extra_details_frame_layout, extraDetailsFragment)
.commit();
} else {
fragmentManager.beginTransaction()
.replace(R.id.extra_details_frame_layout, extraDetailsFragment)
.commit();
}
extraDetailsShowing = true;
previousTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stepID--;
if (stepID >= 0) {
ExtraDetailsFragment extraDetailsFragment = new ExtraDetailsFragment();
extraDetailsFragment.dish = dish;
extraDetailsFragment.stepID = stepID;
extraDetailsFragment.twoPaneLayout = twoPaneLayout;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.extra_details_frame_layout, extraDetailsFragment)
.commit();
detailsFragment.changeAdapterItemSelection(stepID);
} else {
stepID++;
}
}
});
nextTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stepID++;
if (stepID < dish.getSteps().length) {
ExtraDetailsFragment extraDetailsFragment = new ExtraDetailsFragment();
extraDetailsFragment.dish = dish;
extraDetailsFragment.stepID = stepID;
extraDetailsFragment.twoPaneLayout = twoPaneLayout;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.extra_details_frame_layout, extraDetailsFragment)
.commit();
detailsFragment.changeAdapterItemSelection(stepID);
} else {
stepID--;
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("Dish", Parcels.wrap(dish));
outState.putBoolean("TwoPane", twoPaneLayout);
outState.putBoolean("ExtraDetailsShowing", extraDetailsShowing);
outState.putInt("StepID", stepID);
}
}
|
package com.services.utils.encrypt;
/**
* Created by yoke on 2015-10-22.
*/
public class EncryptException extends Exception {
public EncryptException(Exception e) {
super(e);
}
}
|
package com.jk.jkproject.ui.chat;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.TimeUtils;
import com.jk.jkproject.ui.entity.BaseInfo;
import com.jk.jkproject.utils.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Zick
* @params
* @date 2020/7/15 9:38 AM
* @desc 聊天记录
*/
public class ChatRecordBeanInfo extends BaseInfo {
/**
* data : {"conversationList":["{\"msgType\":0,\"count\":0,\"msgId\":\"1897\",\"time\":1594711600205,\"body\":\"[/流泪][/流泪][/流泪]r\",\"userName\":\"赤い\",\"userId\":\"1000002\",\"picture\":\"http://qn.zbjlife.cn/58f43ffe6ccab14ad4d47688ae9e08fb.png\",\"target\":\"1000035\"}"]}
*/
private DataBean data;
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
private List<String> msgList;
private ArrayList<Message> messageList;
public ArrayList<Message> getUserList() {
return setUserList();
}
public List<String> getConversationList() {
return msgList;
}
public void setConversationList(List<String> msgList) {
this.msgList = msgList;
}
public ArrayList<Message> setUserList() {
if (msgList != null && msgList.size() > 0) {
messageList = new ArrayList<>();
long msgTime = -1;
for (int b = 0; b < msgList.size(); b++) {
try {
JSONObject jSONObject = new JSONObject(msgList.get(b));
Message message = new Message();
if (jSONObject.getInt("msgType") == Constants.MsgType.TYPE_LIVE_CHAT_SYSTEM_0 || (jSONObject.getInt("msgType") >= 51 && jSONObject.getInt("msgType") <= 66)) {
message.setUuid(jSONObject.getString("msgId"));
message.setMsgId(jSONObject.getString("msgId"));
/**
* * 订单相关
* * 51 用户已发起订单,同意并立刻接单
* * 52 用户取消订单
* * 53 超时未接单,订单已取消,金额将原路退回
* * 54 你已拒绝该订单,订单金额将原路退还
* * 55 订单已接受,去联系用户开始游戏
* * 56 用户昵称xxx已发起退款,请立即处理退款
* * 57 用户已经确认完成,订单已完成
* * 58 等待大神接单
* * 59 大神超时未接单
* * 60 你已取消订单,金额原路退还
* * 61 大神已拒绝订单,订单金额将原路退还
* * 62 大神已准备就绪,随时可以开始游戏
* * 63 你已申请退款,等待大神处理
* * 64 大神已同意退款,订单金额将原路退还
* * 65 大神已拒绝退款,原因:
* * 66 大神已发起服务完成,同意并确认完成
*/
if (jSONObject.getInt("msgType") == 0) {
message.setMsgType(MsgType.TEXT);
TextMsgBody body = new TextMsgBody();
body.setMessage(jSONObject.getString("body"));
message.setBody(body);
message.setContent(jSONObject.getString("body"));
message.setCount(jSONObject.getInt("count"));
message.setSentTime(jSONObject.getLong("time"));
message.setUserName(jSONObject.getString("username"));
message.setUserId(jSONObject.getString("userId"));
message.setTargetId(jSONObject.getString("target"));
if (!message.getUserId().equals("1")) {
message.setPicture(jSONObject.getString("picture"));
}
} else if (jSONObject.getInt("msgType") >= 51 && jSONObject.getInt("msgType") <= 66) {
message.setMsgType(MsgType.ORDER);
TextMsgBody body = new TextMsgBody();
body.setMessage(jSONObject.getString("body"));
message.setBody(body);
message.setSentTime(jSONObject.getLong("time"));
message.setContent(jSONObject.getString("body"));
message.setUserId(jSONObject.getString("userId"));
}
if (msgTime == -1) {
message.setShowTime(true);
msgTime = message.getSentTime();
} else {
long timeSpan = TimeUtils.getTimeSpan(msgTime, message.getSentTime(), TimeConstants.MIN);
if (timeSpan >= 3) {
message.setShowTime(true);
msgTime = message.getSentTime();
} else {
message.setShowTime(false);
}
}
messageList.add(message);
}
} catch (JSONException jSONException) {
jSONException.printStackTrace();
}
}
}
return messageList;
}
public ArrayList<Message> getReverseMessage() {
if (messageList != null && messageList.size() > 0)
Collections.sort(messageList, (o1, o2) -> {
if (o1.getSentTime() > o2.getSentTime()) {
return 1;
} else if (o1.getSentTime() == o2.getSentTime()) {
return 0;
} else {
return -1;
}
});
return messageList;
}
}
}
|
package com.tencent.mm.plugin.fav.ui.detail;
import com.tencent.mm.plugin.fav.ui.detail.FavoriteVideoPlayUI.4;
import com.tencent.mm.ui.tools.f.b;
class FavoriteVideoPlayUI$4$1 implements b {
final /* synthetic */ 4 jdP;
FavoriteVideoPlayUI$4$1(4 4) {
this.jdP = 4;
}
public final void onAnimationStart() {
if (this.jdP.jdN.jdH != null) {
this.jdP.jdN.jdH.onResume();
}
}
public final void onAnimationEnd() {
}
}
|
package org.mycompany.service.offer.comparator;
import org.mycompany.entity.Offer;
import java.util.Comparator;
public class BuyOfferComparator implements Comparator<Offer> {
@Override
public int compare(Offer offer1, Offer offer2) {
int comparePrice = Integer.compare(offer1.getPrice(), offer2.getPrice());
if (comparePrice != 0) {
return -comparePrice;
}
if (offer1.getId() == null && offer2.getId() == null) {
return 0;
}
if (offer1.getId() == null) {
return 1;
}
if (offer2.getId() == null) {
return -1;
}
return Long.compare(offer1.getId(), offer2.getId());
}
}
|
package com.hand6.health.app.service;
import com.hand6.health.domain.entity.MotionIndicators;
import com.hand6.health.domain.entity.MotionRecords;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* Created by Administrator on 2019/7/3.
*/
public interface MotionRecordsService {
MotionRecords save(HttpServletRequest httpServletRequest);
MotionRecords update(MotionRecords motionRecords);
MotionRecords remove(MotionRecords motionRecords);
List<MotionRecords> list(MotionRecords motionRecords);
MotionRecords disabled(Long id);
}
|
package com.learn.learn.设计模式.Builder;
public class Builder {
private boolean isLong;
private boolean isThin;
private boolean isBuild;
public Builder(Build build) {
isLong = build.isLong;
isThin = build.isThin;
isBuild = build.isBuild;
}
public String toString() {
StringBuilder str = new StringBuilder("Builder设计模式的使用:");
if (isLong) {
str.append(" 是长的");
}
if (isThin) {
str.append(" 是瘦的");
}
if (isBuild) {
str.append(" 是要创造的");
}
return str.toString();
}
public static class Build {
private boolean isLong;
private boolean isThin;
private boolean isBuild;
public Build() {
}
public Build writeIsLong() {
isLong = true;
return this;
}
public Build writeIsThin() {
isThin = true;
return this;
}
public Build writeIsBuild() {
isBuild = true;
return this;
}
public Builder getBuilder() {
return new Builder(this);
}
}
}
|
package com.task.Dao;
import java.util.List;
import com.task.model.Task;
public class TaskDaoImpl implements TaskDao {
public void createTask(Task task) {
// TODO Auto-generated method stub
}
public void updateTask(int taskId, Task task) {
// TODO Auto-generated method stub
}
public void deleteTask(int taskId) {
// TODO Auto-generated method stub
}
public List<Task> searchTask(String taskName) {
// TODO Auto-generated method stub
return null;
}
public void assignTask(int taskId, int userId) {
// TODO Auto-generated method stub
}
public List<Task> viewTask(int taskId) {
// TODO Auto-generated method stub
return null;
}
public List<Task> listAllTask() {
// TODO Auto-generated method stub
return null;
}
}
|
package Kamil_zerg;
import java.util.*;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.MapLocation;
import battlecode.common.Message;
import battlecode.common.RobotController;
import battlecode.common.Team;
/**
*
* @author Mimuw_ZERG
*
*/
public class Comms {
/** If true then print debug strings */
private final boolean DEBUG = false;
private final RobotController myRC;
public final int signature;
public enum MessageType {
/**
* first parameter - MessageType code
* second parameter - YOU_ messages are addressed to a particular robot
* third parameter - some messages have an additional int parameter
* fourth parameter - some messages have an additional MapLocation parameter
*/
NONE (0,false,false,false),
GOTO (2,false,false,true), YOU_GOTO (3,true,false,true),
ATTACK (4,false,false,true), YOU_ATTACK (5,true,false,true),
DRAIN (6,false,false,false), YOU_DRAIN (7,true,false,false),
STOP_DRAIN (8,false,false,false), YOU_STOP_DRAIN (9,true,false,false),
GOING_IN_DIR(10,false,true,false), GOING_TO_LOC (11,false,false,true),
SCOUT (12,false,false,true), YOU_SCOUT (13,true,false,true),
SIEGE_STD (14,false,false,true), SIEGE_SEC (15,false,false,true),
SIEGE_FLANK (16,false,false,true),
DEFENDING (17,false,false,true),
ARTY (18,false,true,true), YOU_ARTY (19,true,true,true),
AIMME (20,false,false,true);
public int code;
public boolean personalized;
public boolean hasParam;
public boolean hasLoc;
private MessageType(int code,boolean personalized,boolean hasParam,boolean hasLoc){
this.code = code;
this.personalized = personalized;
this.hasParam = hasParam;
this.hasLoc = hasLoc;
}
public static MessageType fromInt(int i){
switch(i){
case 2: return GOTO;
case 3: return YOU_GOTO;
case 4: return ATTACK;
case 5: return YOU_ATTACK;
case 6: return DRAIN;
case 7: return YOU_DRAIN;
case 8: return STOP_DRAIN;
case 9: return YOU_STOP_DRAIN;
case 10: return GOING_IN_DIR;
case 11: return GOING_TO_LOC;
case 12: return SCOUT;
case 13: return YOU_SCOUT;
case 14: return SIEGE_STD;
case 15: return SIEGE_SEC;
case 16: return SIEGE_FLANK;
case 17: return DEFENDING;
case 18: return ARTY;
case 19: return YOU_ARTY;
case 20: return AIMME;
default: return NONE;
}
}
public MessageType unpersonalize(){
switch(this){
case YOU_GOTO: return GOTO;
case YOU_ATTACK: return ATTACK;
case YOU_DRAIN: return DRAIN;
case YOU_STOP_DRAIN: return STOP_DRAIN;
case YOU_SCOUT: return SCOUT;
case YOU_ARTY: return ARTY;
default: return this;
}
}
}
public class CompoundMessage{
// message type
public MessageType type = MessageType.NONE;
// who is this message to
MapLocation address;
// parameters
MapLocation loc;
int param;
public CompoundMessage(){}
}
private ArrayList<CompoundMessage> queued = new ArrayList<CompoundMessage>();
public Comms(RobotController rc) {
myRC = rc;
if (myRC.getTeam() == Team.A)
signature = 154;
else
signature = 210;
}
public int dirToInt(Direction dir){
switch (dir){
case EAST: return 0;
case NONE: return 1;
case NORTH: return 2;
case NORTH_EAST: return 3;
case NORTH_WEST: return 4;
case OMNI: return 5;
case SOUTH: return 6;
case SOUTH_EAST: return 7;
case SOUTH_WEST: return 8;
case WEST: return 9;
default: return 10;
}
}
public Direction intToDir(int l){
switch(l){
case 0: return Direction.EAST;
case 1: return Direction.NONE;
case 2: return Direction.NORTH;
case 3: return Direction.NORTH_EAST;
case 4: return Direction.NORTH_WEST;
case 5: return Direction.OMNI;
case 6: return Direction.SOUTH;
case 7: return Direction.SOUTH_EAST;
case 8: return Direction.SOUTH_WEST;
case 9: return Direction.WEST;
default: return Direction.NONE;
}
}
// convert message to a list of easy-to-read classes, ignoring messages not addressed to me
public ArrayList<CompoundMessage> translateMessage(Message msg){
ArrayList<CompoundMessage> result = new ArrayList<CompoundMessage>();
int i = 1, j = 0;
if ((msg != null) && (msg.ints != null)) {
if (msg.ints[0] != signature) return result;
while (i < msg.ints.length) {
CompoundMessage cmsg = new CompoundMessage();
cmsg.type = MessageType.fromInt(msg.ints[i]);
i++;
if (cmsg.type.personalized) {
cmsg.address = msg.locations[j];
j++;
// only add YOU_ messages if I'm the one it's addressed to
if (!cmsg.address.equals(myRC.getLocation()))
continue;
else
cmsg.type = cmsg.type.unpersonalize();
}
if (cmsg.type.hasParam) {
cmsg.param = msg.ints[i];
i++;
}
if (cmsg.type.hasLoc) {
cmsg.loc = msg.locations[j];
j++;
}
result.add(cmsg);
}
}
return result;
}
public Message buildMessage(List<CompoundMessage> cmsgs){
Message result = new Message();
int intsSize = 1, locsSize = 0;
for (CompoundMessage cmsg : cmsgs) {
if (cmsg.type.hasParam)
intsSize += 2;
else
intsSize++;
if (cmsg.type.hasLoc) locsSize++;
if (cmsg.type.personalized) locsSize++;
}
if (intsSize!=0)
result.ints = new int[intsSize];
result.ints[0] = signature;
if (locsSize!=0)
result.locations = new MapLocation[locsSize];
int i = 1, j = 0;
for (CompoundMessage cmsg : cmsgs) {
String s = "Sending message " + cmsg.type;
result.ints[i] = cmsg.type.code;
i++;
if (cmsg.type.hasParam){
result.ints[i] = cmsg.param;
i++;
s += " with " + cmsg.param;
}
if (cmsg.type.personalized){
result.locations[j] = cmsg.address;
j++;
s += " for " + cmsg.address;
}
if (cmsg.type.hasLoc){
result.locations[j] = cmsg.loc;
j++;
s += " loc " + cmsg.loc;
}
if (DEBUG) System.out.println(s);
}
return result;
}
public void sendMessage(CompoundMessage cmsg){
queued.add(cmsg);
}
public void sendMessage(List<CompoundMessage> cmsgs){
for (CompoundMessage compoundMessage : cmsgs) {
queued.add(compoundMessage);
}
}
public void transmitMessages() throws GameActionException{
if (queued.size() > 0) {
Message msg = buildMessage(queued);
myRC.broadcast(msg);
queued.clear();
}
}
}
|
package com.app.gnometown.View.GnomeDetail;
import com.app.gnometown.Model.Gnome;
/**
* Created by andreinasarda on 19/4/16.
*/
public interface populateDetailInteractor {
interface onDetailLoadedListener{
void onSuccess(Gnome gnome);
void onFail();
}
void loadDetail(onDetailLoadedListener listener,int id);
}
|
class Solution {
class Node{
int id;
// distance from source node
int distance = Integer.MAX_VALUE;
Map<Node, Integer> adjacentNodes = new HashMap<>();
public Node(int id){
this.id = id;
}
}
public int networkDelayTime(int[][] times, int N, int K) {
// Dijkstra's Algorithm
Map<Integer, Node> nodes = new HashMap<>();
for(int i = 1; i <= N; i++){
nodes.put(i, new Node(i));
}
for(int i = 0; i < times.length; i++){
int nodeKey= times[i][0];
int targetNodeKey = times[i][1];
int w = times[i][2];
Node n = nodes.get(nodeKey);
Node adj = nodes.get(targetNodeKey);
n.adjacentNodes.put(adj, w);
}
Set<Node> settledNodes = new HashSet<>();
Set<Node> unsettledNodes = new HashSet<>();
Node source = nodes.get(K);
source.distance = 0;
unsettledNodes.add(source);
// start at source node to determine shortest time it takes for source to reach each node
while(!unsettledNodes.isEmpty()){
Node currentNode = getLowestDistanceNode(unsettledNodes);
unsettledNodes.remove(currentNode);
for(Map.Entry<Node, Integer> adjPair: currentNode.adjacentNodes.entrySet()){
Node adjNode = adjPair.getKey();
Integer w = adjPair.getValue();
if(!settledNodes.contains(adjNode)){
calculateMinDistance(adjNode, w, currentNode);
unsettledNodes.add(adjNode);
}
}
settledNodes.add(currentNode);
}
// find node with longest time it takes to reach
// if a node contains max int val as distance, return -1 as it is unreachable from source
int longest = 0;
for(int nodeId : nodes.keySet()){
Node currentNode = nodes.get(nodeId);
if(currentNode.distance == Integer.MAX_VALUE) return -1;
if(currentNode.distance > longest) longest = currentNode.distance;
}
return longest;
}
public Node getLowestDistanceNode(Set<Node> unsettledNodes){
Node lowestDistanceNode = null;
int lowestDistance = Integer.MAX_VALUE;
for(Node node: unsettledNodes){
int nodeDistance = node.distance;
if(nodeDistance < lowestDistance){
lowestDistance = nodeDistance;
lowestDistanceNode = node;
}
}
return lowestDistanceNode;
}
public void calculateMinDistance(Node evalNode, Integer distance, Node sourceNode){
Integer sourceDistance = sourceNode.distance;
if(sourceDistance + distance < evalNode.distance){
evalNode.distance = sourceDistance + distance;
}
}
}
|
package fr.formation.spring.museum.security;
import fr.formation.spring.museum.models.Account;
public interface IAccountDetailsProvider {
public AccountDetails getDetails();
public Account getAccount();
}
|
package com.zooniverse.android.android_zooniverse.projects;
import retrofit.http.GET;
import retrofit.http.Headers;
public interface ProjectsRetrofitInterface {
@Headers("Accept: application/vnd.api+json; version=1")
@GET("/projects")
ProjectsResponse getProjects() throws Exception;
}
|
package kr.pe.ssun.bark;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import com.facebook.AccessToken;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.common.SignInButton;
import kr.pe.ssun.bark.login.FacebookLoginHelper;
import kr.pe.ssun.bark.login.GoogleLoginHelper;
/**
* Created by x1210x on 2016. 8. 15..
*/
public class LoginModel {
private static final String TAG = LoginModel.class.getSimpleName();
private LoginPresenter mLoginPresenter;
private GoogleLoginHelper mGoogleLoginHelper;
private FacebookLoginHelper mFacebookLoginHelper;
public LoginModel(LoginPresenter presenter, FragmentActivity activity,
int googleId, int facebookId) {
mLoginPresenter = presenter;
mGoogleLoginHelper = new GoogleLoginHelper(activity);
mFacebookLoginHelper = new FacebookLoginHelper(new FacebookLoginHelper.FacebookLoginHelperListener() {
@Override
public void handleFacebookAccessToken(AccessToken token) {
mLoginPresenter.handleFacebookAccessToken(token);
}
});
mGoogleLoginHelper.initGoogleSignInButton((SignInButton) activity.findViewById(googleId));
mFacebookLoginHelper.initFacebookLoginButton((LoginButton) activity.findViewById(facebookId));
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebookLoginHelper.onActivityResult(requestCode, resultCode, data);
}
}
|
package 真题.ten;
import java.util.Scanner;
/**
* @Author: Mr.M
* @Date: 2019-04-02 20:28
* @Description: https://www.nowcoder.com/question/next?pid=10611931&qid=161633&tid=22857608
**/
public class T4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int k = Integer.valueOf(scanner.nextLine());
int a = scanner.nextInt();
int x = scanner.nextInt();
int b = scanner.nextInt();
int y = scanner.nextInt();
Long sum = 0L;
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (i * a + j * b == k) {
Long num1 = 1L;
Long num2 = 1L;
for (int m = 0; m < i; m++) {
num1 *= (x - m);
}
for (int m = 0; m < j; m++) {
num2 *= (y - m);
}
sum += num1 * num2;
}
}
}
System.out.println(sum % 1000000007);
}
}
|
package pl.agh.edu.dp.labirynth.Utils;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@AllArgsConstructor
@EqualsAndHashCode
@ToString
public class Vector2d {
final public int x;
final public int y;
public Vector2d nextPos(Direction dir) {
switch (dir) {
case South:
return new Vector2d(this.x, this.y - 1);
case East:
return new Vector2d(this.x + 1, this.y);
case West:
return new Vector2d(this.x - 1, this.y);
case North:
return new Vector2d(this.x, this.y + 1);
}
throw new NullPointerException("Pos doesnt exist");
}
public Vector2d lowerRight(Vector2d other) {
return new Vector2d(Math.max(this.x, other.x), Math.max(this.y, other.y));
}
}
|
package programmers.lv3;
public class Ranking_Test {
//순위
//플로이드 워셜 알고리즘 문제
//플로이드 워셜 알고리즘을 몰랐기에 검색 후 해결
//https://in-intuition.tistory.com/25 이 블로그에서 참고했다.
public int solution(int n, int[][] results) {
int answer = 0;
boolean[][] game = new boolean[n][n];
for (int i = 0; i < results.length; i++) {
game[results[i][0]-1][results[i][1]-1] = true;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
if (game[j][i] && game[i][k])
game[j][k] = true;
for (int i = 0; i < n; i++) {
int result = 0;
for (int j = 0; j < n; j++) {
if (game[i][j] || game[j][i])
result++;
}
if (result == n - 1) answer++;
}
return answer;
}
}
|
package com.jmsReader.webSocket;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import javax.sound.sampled.LineUnavailableException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* @author Vladimir Cherepnalkovski
*
*/
@RestController
public class NotificationRest {
@CrossOrigin(origins = "*", allowedHeaders = "*")
@GET
@Path("/{fileName}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response echo(@PathParam("fileName") final String fileName) throws LineUnavailableException {
// TODO: decript file name and get the file from the disk.
return Response.status(200).entity(String.format("{\"echo\":\"%s\"}", fileName)).build();
}
}
|
package Math;
public class Reverse_7 {
/*7.整数反转*/
/*
注意超过int的最大最小值的情况;
*/
public int reverse(int x) {
boolean flag = false;
int res = 0;
if(x < 0){
flag = true;
}
while(x != 0){
if(flag){
if( res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && x % 10 < -8)){
return 0;
}
}else{
if(res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && x % 10 > 7)){
return 0;
}
}
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
}
|
import com.sun.source.tree.Scope;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Iterator;
public class Server
{
private Socket socket;
private ServerSocket serverSocket;
private String ipInfo;
private BufferedReader bufferedReader;
private BufferedOutputStream bufferedOutputStream;
private FileOutputStream fileOutputStream;
private String adminKey;
private HashSet<User> hashSet;
private String account, passwd, inviteCode;
private File infofile = new File("D://info.key");
private boolean isAdmin = false;
public Server(String adminKey)
{
this.adminKey = adminKey;
try
{
serverSocket = new ServerSocket(10001);
while (true)//循环接受Socket
{
System.out.println("服务端开启,等待客户端建立连接。");
socket = serverSocket.accept();
ipInfo = socket.getInetAddress().getHostAddress().toString();
System.out.println(ipInfo+" Connected! ");
new Thread(new Task(socket)).start();//并且每次接收到Socket之后,就要新建一个线程以达到多次返回数据接受数据的目的
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public class Task implements Runnable
{
private Socket socket;
public Task(Socket socket)
{
this.socket = socket;
}
@Override
public void run()
{
try
{
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(ipInfo);
String code = bufferedReader.readLine();//客户端先发送一个标志,说明是登录还是返回
if (code.equals("0"))
{
login();
}
else
regist();
code = bufferedReader.readLine();
System.out.println(code);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public void login()
{
String result;
String status;
PrintWriter printWriter = null;
if (isAdmin)//确定找到的用户的身份
{
status = "管理员";
}
else
status = "一般用户";
try
{
readFile(infofile);//先读文件
account = bufferedReader.readLine();//客户端传回来的帐号密码
passwd = bufferedReader.readLine();
User user = new User(account, passwd);//封装对象
if (isExists(user, false))//找到了
{
result = "登录成功,身份:" + status;//传回相关信息
}
else
{
result = "登录失败,请查验帐号密码!";
}
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(result);//返回客户端
} catch (IOException e)
{
e.printStackTrace();
}
}
public void regist()
{
PrintWriter printWriter = null;
String status = null;
try
{
printWriter = new PrintWriter(socket.getOutputStream(), true);
account = bufferedReader.readLine();//客户端传回来的帐号密码
passwd = bufferedReader.readLine();
inviteCode = bufferedReader.readLine();
User user = new User(account, passwd);
readFile(infofile);
if (!isExists(user, true))
{
user.setAdmin(inviteCode);
if (user.isAdmin())
{
status = "管理员";
}
else
status = "一般用户";
hashSet.add(user);//没找到就添加进Set
writeFile(infofile);
printWriter.println("注册成功!身份:" + status);
}
else
{
printWriter.println("注册失败,用户已存在!");
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public void readFile(File file)
{
ObjectInputStream objectInputStream = null;
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(socket.getOutputStream());
objectInputStream = new ObjectInputStream(new FileInputStream(file));//读取密码文件
hashSet = (HashSet) objectInputStream.readObject();//信息是以hashSet的形式存放在文件中
} catch (IOException e)
{
if (hashSet == null)
{
hashSet = new HashSet<>();//程序第一次运行时添加进的hashMap是null,需要新实例化一个
writeFile(infofile);//然后再写进去
}
} catch (ClassNotFoundException e)
{
printWriter.println("数据文件异常,请检查文件!");
}
}
public void writeFile(File file)
{
PrintWriter printWriter = null;
ObjectOutputStream objectOutputStream = null;
try
{
objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));//对象写入流
objectOutputStream.writeObject(hashSet);//将hashSet写入文件
printWriter = new PrintWriter(socket.getOutputStream());
} catch (IOException e)
{
printWriter.println("数据文件异常,请检查文件!");
}
}
public boolean isExists(User user, boolean isRegister)
{
String account = user.getAccount();
String passwd = user.getPasswd();
Iterator iterator = hashSet.iterator();
while (iterator.hasNext())
{
User stu = (User) iterator.next();
isAdmin = stu.isAdmin();
if (stu.getAccount().equals(account))//如果找到了相同用户名
{
if (isRegister)//注册的话
{
return true;//已经找到了
}
return stu.getPasswd().equals(passwd);//登陆的话还要比较密码是否相同
}
}
return false;//没找到就是假
}
public void setAdminKey(String string)
{
adminKey = string;
}
public String getAdminKey()
{
return adminKey;
}
public static void main(String[] args)
{
Server server = new Server("KangYh is very handsome!");
}
}
class User implements Serializable
{
private String account;
private String passwd;
private boolean isAdmin = false;
public User(String account, String passwd)
{
this.account = account;
this.passwd = passwd;
}
public String getAccount()
{
return account;
}
public void setAccount(String account)
{
this.account = account;
}
public String getPasswd()
{
return passwd;
}
public void setPasswd(String passwd)
{
this.passwd = passwd;
}
public boolean isAdmin()
{
return isAdmin;
}
public void setAdmin(String string)
{
if (string.equals(new Server("KangYh is very handsome!").getAdminKey()))
{
isAdmin = true;
}
}
@Override
public int hashCode()
{
return account.hashCode() + passwd.hashCode() * 3;
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof User))
{
return false;
}
User user = (User) obj;
return account.equals(user.account);
}
}
|
package net.h2.web.core.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Configuration
@PropertySources(value = {@PropertySource("classpath:file.properties")})
public class FileConfig {
@Autowired
private Environment environment;
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver result = new CommonsMultipartResolver();
String maxSize = environment.getProperty("file.upload.max.size");
if(maxSize.toLowerCase().endsWith("k"))
result.setMaxUploadSize(Long.valueOf(maxSize.substring(0,maxSize.length() - 1)) * 1024);
else
result.setMaxUploadSize(200 * 1024);//200K
return result;
}
}
|
class Circle{
int radius;
public Cricle(int radius) {
this.radius = radius;
}
public double getArea() {
return 3.14*radius*radius;
}
}
public class CircleArray {
public static void main(String ar[]) {
Circle[] c;
c = new Circle[5];
for(int i = 0;i<=4;i++) {
}
}
}
|
package dictionary;
public class Main {
public static void main(String[] args) {
// Test your dictionary here
MindfulDictionary dict = new MindfulDictionary("src/words.txt");
dict.load();
dict.add("onet", "mendy");
dict.save();
}
}
|
package mainpackage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Admin extends Users {
List<Program> Programs = new ArrayList<Program>();
public Admin(String username, String name, String surname) {
super(username, name, surname, "Admin");
}
// Create a new User
public static void CreateUser() {
Scanner scan = new Scanner(System.in);
Boolean flag = true;
String t = null;
System.out.println("Fill in the fields to continue the registration!");
System.out.println("Enter Username:");
String un = scan.nextLine(); // Read user input
System.out.println("Enter Name:");
String n = scan.nextLine(); // Read user input
System.out.println("Enter Surname:");
String s = scan.nextLine(); // Read user input
while(flag)
{
System.out.println("Enter type(Client,Admin,Seller):");
t = scan.nextLine(); // Read user input
if (t.equals("Client") || t.equals("Admin") || t.equals("Seller")){
flag = false;
}
}
//TODO add user to db
switch (t){
case "Client":
var client = new Client(un, n, s);
// client.Register(un, n, s, t);
break;
case "Admin":
var admin = new Admin(un, n, s);
break;
case "Seller":
var seller = new Seller(un, n, s);
}
}
// Print all progrm
public void ShowPrograms() {
for( int i = 0; i < Programs.size(); i++)
{
printObject(Programs.get(i));
}
}
// Delete an existing User
public void DeleteUser(String un, String type){
//TODO delete user from db
}
// Creates new package
public void CreateProgram() throws IOException{
//TODO create new package and add to db
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
String name = scan.nextLine(); // Read user input
System.out.println("Enter number for free calls per month:");
int FCPM = Integer.parseInt(scan.nextLine()); // Read user input
System.out.println("Enter number for free messages per moth:");
int FMPM = Integer.parseInt(scan.nextLine()); // Read user input
System.out.println("Can client call abroad?");
int CCA = Integer.parseInt(scan.nextLine()); // Read user input
System.out.println("Enter price per month:");
int PPMo = Integer.parseInt(scan.nextLine()); // Read user input
System.out.println("Enter price per message: ");
int PPMe = Integer.parseInt(scan.nextLine()); // Read user input
System.out.println("Enter price per call:");
int PPC = Integer.parseInt(scan.nextLine()); // Read user input
Program prog = new Program(name, FCPM, FMPM, CCA, PPMo, PPMe, PPC);
Programs.add(prog);
}
public void DeleteProgram(){
//TODO delete a package from the db
}
public void printObject(Object object) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(object));
}
}
|
package saudacoes;
import saudacoes.Saudacao;
public class TestaSaudacao {
public static void main(String[] args) {
Saudacao saudacao = new Saudacao();
saudacao.texto = "Boa noite";
saudacao.destinatario = "Someone";
System.out.println(saudacao.obterSaudacao());
}
}
|
/*
Things I've learned:
- Check corner cases
- In this case, the case where the center is less than either one of the sides
*/
import java.util.*;
import java.io.*;
public class cf491a{
public static void main(String [] args) throws IOException{
InputReader in = new InputReader("cf491a.in");
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int d = in.nextInt();
if(d - (a + b - c) >= 1){
if(c <= b && c <= a)
System.out.println(d - (a + b - c));
else
System.out.println(-1);
}
else{
System.out.println(-1);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(String s) {
try{
reader = new BufferedReader(new FileReader(s), 32768);
}
catch (Exception e){
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
}
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
package am.main.data.jaxb.am.logger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the am.main.data.jaxb.am.logger package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _AMLogger_QNAME = new QName("", "AM-Logger");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: am.main.data.jaxb.am.logger
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link AMLogger }
*
*/
public AMLogger createAMLogger() {
return new AMLogger();
}
/**
* Create an instance of {@link LoggerGroup }
*
*/
public LoggerGroup createLoggerGroup() {
return new LoggerGroup();
}
/**
* Create an instance of {@link AMLoggerConfig }
*
*/
public AMLoggerConfig createAMLoggerConfig() {
return new AMLoggerConfig();
}
/**
* Create an instance of {@link LoggerData }
*
*/
public LoggerData createLoggerData() {
return new LoggerData();
}
/**
* Create an instance of {@link LoggerProperty }
*
*/
public LoggerProperty createLoggerProperty() {
return new LoggerProperty();
}
/**
* Create an instance of {@link AMApplications }
*
*/
public AMApplications createAMApplications() {
return new AMApplications();
}
/**
* Create an instance of {@link AMApplication }
*
*/
public AMApplication createAMApplication() {
return new AMApplication();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link AMLogger }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "AM-Logger")
public JAXBElement<AMLogger> createAMLogger(AMLogger value) {
return new JAXBElement<AMLogger>(_AMLogger_QNAME, AMLogger.class, null, value);
}
}
|
package top.kylewang.bos.dao.transit;
import org.springframework.data.jpa.repository.JpaRepository;
import top.kylewang.bos.domain.transit.InOutStorageInfo;
/**
* @author Kyle.Wang
* 2018/1/13 0013 16:26
*/
public interface InOutStorageInfoRepository extends JpaRepository<InOutStorageInfo,Integer> {
}
|
package Model.MakingPackage;
import Model.*;
import java.util.List;
public class Make {
public void makeStudent(String username, List<Student> list){
Student s = new Student(username);
list.add(s);
}
public void makeCourse(String name, int unit, int capacity, int start, int end, Day day, String professor, List<Course> list){
Course c = new Course(name, unit, capacity, start, end, day, professor);
list.add(c);
}
public void makeFood(String name, int price, List<Food> list){
Food f = new Food(name, price);
list.add(f);
}
public void makeProfessor(String username, List<Professor> list){
Professor p = new Professor(username);
list.add(p);
}
public void makeBook(String title, String author, String publisher, List<Book> list){
Book b = new Book(title, author, publisher);
list.add(b);
}
}
|
// Sun Certified Java Programmer
// Chapter 1, P75_5
// Declarations and Access Control
package pkgA;
public class Foo {
int a = 5;
protected int b = 6;
public int c = 7;
}
|
class Main {
public static void main(String[] a) {
System.out.println(3);
}
}
class Simple {
int fun() {
int x;
boolean a;
boolean b;
int[] arr;
if (2 < 3) {
{
x = 5;
while (x < 7) {
a = false;
if (x < 3) {
b = a && true;
} else {
a = true;
}
b = a && true;
}
}
} else {
{
a = true;
if (a) {
arr = new int[5];
} else {
arr = new int[7];
}
x = arr[3];
}
}
return 0;
}
}
|
/**
* Author: obullxl@gmail.com
* Copyright (c) 2004-2014 All Rights Reserved.
*/
package com.github.obullxl.lang.utils;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
/**
* 缓冲服务
* <p/>
* 目前基于EhCache框架!
*
* @author obullxl@gmail.com
* @version $Id: CacheUtils.java, V1.0.1 2014年1月6日 下午4:07:42 $
*/
public final class CacheUtils {
/** Logger */
// private static final Logger logger = LogUtils.get();
/** 单例 */
private static CacheManager cmngt;
/**
* 获取CacheManager单例
*/
public static CacheManager getCacheManager() {
if (cmngt != null) {
return cmngt;
}
synchronized (CacheUtils.class) {
if (cmngt != null) {
return cmngt;
} else {
cmngt = new EhCacheCacheManager(net.sf.ehcache.CacheManager.getInstance());
return cmngt;
}
}
}
/**
* 清理缓存
*/
public static void clear(String cache) {
getCacheManager().getCache(cache).clear();
}
/**
* 删除数据
*/
public static void evict(String cache, Object key) {
getCacheManager().getCache(cache).evict(key);
}
/**
* 获取数据
*/
@SuppressWarnings("unchecked")
public static <T> T get(String cache, Object key) {
ValueWrapper vw = getCacheManager().getCache(cache).get(key);
if (vw != null) {
return (T) vw.get();
}
return null;
}
/**
* 缓存数据
*/
public static void put(String cache, Object key, Object value) {
getCacheManager().getCache(cache).put(key, value);
}
}
|
package com.ibiscus.myster.service.assignment;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import com.ibiscus.myster.model.company.PointOfSale;
import com.ibiscus.myster.model.security.User;
import com.ibiscus.myster.model.shopper.Shopper;
import com.ibiscus.myster.model.survey.*;
import com.ibiscus.myster.model.survey.category.Category;
import com.ibiscus.myster.model.survey.category.CategoryDto;
import com.ibiscus.myster.model.survey.data.DiscreteResponse;
import com.ibiscus.myster.model.survey.data.OpenResponse;
import com.ibiscus.myster.model.survey.data.Response;
import com.ibiscus.myster.model.survey.item.*;
import com.ibiscus.myster.repository.category.CategoryRepository;
import com.ibiscus.myster.repository.security.UserRepository;
import com.ibiscus.myster.repository.shopper.ShopperRepository;
import com.ibiscus.myster.repository.survey.data.ResponseRepository;
import com.ibiscus.myster.repository.survey.item.SurveyItemRepository;
import com.ibiscus.myster.service.communication.MailSender;
import com.ibiscus.myster.service.survey.data.DatastoreService;
import com.ibiscus.myster.web.admin.survey.SurveyAssignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import com.ibiscus.myster.repository.assignment.AssignmentRepository;
import static com.google.common.collect.Lists.newArrayList;
import static com.ibiscus.myster.model.survey.Assignment.Builder.newAssignmentBuilder;
import static com.ibiscus.myster.model.survey.Assignment.STATE.*;
import static java.lang.String.format;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.Validate.isTrue;
@Service
public class AssignmentService {
private static final Logger logger = LoggerFactory.getLogger(AssignmentService.class);
private final AssignmentRepository assignmentRepository;
private final CategoryRepository categoryRepository;
private final SurveyItemRepository surveyItemRepository;
private final ResponseRepository responseRepository;
private final UserRepository userRepository;
private final ShopperRepository shopperRepository;
private final MailSender mailSender;
private final DatastoreService datastoreService;
private final String siteUrl = "http://localhost:8080/";
public AssignmentService(AssignmentRepository assignmentRepository, CategoryRepository categoryRepository,
SurveyItemRepository surveyItemRepository, ResponseRepository responseRepository,
UserRepository userRepository, ShopperRepository shopperRepository, MailSender mailSender,
DatastoreService datastoreService) {
this.assignmentRepository = assignmentRepository;
this.categoryRepository = categoryRepository;
this.surveyItemRepository = surveyItemRepository;
this.responseRepository = responseRepository;
this.userRepository = userRepository;
this.shopperRepository = shopperRepository;
this.mailSender = mailSender;
this.datastoreService = datastoreService;
}
public List<TaskDescription> findByUsername(String username) {
List<TaskDescription> assignmentDescriptors = newArrayList();
User user = userRepository.getByUsername(username);
Shopper shopper = shopperRepository.getByUserId(user.getId());
List<Assignment> assignments = assignmentRepository.findByShopperId(shopper.getId());
for (Assignment assignment : assignments) {
if (!assignment.isClosed()) {
PointOfSale pointOfSale = assignment.getPointOfSale();
assignmentDescriptors.add(new TaskDescription(assignment.getId(), assignment.getSurvey().getName(),
pointOfSale.getLocation(), assignment.getPayRate(), FINISHED.equals(assignment.getState())));
}
}
return assignmentDescriptors;
}
public SurveyTask getSurveyTask(long assignmentId) {
Assignment assignment = get(assignmentId);
validateAccess(assignment);
Survey survey = assignment.getSurvey();
List<CategoryDto> taskCategories = newArrayList();
List<Category> categories = categoryRepository.findBySurveyId(survey.getId());
int index = 0;
for (Category category : categories) {
List<AbstractSurveyItem> items = surveyItemRepository.findByCategoryIdOrderByPositionAsc(category.getId());
List<SurveyItemDto> taskItems = newArrayList();
for (SurveyItem item : items) {
Optional<Response> response = Optional.ofNullable(
responseRepository.findByAssignment(assignment.getId(), item.getId()));
String value = null;
if (response.isPresent()) {
value = response.get().getValue();
}
if (item instanceof SingleChoice) {
List<ChoiceDto> choicesDtos = ((SingleChoice) item).getChoices()
.stream()
.map(choice -> new ChoiceDto(choice.getDescription(), choice.getId()))
.collect(Collectors.toList());
taskItems.add(new SingleChoiceDto(item.getId(), item.getClass().getSimpleName(), item.getTitle(),
item.getDescription(), value, index++, response.isPresent(), choicesDtos));
} else if (item instanceof FileItem) {
taskItems.add(new FilesDto(item.getId(), item.getClass().getSimpleName(), item.getTitle(),
item.getDescription(), value, index++, response.isPresent()));
} else {
taskItems.add(new SurveyItemDto(item.getId(), item.getClass().getSimpleName(), item.getTitle(),
item.getDescription(), value, index++, response.isPresent()));
}
}
taskCategories.add(new CategoryDto(category.getName(), taskItems));
}
TaskDescription taskDescription = new TaskDescription(assignmentId, survey.getName(),
assignment.getPointOfSale().getLocation(), assignment.getPayRate(), FINISHED.equals(assignment.getState()));
java.util.Date visitDate = new java.util.Date();
if (assignment.getVisitDate() != null) {
visitDate = new java.util.Date(assignment.getVisitDate().getTime());
}
LocalTime inTime = LocalTime.now();
if (assignment.getInTime() != null) {
inTime = assignment.getInTime().toLocalTime();
}
LocalTime outTime = LocalTime.now();
if (assignment.getOutTime() != null) {
outTime = assignment.getOutTime().toLocalTime();
}
return new SurveyTask(assignmentId, taskDescription, taskCategories, visitDate, inTime, outTime);
}
private void validateAccess(Assignment assignment) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails principal = (UserDetails) authentication.getPrincipal();
User user = userRepository.getByUsername(principal.getUsername());
Shopper shopper = shopperRepository.getByUserId(user.getId());
isTrue(assignment.getShopperId() == shopper.getId(),
format("The current logged shopper %s cannot view the assignment id: %s", principal.getUsername(),
assignment.getId()));
}
public Assignment get(long id) {
return assignmentRepository.findOne(id);
}
public void assign(SurveyAssignment surveyAssignment) {
Assignment assignment = new Assignment(surveyAssignment.getSurvey(), surveyAssignment.getShopper().getId(),
surveyAssignment.getPointOfSale());
assignmentRepository.save(assignment);
User user = userRepository.findOne(surveyAssignment.getShopper().getUserId());
String bodyMessage = getAssignmentBodyMessage(assignment, surveyAssignment.getSurvey(),
surveyAssignment.getPointOfSale());
mailSender.sendMail(user.getUsername(), "Asignacion de encuesta", bodyMessage);
}
public void save(long assignmentId, CompletedSurvey completedSurvey) {
logger.info("Saving survey assignment {}", assignmentId);
completedSurvey.getCompletedSurveyItems().stream()
.filter(completedSurveyItem -> completedSurveyItem.hasContent())
.forEach(completedSurveyItem -> save(assignmentId, completedSurveyItem));
Assignment assignment = assignmentRepository.findOne(assignmentId);
Assignment filledAssignment = newAssignmentBuilder()
.withAssignment(assignment)
.withVisitDate(new Date(completedSurvey.getVisitDate().getTime()))
.withInTime(Time.valueOf(LocalTime.of(completedSurvey.getInHour(), completedSurvey.getInMinute())))
.withOutTime(Time.valueOf(LocalTime.of(completedSurvey.getOutHour(), completedSurvey.getOutMinute())))
.withState(completedSurvey.isComplete() ? FINISHED : PENDING)
.build();
assignmentRepository.save(filledAssignment);
}
private void save(long assignmentId, CompletedSurveyItem completedSurveyItem) {
logger.info("Saving survey item {} in assignment {}", completedSurveyItem.getSurveyItemId(), assignmentId);
Optional<Response> responseValue = Optional.ofNullable(
responseRepository.findByAssignment(assignmentId,
completedSurveyItem.getSurveyItemId()));
if (completedSurveyItem.isFilesResponse()) {
if (!isBlank(completedSurveyItem.getValue())) {
newArrayList(completedSurveyItem.getValue().split(","))
.stream()
.filter(s -> !completedSurveyItem.getValidValues().contains(s))
.forEach(s -> datastoreService.delete(s));
}
if (completedSurveyItem.getFiles().stream().filter(file -> !file.isEmpty()).findAny().isPresent()) {
StringJoiner fileValues = new StringJoiner(",");
completedSurveyItem.getValidValues().stream().forEach(s -> fileValues.add(s));
completedSurveyItem.getFiles().stream()
.filter(file -> !file.isEmpty())
.forEach(file -> fileValues.add(datastoreService.save("shopncheck/" + assignmentId + "/", file)));
completedSurveyItem.setValue(fileValues.toString());
}
}
Response response;
if (responseValue.isPresent()) {
if (completedSurveyItem.isDiscrete()) {
response = new DiscreteResponse(responseValue.get().getId(), assignmentId, completedSurveyItem.getSurveyItemId(),
Long.valueOf(completedSurveyItem.getValue()));
} else {
response = new OpenResponse(responseValue.get().getId(), assignmentId, completedSurveyItem.getSurveyItemId(),
completedSurveyItem.getValue());
}
} else {
if (completedSurveyItem.isDiscrete()) {
response = new DiscreteResponse(assignmentId, completedSurveyItem.getSurveyItemId(),
Long.valueOf(completedSurveyItem.getValue()));
} else {
response = new OpenResponse(assignmentId, completedSurveyItem.getSurveyItemId(),
completedSurveyItem.getValue());
}
}
responseRepository.save(response);
}
private String getAssignmentBodyMessage(Assignment assignment, Survey survey, PointOfSale pointOfSale) {
StringBuilder builder = new StringBuilder("Se le ha asignado la siguiente encuesta: ")
.append(survey.getName())
.append("<br/><br/>")
.append("Punto de venta: ")
.append(pointOfSale.getLocation().getAddress())
.append("<br/><br/>")
.append("Se puede ver la encuesta completada en el siguiente link: ")
.append(siteUrl)
.append("shopper/#!assignment/fill/")
.append(assignment.getId());
return builder.toString();
}
public void close(long assignmentId) {
Assignment assignment = assignmentRepository.findOne(assignmentId);
validateAccess(assignment);
Assignment sentAssignment = newAssignmentBuilder()
.withAssignment(assignment)
.withState(CLOSED)
.build();
assignmentRepository.save(sentAssignment);
}
}
|
package com.gcit.training.library.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.gcit.training.library.Books;
import com.gcit.training.library.Genre;
public class GenreDAO extends BaseDAO<Genre> {
public GenreDAO(Connection c){
this.conn = c;
}
public void create(Genre genre) throws SQLException{
save("insert into tbl_genre (genre_name) values(?)",
new Object[] { genre.getGenre_name()});
}
public List<Genre> read() throws SQLException {
return (List<Genre>) readResultSet("select * from tbl_genre");
}
public Genre readOne(int genreid) throws SQLException {
List<Genre> list = (List<Genre>) readAllResultSet("select * from tbl_genre where genre_id = ?",
new Object[] {genreid});
if(list != null && list.size()>0)
return list.get(0);
else
return null;
}
public void update(Genre genre) throws SQLException{
save("update tbl_genre set genre_name = ? where genre_id=?",
new Object[] { genre.getGenre_name(), genre.getGenreid()});
}
public void delete(Genre genre) throws SQLException{
save("delete from tbl_genre where genre_id = ?",
new Object[] {genre.getGenreid()});
}
@Override
public List<Genre> mapResults(ResultSet rs) throws SQLException {
List<Genre> list = new ArrayList<Genre>();
BooksDAO bDAO = new BooksDAO(conn);
while(rs.next()){
Genre g = new Genre();
g.setGenreid(rs.getInt("genre_id"));
g.setGenre_name(rs.getString("genre_name"));
//set book list
List<Books> booklist = (List<Books>) bDAO.readFirstLevel("select * from tbl_book where bookId in (select bookId from tbl_book_genres where genre_id = ?)",
new Object[] {g.getGenreid()});
g.setBooks(booklist);
list.add(g);
}
return list;
}
@Override
public List<Genre> mapFirstLevelResults(ResultSet rs) throws SQLException {
List<Genre> list = new ArrayList<Genre>();
while(rs.next()){
Genre g = new Genre();
g.setGenreid(rs.getInt("genre_id"));
g.setGenre_name(rs.getString("genre_name"));
list.add(g);
}
return list;
}
public List<Genre> getGenresByName(String genreToSearch)
throws SQLException {
genreToSearch = "%" + genreToSearch + "%";
return (List<Genre>) readFirstLevel(
"select * from tbl_genre where genre_name like ?",
new Object[] { genreToSearch });
}
public List<Genre> page(int pageNo) throws SQLException {
return (List<Genre>) readResultSet("select * from tbl_genre LIMIT " + (pageNo-1)*5 + ",5");
}
public int count() throws SQLException {
return count("select count(*) from tbl_genre");
}
}
|
package biz.infosoft.bellweather.DAL;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import biz.infosoft.bellweather.R;
public class LocationDAL {
private static final int imgId = R.drawable.airplane;
// sample Points of Interest (POI) location
public static final LinkedHashSet<String> arrTitle = new LinkedHashSet<String>()
{{
add("New York");
add("Los Angeles");
add("Mexico City");
add("London");
add("Berlin");
add("Paris");
add("Rome");
add("Moscow");
add("Amsterdam");
add("Tokyo");
}};
// sample woeid (Where On Earth ID)
public static final LinkedHashSet<Integer> arrWoeid = new LinkedHashSet<Integer>()
{{
add(2459115);
add(2442047);
add(116545);
add(44418);
add(638242);
add(615702);
add(721943);
add(2122265);
add(727232);
add(1118370);
}};
// mock POI image
public static final List<Integer> arrImgLocation = new ArrayList<Integer>()
{{
add(imgId); add(imgId); add(imgId); add(imgId);add(imgId);
add(imgId); add(imgId); add(imgId); add(imgId); add(imgId);
}};
}
|
package com.simple.msg;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import com.simple.msg.message.MsgFactory;
import com.simple.msg.message.MsgManager;
public class MainActivity extends AppCompatActivity {
private MsgManager mMsgManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMsgManager = MsgFactory.getMsgManager(this);
mMsgManager.init();
}
public void add(View view){
EditText viewById = (EditText) findViewById(R.id.phone);
mMsgManager.haveNewMsg(viewById.getText().toString() , "--");
mMsgManager.haveNewMsg(viewById.getText().toString() , "bind");
}
}
|
package com.atn.app.webservices;
public interface PromotionExpireWebServiceListener {
public abstract void onFailed(int paramInt, String paramString);
public abstract void onSuccess(String paramString);
}
|
package com.zking.ssm.service;
import com.zking.ssm.model.Customer;
import com.zking.ssm.model.Order;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @anthor 小李
* @ddddddd
* @company 郴州
* @create 2020-11-27 19:28
*/
public class ICustomerServiceTest extends BaseTestCast {
@Autowired
private ICustomerService customerService;
private Customer customer;
@Before
public void setUp() throws Exception {
customer=new Customer();
}
@Test
public void insert() {
customer.setCustomerId(null);
customer.setCustomerName("kk");
customerService.insert(customer);
}
@Test
public void insertSelective() {
}
@Test
public void selectByPrimaryKey() {
Customer c= customerService.selectByPrimaryKey(5);
System.out.println(c);
}
@Test
public void queryOrderByCust() {
customer.setCustomerId(2);
List<Customer> lst=customerService.queryOrderByCust(customer);
lst.forEach(c->{
System.out.println(c.getOrders());
List<Order> list=c.getOrders();
list.forEach(o->{
System.out.println(o);
});
});
}
}
|
package com.tencent.mm.g.c;
import android.content.ContentValues;
import android.database.Cursor;
import com.tencent.mm.sdk.e.c;
public abstract class et extends c {
private static final int cTC = "timeStamp".hashCode();
private static final int cTF = "link".hashCode();
private static final int cTG = "imgUrl".hashCode();
public static final String[] ciG = new String[0];
private static final int ciP = "rowid".hashCode();
private static final int clt = "recordId".hashCode();
private static final int cnf = "title".hashCode();
private static final int cnh = "source".hashCode();
private boolean cTA = true;
private boolean cTD = true;
private boolean cTE = true;
private boolean clq = true;
private boolean cnb = true;
private boolean cnd = true;
public String field_imgUrl;
public String field_link;
public String field_recordId;
public String field_source;
public long field_timeStamp;
public String field_title;
public final void d(Cursor cursor) {
String[] columnNames = cursor.getColumnNames();
if (columnNames != null) {
int length = columnNames.length;
for (int i = 0; i < length; i++) {
int hashCode = columnNames[i].hashCode();
if (clt == hashCode) {
this.field_recordId = cursor.getString(i);
this.clq = true;
} else if (cTF == hashCode) {
this.field_link = cursor.getString(i);
} else if (cnf == hashCode) {
this.field_title = cursor.getString(i);
} else if (cnh == hashCode) {
this.field_source = cursor.getString(i);
} else if (cTG == hashCode) {
this.field_imgUrl = cursor.getString(i);
} else if (cTC == hashCode) {
this.field_timeStamp = cursor.getLong(i);
} else if (ciP == hashCode) {
this.sKx = cursor.getLong(i);
}
}
}
}
public final ContentValues wH() {
ContentValues contentValues = new ContentValues();
if (this.clq) {
contentValues.put("recordId", this.field_recordId);
}
if (this.cTD) {
contentValues.put("link", this.field_link);
}
if (this.cnb) {
contentValues.put("title", this.field_title);
}
if (this.cnd) {
contentValues.put("source", this.field_source);
}
if (this.cTE) {
contentValues.put("imgUrl", this.field_imgUrl);
}
if (this.cTA) {
contentValues.put("timeStamp", Long.valueOf(this.field_timeStamp));
}
if (this.sKx > 0) {
contentValues.put("rowid", Long.valueOf(this.sKx));
}
return contentValues;
}
}
|
package com.uphyca.stetho_realm.delegate;
import com.facebook.stetho.inspector.jsonrpc.JsonRpcException;
import com.facebook.stetho.inspector.jsonrpc.JsonRpcPeer;
import com.facebook.stetho.inspector.jsonrpc.JsonRpcResult;
import com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain;
import com.facebook.stetho.inspector.protocol.ChromeDevtoolsMethod;
import com.facebook.stetho.json.ObjectMapper;
import com.facebook.stetho.json.annotation.JsonProperty;
import org.json.JSONObject;
import java.util.regex.Pattern;
public class Database implements ChromeDevtoolsDomain {
private final ObjectMapper objectMapper;
private final com.facebook.stetho.inspector.protocol.module.Database database;
private final com.uphyca.stetho_realm.Database realmDatabase;
private final Pattern databaseNamePattern;
public Database(com.facebook.stetho.inspector.protocol.module.Database database, com.uphyca.stetho_realm.Database realmDatabase, Pattern databaseNamePattern) {
this.objectMapper = new ObjectMapper();
this.database = database;
this.realmDatabase = realmDatabase;
this.databaseNamePattern = databaseNamePattern;
}
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public void enable(JsonRpcPeer peer, JSONObject params) {
database.enable(peer, params);
realmDatabase.enable(peer, params);
}
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public void disable(JsonRpcPeer peer, JSONObject params) {
database.disable(peer, params);
realmDatabase.disable(peer, params);
}
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer, JSONObject params) throws JsonRpcException {
GetDatabaseTableNamesRequest request = objectMapper.convertValue(params, GetDatabaseTableNamesRequest.class);
if (databaseNamePattern.matcher(request.databaseId).find()) {
return realmDatabase.getDatabaseTableNames(peer, params);
} else {
return database.getDatabaseTableNames(peer, params);
}
}
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult executeSQL(JsonRpcPeer peer, JSONObject params) {
ExecuteSQLRequest request = objectMapper.convertValue(params, ExecuteSQLRequest.class);
if (databaseNamePattern.matcher(request.databaseId).find()) {
return realmDatabase.executeSQL(peer, params);
} else {
return database.executeSQL(peer, params);
}
}
private static class GetDatabaseTableNamesRequest {
@JsonProperty(required = true)
public String databaseId;
}
private static class ExecuteSQLRequest {
@JsonProperty(required = true)
public String databaseId;
@JsonProperty(required = true)
@SuppressWarnings("unused")
public String query;
}
}
|
public class PlayingCard { // begin PlayingCard data type
// public constants
public static final int ACE = 1, JACK = 11, KNIGHT = 12, QUEEN = 13,
KING = 14;
public static final int[] RANKS = {ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10,
JACK, KNIGHT, QUEEN, KING}; // rank order of playing cards
public static final int SPADES = 0, HEARTS = 1, DIAMONDS = 2, CLUBS = 3;
public static final int[] SUITS = {SPADES, HEARTS, DIAMONDS, CLUBS};
// private constant
private static final char[][][] pictographs; // card pictographs
// as surrogate pairs
// rankIndex of playing card
private final int rankIndex; // invariant: 0 <= rankIndex < RANKS.length()
// suitIndex of playing card:
private final int suitIndex; // invariant: 0 <= suitIndex < SUITS.length()
// initialise the playing card pictographs
static {
pictographs = new char [SUITS.length][RANKS.length][2];
int codePoint = 0x1F0A1; // ace of spades unicode code point
for(int suitIndex = 0; suitIndex < SUITS.length; suitIndex++) {
for(int rankIndex = 0; rankIndex < RANKS.length; rankIndex++ ) {
pictographs[suitIndex][rankIndex][0] =
Character.highSurrogate(codePoint + rankIndex);
pictographs[suitIndex][rankIndex][1] =
Character.lowSurrogate(codePoint + rankIndex);
}
codePoint = codePoint + 0x10; // ace of heart then diamonds then cluds
}
}
// construct playing card with a rank and suit;
// where rankIndex corresponds to the following (ranks): 0 (ACE), 1 (2),
// 2 (3), ..., 8 (9), 9 (10), 10 (JACK), 11 (KNIGHT), 12 (QUEEN), 13 (KING);
// and where suitIndex corresponds to the following (suits): 0 (SPADES),
// 1 (HEARTS), 2 (DIAMONDS), 3 (CLUBS).
public PlayingCard(int rankIndex, int suitIndex) {
this.rankIndex = (0 <= rankIndex && rankIndex < RANKS.length) ? rankIndex : 0;
this.suitIndex = (0 <= suitIndex && suitIndex < SUITS.length) ? suitIndex : 0;
}
// is rank of current card less than rank of given card?
public boolean isRankLessThan(PlayingCard card) {
return (RANKS[this.rankIndex] < RANKS[card.rankIndex]);
}
// is rank of current card equal to rank of given card?
public boolean isRankEqual(PlayingCard card) {
return (RANKS[this.rankIndex] == RANKS[card.rankIndex]);
}
// convert to a String value description of the card.
@Override
public String toString() {
int rank = RANKS[rankIndex];
String rankAsString =
(rank == ACE) ? "Ace" :
(rank < JACK) ? ("" + rank) :
(rank == JACK) ? "Jack" :
(rank == KNIGHT) ? "Knight" :
(rank == QUEEN) ? "Queen" :
(rank == KING) ? "King" : "Error!";
int suit = SUITS[suitIndex];
String suitAsString =
(suit == SPADES) ? "Spades" :
(suit == HEARTS) ? "Hearts" :
(suit == DIAMONDS) ? "Diamonds" :
(suit == CLUBS) ? "Clubs" : "Error!";
return rankAsString + " of " + suitAsString;
}
// convert to a String value pictograph of the card.
public String toPictograph() {
String cardPictograph = "" +
pictographs[suitIndex][rankIndex][0] +
pictographs[suitIndex][rankIndex][1];
return cardPictograph;
}
// test the PlayingCard data type by constructing a playing card of
// each rank and suit and printing a pictograph of the card to the
// standard output.
public static void main(String[] args) {
for(int suitIndex = 0; suitIndex < SUITS.length; suitIndex++) {
for(int rankIndex = 0; rankIndex < RANKS.length; rankIndex++) {
PlayingCard card = new PlayingCard(rankIndex, suitIndex);
System.out.print(card.toPictograph() + " ");
}
System.out.println();
}
}
} // end PlayingCard data type
|
package com.bluemingo.bluemingo.domain;
import org.springframework.security.core.GrantedAuthority;
public class RoleVO implements GrantedAuthority{
private static final long serialVersionUID = 1L;
private String role_name;
public RoleVO(String rolename){
this.role_name = rolename;
}
@Override
public String getAuthority() {
return this.role_name;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public String toString(){
return ""+role_name;
}
}
|
package ru.abusabir.test;
/**
* Oleg
* 23.10.2016
*/
public enum CardName {
CARD1, CARD2, CARD3, CARD4, CARD5, CARD6, CARD7, CARD8, CARD9, CARD10,
CARD11, CARD12, CARD13, CARD14, CARD15, CARD16, CARD17, CARD18, CARD19, CARD20,
CARD21, CARD22, CARD23, CARD24
}
|
package com.kashu.controller.base;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.kashu.domain.User;
@Controller
@SessionAttributes({"currentURL"})
public class HomeController {
@RequestMapping(value = "/home")
public ModelAndView home(HttpServletRequest request, HttpServletResponse response){
ModelAndView mv = new ModelAndView();
mv.addObject("message", "Hello Reader!");
mv.addObject("currentURL", "/home");
response.addCookie(new Cookie("cookie_currentURL","/home"));
mv.setViewName("home");
return mv;
}
/*
public String rrregister_form(Model model){
User user = new User();
model.addAttribute("user", user);
return "users/register";
}
*/
@RequestMapping(value = "/part")
public ModelAndView part(){
ModelAndView mv = new ModelAndView();
mv.addObject("message", "I am part.jsp 噗");
mv.setViewName("part");
return mv;
}
@RequestMapping(value = "/user_only")
public ModelAndView user_only(HttpServletRequest request, HttpServletResponse response){
ModelAndView mv = new ModelAndView();
//mv.addObject("title", "林爸是/user_only.jsp的title");
mv.addObject("message", "I am user_only.jsp 我噗我噗");
mv.addObject("currentURL", "/user_only");
response.addCookie(new Cookie("cookie_currentURL","/user_only"));
mv.setViewName("user_only");
return mv;
}
}
|
package com.pangpang6.books.base;
/**
* Created by jiangjiguang on 2017/9/1.
*/
public class BlackDog extends Dog {
}
|
package dk.aarhustech.edu.rainbow.horario;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import java.util.Arrays;
public class MapView extends SubsamplingScaleImageView {
private static final String TAG = MapView.class.getSimpleName();
private final Paint paint = new Paint();
private OnClickLocationListener onClickLocationListener;
private String floor;
private MapFragment.Room[] rooms;
public MapView(Context context) {
this(context, null);
}
public MapView(Context context, AttributeSet attr) {
super(context, attr);
initialise();
final GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
if (isReady() && onClickLocationListener != null) {
onClickLocationListener.onClickLocation(viewToSourceCoord(event.getX(), event.getY()));
}
return true;
}
});
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
}
public void setRooms(MapFragment.Room[] rooms) {
this.rooms = rooms;
if (!floor.equals(rooms[0].getFloor())) {
setFloor(rooms[0].getFloor());
}
initialise();
invalidate();
}
private void initialise() {
paint.setColor(getResources().getColor(R.color.highlight));
paint.setStyle(Paint.Style.FILL);
// float density = getResources().getDisplayMetrics().densityDpi;
// pin = BitmapFactory.decodeResource(this.getResources(), R.drawable.pin);
// float w = (density/4000f) * pin.getWidth();
// float h = (density/4000f) * pin.getHeight();
// pin = Bitmap.createScaledBitmap(pin, (int)w, (int)h, true);
}
public void setFloor(String name) {
floor = name;
setImage(ImageSource.asset("maps/" + name + ".png"));
rooms = null;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!isReady()) {
return;
}
//paint.setAntiAlias(true);
if (rooms != null) {
for (MapFragment.Room room : rooms) {
drawRoom(canvas, room);
}
}
}
private void drawRoom(Canvas canvas, MapFragment.Room room) {
PointF[] points = room.getPoints();
Path path = new Path();
PointF start = sourceToViewCoord(points[0]);
path.reset();
path.moveTo(start.x, start.y);
for (int i = 1; i < points.length; i++) {
PointF p = sourceToViewCoord(points[i]);
path.lineTo(p.x, p.y);
}
path.lineTo(start.x, start.y);
path.close();
canvas.drawPath(path, paint);
}
void setOnClickLocationListener(OnClickLocationListener listener) {
this.onClickLocationListener = listener;
}
public String getFloor() {
return floor;
}
interface OnClickLocationListener {
void onClickLocation(PointF point);
}
}
|
package geometries;
import java.util.List;
import primitives.*;
/**
* Geometries interface, represent all the geometries
* @author Rina and Tamar
*
*/
public abstract class Geometry implements Intersectable
{
/**
* Geometry values
*/
protected Color _emission;
protected Material _material;
/**
* Geometry constructor
* @param emission
*/
public Geometry(Color emission)
{
_emission = new Color(emission);
_material = new Material(0,0,0);
}
/**
* default constructor
*/
public Geometry()
{
this(Color.BLACK);
_material = new Material(0,0,0);
}
/**
* Geometry constructor
* @param emission
* @param material
*/
public Geometry(Color emission, Material material)
{
_emission = new Color(emission);
_material = new Material(material.getKD(),material.getKS(),material.getShin());
}
/**
* function to get emission
*
* @return color
*/
public Color getEmission() {return _emission;}
/**
* abstract function to get normal
*
* @param point
* @return vector
*/
abstract public Vector getNormal(Point3D p);
/**
* function to get material
*
* @return material
*/
public Material getMaterial() {return _material;}
//public void setEmission()
}
|
package com.albabich.grad;
import com.albabich.grad.model.User;
import com.albabich.grad.to.UserTo;
import com.albabich.grad.util.UserUtil;
public class AuthorizedUser extends org.springframework.security.core.userdetails.User {
private UserTo userTo;
public AuthorizedUser(User user) {
super(user.getEmail(), user.getPassword(), true, true, true, true, user.getRoles());
this.userTo = UserUtil.asTo(user);
}
public int getId() {
return userTo.getId();
}
@Override
public String toString() {
return userTo.toString();
}
}
|
package com.smxknife.cache.custom.jsr107;
import com.smxknife.cache.custom.CsCache;
import com.smxknife.cache.custom.store.impl.BasicDataStore;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.configuration.CacheEntryListenerConfiguration;
import javax.cache.configuration.Configuration;
import javax.cache.integration.CompletionListener;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.EntryProcessorException;
import javax.cache.processor.EntryProcessorResult;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @author smxknife
* 2020/6/8
*/
public class Cs107Cache<K, V> implements Cache<K, V> {
private CsCache<K, V> csCache = new CsCache<>(new BasicDataStore<>());
private volatile boolean isClosed;
private String cacheName;
private CsCache107Manager cacheManager;
private Configuration<K, V> configuration;
public Cs107Cache(CsCache107Manager cacheManager, String cacheName, Configuration<K, V> configuration) {
this.cacheManager = cacheManager;
this.cacheName = cacheName;
this.configuration = configuration;
this.isClosed = false;
}
@Override
public V get(K k) {
return csCache.get(k);
}
@Override
public Map<K, V> getAll(Set<? extends K> set) {
return null;
}
@Override
public boolean containsKey(K k) {
return csCache.get(k) != null;
}
@Override
public void loadAll(Set<? extends K> set, boolean b, CompletionListener completionListener) {
}
@Override
public void put(K k, V v) {
}
@Override
public V getAndPut(K k, V v) {
return null;
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
}
@Override
public boolean putIfAbsent(K k, V v) {
return false;
}
@Override
public boolean remove(K k) {
return false;
}
@Override
public boolean remove(K k, V v) {
return false;
}
@Override
public V getAndRemove(K k) {
return null;
}
@Override
public boolean replace(K k, V v, V v1) {
return false;
}
@Override
public boolean replace(K k, V v) {
return false;
}
@Override
public V getAndReplace(K k, V v) {
return null;
}
@Override
public void removeAll(Set<? extends K> set) {
}
@Override
public void removeAll() {
}
@Override
public void clear() {
csCache.clear();
}
@Override
public <C extends Configuration<K, V>> C getConfiguration(Class<C> aClass) {
return null;
}
@Override
public <T> T invoke(K k, EntryProcessor<K, V, T> entryProcessor, Object... objects) throws EntryProcessorException {
return null;
}
@Override
public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> set, EntryProcessor<K, V, T> entryProcessor, Object... objects) {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public CacheManager getCacheManager() {
return this.cacheManager;
}
@Override
public synchronized void close() {
if (!isClosed) {
isClosed = true;
if (cacheManager != null) {
cacheManager.releaseCache(cacheName);
}
csCache.clear();
}
}
@Override
public boolean isClosed() {
return this.isClosed;
}
@Override
public <T> T unwrap(Class<T> aClass) {
return null;
}
@Override
public void registerCacheEntryListener(CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration) {
}
@Override
public void deregisterCacheEntryListener(CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration) {
}
@Override
public Iterator<Entry<K, V>> iterator() {
return null;
}
}
|
package hu.bme.aut.exhibitionexplorer;
import android.content.Intent;
import android.graphics.PointF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.dlazaro66.qrcodereaderview.QRCodeReaderView;
import hu.bme.aut.exhibitionexplorer.data.Artifact;
public class QrReaderActivity extends AppCompatActivity implements QRCodeReaderView.OnQRCodeReadListener{
private QRCodeReaderView qrCodeReaderView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr_reader);
qrCodeReaderView = (QRCodeReaderView) findViewById(R.id.qrdecoderview);
qrCodeReaderView.setOnQRCodeReadListener(this);
qrCodeReaderView.setBackCamera();
}
@Override
public void onQRCodeRead(String text, PointF[] points) {
Intent data = new Intent();
data.putExtra(Artifact.KEY_ARTIFACT_ID, text);
setResult(RESULT_OK, data);
finish();
}
}
|
package asscry;
import java.io.File;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
public class RSAGenerate {
public static final int KEY_SIZE = 4096;
public static void saveKeyFile() {
try{
//String filePath = "C:\\";
//FileUtil.createDirectory("KeyRSA","//storage//emulated//0//Crypto//");
File directory = new File("");
String fileName = directory.getAbsolutePath();
Security.addProvider(new BouncyCastleProvider());
KeyPair keyPair = generateRSAKeyPair();
RSAPrivateKey priv = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey pub = (RSAPublicKey) keyPair.getPublic();
writePemFile(priv, "RSA PRIVATE KEY", fileName+"\\rsa_priv.txt");
writePemFile(pub, "RSA PUBLIC KEY", fileName+"\\rsa_pub.txt");
}catch (Exception e){
e.printStackTrace();
}
}
private static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
generator.initialize(KEY_SIZE);
KeyPair keyPair = generator.generateKeyPair();
return keyPair;
}
private static void writePemFile(Key key, String description, String filename)
throws FileNotFoundException, IOException {
PemFileWrite pemFile = new PemFileWrite(key, description);
pemFile.write(filename);}
}
|
package com.file;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/WriteFile")
public class WriteFile extends HttpServlet{
private static final long serialVersionUID = 1L;
public WriteFile(){
super();
//TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
//TODO Auto-generated method stub
this.doPost(request,response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
//设置页面的文档类型和字符集,页面中的字符所采用的字符集
response.setContentType("text/html;charset=UTF-8");
//设置页面的编码方式,即以什么样的编码方式来保存页面文件
response.setCharacterEncoding("UTF-8");
//从response中获得PrintWriter类的对象,以用于向页面输出信息
PrintWriter out = response.getWriter();
String fileName = "temp.txt";//文件相对路径
String filePath = this.getServletContext().getRealPath(fileName);//文件绝对路径
//使用文件的绝对路径打开文件,如果文件不存在则创建文件
File file = new File(filePath);
//使用打开的文件对象,创建FileWriter类的实例
FileWriter writer = new FileWriter(file);
//使用打开的文件对象,创建BufferedWriter类的实例
BufferedWriter bufferedWriter = new BufferedWriter(writer);
//通过BufferedWriter类的实例,向文件中写入信息
bufferedWriter.write("J2EE课程");
bufferedWriter.newLine();
bufferedWriter.write("Servlet写文件");
//刷新缓存,将缓存中的内容写入到文件中
bufferedWriter.flush();
bufferedWriter.close();
writer.close();
out.print("<font-size='2'>文件写入完毕,路径:"+file.getAbsolutePath()+"</font>");
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.operations.facades.populator;
import de.hybris.platform.commercefacades.order.data.OrderData;
import de.hybris.platform.commercefacades.product.data.ProductData;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.enumeration.EnumerationService;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import de.hybris.platform.servicelayer.dto.converter.Converter;
import de.hybris.platform.workflow.model.WorkflowActionModel;
import java.util.Date;
import com.cnk.travelogix.common.core.enums.ToDoTaskStatus;
import com.cnk.travelogix.operations.data.WorkflowActionData;
/**
*
*/
public class ToDoTaskPopulator implements Populator<WorkflowActionModel, WorkflowActionData>
{
private Converter<OrderModel, OrderData> orderConverter;
private EnumerationService enumerationService;
@Override
public void populate(final WorkflowActionModel source, final WorkflowActionData target) throws ConversionException
{
if (source != null)
{
target.setCode(source.getCode());
target.setName(source.getName());
target.setAssignedUser(source.getPrincipalAssigned().getUid());
target.setSecondaryAssignedUser(
source.getSecondaryAssignedUser() != null ? source.getSecondaryAssignedUser().getUid() : "");
if (source.getDueDate() != null)
{
target.setDueDate(source.getDueDate() != null ? source.getDueDate() : null);
if (source.getDueDate().before(new Date()))
{
target.setTaskStatus(enumerationService.getEnumerationName(ToDoTaskStatus.OVERDUE));
final long diff = new Date().getTime() - source.getDueDate().getTime();
final int noofdays = (int) (diff / (1000 * 24 * 60 * 60));
target.setOverdueDays(new Integer(noofdays));
}
else
{
target.setTaskStatus(enumerationService.getEnumerationName(source.getTaskStatus()));
target.setOverdueDays(new Integer(0));
}
}
else
{
target.setTaskStatus(enumerationService.getEnumerationName(source.getTaskStatus()));
}
target.setStatus(source.getStatus() != null ? source.getStatus().getCode() : "");
target.setAssignedTo(source.getAssignedTo() != null ? source.getAssignedTo().getUid() : "");
target.setIsRead(source.getReadbyAssignedUser());
target.setTaskType(source.getTaskType() != null ? source.getTaskType().getCode() : "");
target.setTaskCategory(source.getTaskCategory() != null ? source.getTaskCategory().getCode() : "");
target.setPriority(source.getAlertPriority() != null ? source.getAlertPriority().getCode() : "");
target.setClientCategory(source.getClientCategory() != null ? source.getClientCategory().getCode() : "");
target.setClientSubCategory(source.getClientSubCategory() != null ? source.getClientSubCategory().getCode() : "");
target.setClientType(source.getClientType() != null ? source.getClientType().getCode() : "");
target.setFunctionalArea(source.getFunctionalArea() != null ? source.getFunctionalArea().getCode() : "");
target.setSuggestedAction(source.getSuggestedAction());
target.setParent(source.getParent() != null ? source.getParent().getCode() : "");
target.setLockedBy(source.getLockedBy() != null ? source.getLockedBy().getName() : "");
if (source.getDueDate() != null)
{
//final Date date = source.getDueDate();
//target.setDueDate(date.getDate() + "-" + date.getMonth() + "-" + date.getYear());
}
target.setParent(source.getParent() != null ? source.getParent().getCode() : "");
if (source.getOrder() != null)
{
target.setOrder(getOrderConverter().convert(source.getOrder()));
}
target.setDesc(source.getDescription());
if (source.getProduct() != null)
{
final ProductModel model = source.getProduct();
final ProductData product = new ProductData();
product.setCode(model.getCode());
product.setName(model.getName());
target.setProduct(product);
}
if (source.getCompany() != null)
{
target.setCompanyName(source.getCompany().getName());
}
if (source.getMarket() != null)
{
target.setCompanyMarket(source.getMarket().getName());
}
}
}
/**
* @return the orderConverter
*/
public Converter<OrderModel, OrderData> getOrderConverter()
{
return orderConverter;
}
/**
* @param orderConverter
* the orderConverter to set
*/
public void setOrderConverter(final Converter<OrderModel, OrderData> orderConverter)
{
this.orderConverter = orderConverter;
}
/**
* @return the enumerationService
*/
public EnumerationService getEnumerationService()
{
return enumerationService;
}
/**
* @param enumerationService
* the enumerationService to set
*/
public void setEnumerationService(final EnumerationService enumerationService)
{
this.enumerationService = enumerationService;
}
}
|
import java.util.*;
public class ClientTest {
public static void main(String[] s) {
Client c1 = new Client("jkb", "lrnz", "street name and other things");
Client c2 = new Client("Oscar", "Kilo", "rd name and some things");
ClientList list = ClientList.instance();
list.insertClient(c1);
list.insertClient(c2);
Iterator<Client> clients = list.getClients();
while (clients.hasNext()) {
System.out.println(clients.next()); // test id autogen
}
c1.setClientId("test007");
System.out.println("client id should be test007 : " + c1.getClientId());
c1.setFirstName("Alpha");
c1.setLastName("Bravo");
System.out.println("client name should be Alpha Bravo : " + c1.getFirstName() + " " + c1.getLastName());
c1.setAddress("court yard name and city");
System.out.println("client address should be court yard name and city : " + c1.getAddress());
System.out.println(list.toString());
// set and show balance
c1.setBalance(101.01);
System.out.println("client's balance should be 101.01 : " + c1.getBalance());
// shopping cart test
System.out.println("Client Shopping Cart Test:");
Product p1 = new Product("product1", 1, 1.00, .50);
Product p2 = new Product("product2", 1, 4.99, 2.49);
System.out.println("Test Products:");
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println("'2 of product1' to be added to " + c1.getFirstName() + " " + c1.getLastName() + "'s shopping cart:");
System.out.println("'5 of product2' to be added to " + c2.getFirstName() + " " + c2.getLastName() + "'s shopping cart:");
c1.getShoppingCart().insertProductToCart(p1, 2);
c2.getShoppingCart().insertProductToCart(p2, 5);
// print c1's shopping cart contents
System.out.println(c1.getFirstName() + " " + c1.getLastName() + "'s Shopping Cart contents:");
Iterator<ShoppingCartItem> cart1Iterator = c1.getShoppingCart().getShoppingCartProducts();
while (cart1Iterator.hasNext()) {
System.out.println(cart1Iterator.next());
}
// print c2's shopping cart contents
System.out.println(c2.getFirstName() + " " + c2.getLastName() + "'s Shopping Cart contents:");
Iterator<ShoppingCartItem> cart2Iterator = c2.getShoppingCart().getShoppingCartProducts();
while (cart2Iterator.hasNext()) {
System.out.println(cart2Iterator.next());
}
}
}
|
package pl.edu.agh.internetshop.MoneyTransfer;
import pl.edu.agh.internetshop.MoneyTransfer.MoneyTransfer;
import pl.edu.agh.internetshop.PaymentMethod;
public interface MoneyTransferPaymentTransaction extends PaymentMethod {
boolean validate(MoneyTransfer transfer);
}
|
package com.hiwes.cores.other.deepreview4offlinecomputing.SparkMLlib.java.DecisionTree;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.mllib.clustering.KMeans;
import org.apache.spark.mllib.clustering.KMeansModel;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.mllib.tree.DecisionTree;
import org.apache.spark.mllib.tree.model.DecisionTreeModel;
import org.apache.spark.mllib.util.MLUtils;
import org.apache.spark.storage.StorageLevel;
import scala.Tuple2;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class JavaDecisionTreeExample {
private static String allTaxiDataPath = "file:///Users/hiwes/data/mllib/AlltaxiDatas.txt";
private static String kmeansDataPath = "file:///Users/hiwes/data/mllib/kmeansData.txt";
private static String decisionModelPath = "file:///Users/hiwes/data/model/decisionTree/bike/DecisionTreeModel";
// 实现字符串变量化
public static Vector parseVector(String s) {
String[] array = s.split(",");
double[] values = new double[array.length];
for (int i = 0; i < array.length; i++) {
values[i] = Double.parseDouble(array[i]);
}
return Vectors.dense(values);
}
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaDecisionTreeExample").setMaster("local[2]");
JavaSparkContext jsc = new JavaSparkContext(conf);
/**
* 读取本地数据文件,将数据文件进行筛选过滤,提取晚上19-21点之间的行车数据,并获取上车经纬度
* 将经纬度进行聚类,计算结果写入本地文件。
*/
// 0.获取所有数据
JavaRDD<String> allDataRDD = jsc.textFile(allTaxiDataPath);
// 1.过滤时间,获取19点-21点间的出行记录
JavaRDD<String> periodData = allDataRDD.filter(s -> {
String[] arr = s.split(",");
String[] array1 = (arr[1].split(" "))[1].split(":");
return (Integer.parseInt(array1[0]) >= 19 && Integer.parseInt(array1[0]) <= 21);
}).persist(StorageLevel.MEMORY_AND_DISK());
// 2.将目标文件通过筛选,得到需要的经纬度
JavaRDD<String> latitudeAndLongitudeData = periodData.map(s -> {
String[] arr = s.split(",");
return arr[5] + "," + arr[6];
});
// 3.建立JavaRDD<Vector>得到结果用来传入K—means算法
JavaRDD<Vector> VectorData = latitudeAndLongitudeData.map(s -> parseVector(s)).persist(StorageLevel.MEMORY_AND_DISK());
List<Vector> collect3 = VectorData.collect();
// 4.使用K—Means算法,创建KMeans模型。
int bestNumClusters = 0;
int bestNumIterations = 0;
double bestWSSSE = 1.0;
for (int k = 10; k <= 30; k++) {
for (int i = 15; i <= 25; i++) {
KMeansModel kmeansmodel = KMeans.train(VectorData.rdd(), k, i);
double WSSSE = kmeansmodel.computeCost(VectorData.rdd());
if (WSSSE < bestWSSSE) {
bestWSSSE = WSSSE;
bestNumClusters = k;
bestNumIterations = i;
}
}
}
KMeansModel bestKmeansmodel = KMeans.train(VectorData.rdd(), bestNumClusters, bestNumIterations);
System.out.println("The minimum loss function is: " + bestWSSSE);
// 5.实现字符串的本地化文件保存
String newData = ""; // 创建空字符串用来进行字符串拼接
for (Vector v : collect3) {
int number = bestKmeansmodel.predict(v);
newData += String.valueOf(number) + "," + v.toString().substring(1, v.toString().length() - 1) + "\n";
}
try {
Scanner input = new Scanner(newData);
FileOutputStream fos = new FileOutputStream(kmeansDataPath);
while (input.hasNext()) {
String a = input.next();
fos.write((a + "\r\n").getBytes());
}
fos.close();
input.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
periodData.unpersist();
VectorData.unpersist();
/**
* 加载kmeans文件,并将数据切分,20%用作测试数据,80%作为训练数据用来生成Decision模型
*/
// 加载和解析数据文件
JavaRDD<LabeledPoint> data = MLUtils.loadLabeledPoints(jsc.sc(), kmeansDataPath).toJavaRDD();
// 将数据分成培训和测试集(20%用于测试)
JavaRDD<LabeledPoint>[] splits = data.randomSplit(new double[]{0.8, 0.2});
JavaRDD<LabeledPoint> trainingData = splits[0];
JavaRDD<LabeledPoint> testData = splits[1];
// 设置参数。
// 空的分类功能表明所有的特性都是连续的。
int numClasses = 20;
Map<Integer, Integer> categoricalFeaturesInfo = new HashMap<>();
String impurity = "gini";
int numDepth = 2;
int numBins = 10; //分支中的元素个数是多少
double testError = run(trainingData, numClasses, categoricalFeaturesInfo, impurity, numDepth, numBins, testData);
for (int Depth = 2; Depth <= 20; Depth++) {
for (int Bins = 10; Bins <= 100; Bins++) {
double testErr = run(trainingData, numClasses, categoricalFeaturesInfo, impurity, Depth, Bins, testData);
if (testErr < testError) {
testError = testErr;
numDepth = Depth;
numBins = Bins;
}
}
}
int resultDepth = numDepth;
int resultBins = numBins;
DecisionTreeModel decisionTreeModel = DecisionTree.trainClassifier(trainingData, numClasses, categoricalFeaturesInfo, impurity, resultDepth, resultBins);
double minTestError = run(trainingData, numClasses, categoricalFeaturesInfo, impurity, resultDepth, resultBins, testData);
System.out.println(minTestError);
decisionTreeModel.save(jsc.sc(), decisionModelPath);
jsc.close();
}
// 决策树方法
public static double run(JavaRDD<LabeledPoint> trainingData, int numClasses, Map<Integer, Integer> categoricalFeaturesInfo,
String impurity, int maxDepth, int maxBins, JavaRDD<LabeledPoint> testData) {
DecisionTreeModel model = DecisionTree.trainClassifier(trainingData, numClasses, categoricalFeaturesInfo, impurity, maxDepth, maxBins);
// 对测试实例进行评估,并计算测试错误
JavaPairRDD<Double, Double> predictionAndLabel = testData.mapToPair(p -> new Tuple2<>(model.predict(p.features()), p.label()));
double testErr = predictionAndLabel.filter(pl -> !pl._1().equals(pl._2())).count() / (double) testData.count();
return testErr;
}
}
|
package net.liuzd.spring.boot.v2.util;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class IPUtils {
private static final String UNKNOWN = "unknown";
public static String getIP(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (String ipStr : ips) {
if (!(UNKNOWN.equalsIgnoreCase(ipStr))) {
return ipStr;
}
}
}
return ip;
}
@SuppressWarnings("rawtypes")
public static String getIP() {
String serverIp = "";
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
for (InterfaceAddress i : ni.getInterfaceAddresses()) {
i.getAddress();
ip = InetAddress.getLocalHost();
if ((ip.isSiteLocalAddress()) && (!ip.isLoopbackAddress()) && (ip.getHostAddress().indexOf(
":") == -1)) {
serverIp = ip.getHostAddress();
break;
}
serverIp = "1";
}
}
} catch (SocketException e1) {
log.error("SocketException", e1);
} catch (UnknownHostException e) {
log.error("UnknownHostException", e);
}
return serverIp;
}
public static String getLocalIP() {
InetAddress addr = null;
String serverIp = "";
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
log.error("UnknownHostException", e);
}
if ((addr.isSiteLocalAddress()) && (!addr.isLoopbackAddress()) && (addr.getHostAddress().indexOf(":") == -1))
serverIp = addr.getHostAddress();
else {
serverIp = "0.0.0.0";
}
return serverIp;
}
}
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot.commands.Shooter;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.Constants.ShooterConstants;
import frc.robot.subsystems.BottomConveyor;
import frc.robot.subsystems.Shooter;
import frc.robot.subsystems.TopConveyor;
public class AutonomousShoot extends CommandBase {
private final Shooter m_shooter;
private final TopConveyor m_topConveyor;
private final BottomConveyor m_bottomConveyor;
private final double m_optimalVelocity;
private Timer m_conveyorTimer;
private boolean m_conveyorsRunning = false;
/**
* Creates a new AutonomousShoot.
*/
public AutonomousShoot(final Shooter shooter, final TopConveyor topConveyor, final BottomConveyor bottomConveyor,
final double optimalVelocity) {
m_shooter = shooter;
m_topConveyor = topConveyor;
m_bottomConveyor = bottomConveyor;
m_optimalVelocity = optimalVelocity;
addRequirements(m_shooter, m_topConveyor, m_bottomConveyor);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
m_shooter.startMotor();
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
// m_shooter.startMotor();
double currentVelocity = m_shooter.getVelocity();
if (Math.abs(
currentVelocity - m_optimalVelocity) <= (ShooterConstants.kVelocityTolerance / 100.0 * m_optimalVelocity)) {
// If within desired velocity for shooter, start conveyors
if (!m_conveyorsRunning) { // Start the timer if it hasn't already been started
m_conveyorsRunning = true;
if (m_conveyorTimer == null) { // Reset timer before starting timing
m_conveyorTimer = new Timer();
}
m_conveyorTimer.start();
}
m_topConveyor.conveyorIn();
m_bottomConveyor.conveyorIn();
} else if (m_conveyorsRunning) {
// Stop the conveyors if they've already started and pause timer
m_topConveyor.stopConveyor();
m_bottomConveyor.stopConveyor();
m_conveyorTimer.stop();
m_conveyorsRunning = false;
}
}
// Called once the command ends or is interrupted.
@Override
public void end(final boolean interrupted) {
m_shooter.stop();
m_topConveyor.stopConveyor();
m_bottomConveyor.stopConveyor();
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
if (m_conveyorTimer == null)
return false;
return m_conveyorTimer.get() > 5;
}
}
|
package com.sietecerouno.atlantetransportador.sections;
import android.app.ActionBar;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.sietecerouno.atlantetransportador.MainActivity;
import com.sietecerouno.atlantetransportador.R;
import com.sietecerouno.atlantetransportador.manager.Manager;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class DocumentsActivity extends AppCompatActivity
{
String TAG = "GIO";
TextView photo;
TextView cc;
TextView idCar;
TextView rut;
TextView tarjetaPropiedad;
TextView soat;
TextView tecnomecanica;
TextView car;
ImageView ok_photo;
ImageView ok_cc;
ImageView ok_idCar;
ImageView ok_rut;
ImageView ok_tarjetaPropiedad;
ImageView ok_soat;
ImageView ok_tecnomecanica;
ImageView ok_car;
FirebaseFirestore db;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_documents);
db = FirebaseFirestore.getInstance();
Manager.getInstance().actualContext = this;
//title
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_bar);
TextView title = (TextView) findViewById(R.id.action_bar_title);
title.setText("DOCUMENTOS");
//bg
ImageView bg = (ImageView) findViewById(R.id.bg);
Glide.with(bg.getContext()).load(R.drawable.bg_solo).into(bg);
//fields
photo = (TextView) findViewById(R.id.photo);
ok_photo = (ImageView) findViewById(R.id.ok_photo);
cc = (TextView) findViewById(R.id.cc);
ok_cc = (ImageView) findViewById(R.id.ok_cc);
idCar = (TextView) findViewById(R.id.idCar);
ok_idCar = (ImageView) findViewById(R.id.ok_idCar);
rut = (TextView) findViewById(R.id.rut);
ok_rut = (ImageView) findViewById(R.id.ok_rut);
tarjetaPropiedad = (TextView) findViewById(R.id.tarjetaPropiedad);
ok_tarjetaPropiedad = (ImageView) findViewById(R.id.ok_tarjetaPropiedad);
soat = (TextView) findViewById(R.id.soat);
ok_soat = (ImageView) findViewById(R.id.ok_soat);
tecnomecanica = (TextView) findViewById(R.id.tecnomecanica);
ok_tecnomecanica = (ImageView) findViewById(R.id.ok_tecnomecanica);
car = (TextView) findViewById(R.id.car);
ok_car = (ImageView) findViewById(R.id.ok_car);
if(!Manager.getInstance().isFirstV)
{
photo.setVisibility(View.GONE);
ok_photo.setVisibility(View.GONE);
cc.setVisibility(View.GONE);
ok_cc.setVisibility(View.GONE);
idCar.setVisibility(View.GONE);
ok_idCar.setVisibility(View.GONE);
rut.setVisibility(View.GONE);
ok_rut.setVisibility(View.GONE);
}
setInvisibleChecks();
checkFields();
TextView btn_next = (TextView) findViewById(R.id.btn_next);
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(Manager.getInstance().isFirstV)
{
registerVehicle();
registerUserDocuments();
Intent i = new Intent(DocumentsActivity.this, HomeActivity.class);
startActivity(i);
finish();
}else{
registerVehicle();
Intent i = new Intent(DocumentsActivity.this, HomeActivity.class);
i.putExtra("tab", "datos");
startActivity(i);
finish();
}
}
});
TextView photo = (TextView) findViewById(R.id.photo);
photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DocumentsActivity.this, DocumentWhitPhotoActivity.class);
i.putExtra("type", "photo");
startActivity(i);
finish();
}
});
TextView cc = (TextView) findViewById(R.id.cc);
cc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DocumentsActivity.this, DocumentWhitPhotoActivity.class);
i.putExtra("type", "cc");
startActivity(i);
finish();
}
});
TextView idcar = (TextView) findViewById(R.id.idCar);
idcar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DocumentsActivity.this, DocumentWhitPhotoActivity.class);
i.putExtra("type", "idCar");
startActivity(i);
finish();
}
});
TextView rut = (TextView) findViewById(R.id.rut);
rut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DocumentsActivity.this, DocumentWhitPhotoActivity.class);
i.putExtra("type", "rut");
startActivity(i);
finish();
}
});
TextView tarjetaPropiedad = (TextView) findViewById(R.id.tarjetaPropiedad);
tarjetaPropiedad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DocumentsActivity.this, DocumentWhitPhotoActivity.class);
i.putExtra("type", "tarjetaPropiedad");
startActivity(i);
finish();
}
});
TextView soat = (TextView) findViewById(R.id.soat);
soat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DocumentsActivity.this, DocumentWhitPhotoActivity.class);
i.putExtra("type", "soat");
startActivity(i);
finish();
}
});
TextView tecnomecanica = (TextView) findViewById(R.id.tecnomecanica);
tecnomecanica.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DocumentsActivity.this, DocumentWhitPhotoActivity.class);
i.putExtra("type", "tecnomecanica");
startActivity(i);
finish();
}
});
TextView car = (TextView) findViewById(R.id.car);
car.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DocumentsActivity.this, DocumentWhitPhotoActivity.class);
i.putExtra("type", "car");
startActivity(i);
finish();
}
});
}
private void setInvisibleChecks()
{
ok_tecnomecanica.setVisibility(View.INVISIBLE);
ok_soat.setVisibility(View.INVISIBLE);
ok_car.setVisibility(View.INVISIBLE);
ok_rut.setVisibility(View.INVISIBLE);
ok_idCar.setVisibility(View.INVISIBLE);
ok_photo.setVisibility(View.INVISIBLE);
ok_cc.setVisibility(View.INVISIBLE);
ok_tarjetaPropiedad.setVisibility(View.INVISIBLE);
}
private void checkFields()
{
if(Manager.getInstance().photoTemp_v_user_1.length() > 0)
ok_photo.setVisibility(View.VISIBLE);
if(Manager.getInstance().photoTemp_v_cc_1.length() > 0
&& Manager.getInstance().photoTemp_v_cc_2.length() > 0)
ok_cc.setVisibility(View.VISIBLE);
if(Manager.getInstance().photoTemp_v_id_1.length() > 0
&& Manager.getInstance().photoTemp_v_id_2.length() > 0)
ok_idCar.setVisibility(View.VISIBLE);
if(Manager.getInstance().photoTemp_v_rut_1.length() > 0)
ok_rut.setVisibility(View.VISIBLE);
if(Manager.getInstance().photoTemp_v_tp_1.length() > 0
&& Manager.getInstance().photoTemp_v_tp_2.length() > 0)
ok_tarjetaPropiedad.setVisibility(View.VISIBLE);
if(Manager.getInstance().photoTemp_v_soat_1.length() > 0)
ok_soat.setVisibility(View.VISIBLE);
if(Manager.getInstance().photoTemp_v_tec_1.length() > 0)
ok_tecnomecanica.setVisibility(View.VISIBLE);
if(Manager.getInstance().photoTemp_v_img_1.length() > 0
&& Manager.getInstance().photoTemp_v_img_2.length() > 0
&& Manager.getInstance().photoTemp_v_img_3.length() > 0
&& Manager.getInstance().photoTemp_v_img_4.length() > 0)
ok_car.setVisibility(View.VISIBLE);
}
private void registerUserDocuments()
{
FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
DocumentReference docRef = db.collection("usuarios").document(fbUser.getUid());
Map<String, Object> estado = new HashMap<>();
estado.put("pendiente", new Date());
Map<String, String> cc = new HashMap<>();
cc.put("f1", Manager.getInstance().photoTemp_v_cc_1);
cc.put("f2", Manager.getInstance().photoTemp_v_cc_2);
Map<String, String> id = new HashMap<>();
id.put("f1", Manager.getInstance().photoTemp_v_id_1);
id.put("f2", Manager.getInstance().photoTemp_v_id_2);
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("cedula", cc);
user.put("estado", estado);
user.put("foto", Manager.getInstance().photoTemp_v_user_1);
user.put("licencia", id);
user.put("user", docRef);
user.put("rut", Manager.getInstance().photoTemp_v_rut_1);
// Access a Cloud Firestore instance from your Activity
// Add a new document with a generated ID
db.collection("documentos").document()
.set(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void _void) {
Log.d(TAG, "DocumentSnapshot added with ID: " + _void);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
db.collection("usuarios")
.document(fbUser.getUid())
.update("foto", Manager.getInstance().photoTemp_v_user_1).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, "save foto!");
}
});
}
private void registerVehicle()
{
FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
DocumentReference docRef = db.collection("usuarios").document(fbUser.getUid());
Map<String, Object> estado = new HashMap<>();
estado.put("pendiente", new Date());
Map<String, String> tarjeta_propiedad = new HashMap<>();
tarjeta_propiedad.put("f1", Manager.getInstance().photoTemp_v_tp_1);
tarjeta_propiedad.put("f2", Manager.getInstance().photoTemp_v_tp_2);
Map<String, String> car = new HashMap<>();
car.put("f1", Manager.getInstance().photoTemp_v_img_1);
car.put("f2", Manager.getInstance().photoTemp_v_img_2);
car.put("f3", Manager.getInstance().photoTemp_v_img_3);
car.put("f4", Manager.getInstance().photoTemp_v_img_4);
Map<String, Object> user = new HashMap<>();
user.put("color", "");
//user.put("idUser", fbUser.getUid());
user.put("estado", estado);
user.put("modelo", "");
user.put("placa", "");
user.put("tipo", Manager.getInstance().idTempVSelected+1);
user.put("user", docRef);
user.put("soat", Manager.getInstance().photoTemp_v_soat_1);
user.put("tecnomecanica", Manager.getInstance().photoTemp_v_tec_1);
user.put("tarjeta_propiedad", tarjeta_propiedad);
user.put("fotos", car);
// Access a Cloud Firestore instance from your Activity
// Add a new document with a generated ID
db.collection("vehiculos").document()
.set(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void _void) {
Log.d(TAG, "DocumentSnapshot added with ID: " + _void);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
Manager.getInstance().actualContext = null;
}
}
|
package com.tencent.mm.plugin.product.ui;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.u;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.tencent.mm.platformtools.y;
import com.tencent.mm.platformtools.y.a;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
import java.util.List;
public final class g extends u {
private ArrayList<b> lSM;
private boolean lSN;
a lSO;
private List<String> lSq;
Context mContext;
class b implements a {
public ImageView bRk = null;
public String url;
public b(String str) {
this.url = str;
this.bRk = (ImageView) ((LayoutInflater) g.this.mContext.getSystemService("layout_inflater")).inflate(com.tencent.mm.plugin.wxpay.a.g.product_image_item, null);
this.bRk.setImageBitmap(y.a(new c(str)));
this.bRk.setOnClickListener(new 1(this, g.this));
y.a(this);
}
public final void m(String str, final Bitmap bitmap) {
x.d("MicroMsg.MallProductImageAdapter", str + ", bitmap = " + (bitmap == null));
if (this.url != null && str.equals(this.url)) {
this.bRk.post(new Runnable() {
public final void run() {
b.this.bRk.setImageBitmap(bitmap);
}
});
}
}
}
public g(Context context) {
this(context, (byte) 0);
}
private g(Context context, byte b) {
this.lSN = false;
this.lSO = null;
this.mContext = context;
this.lSq = null;
aK(this.lSq);
}
public final void aK(List<String> list) {
if (list != null) {
if (list.size() > 0) {
this.lSq = list;
}
if (this.lSM == null) {
this.lSM = new ArrayList();
} else {
this.lSM.clear();
}
for (String bVar : this.lSq) {
this.lSM.add(new b(bVar));
}
}
}
public final int getCount() {
if (this.lSq == null) {
return 0;
}
if (this.lSN) {
return Integer.MAX_VALUE;
}
return this.lSq.size();
}
public final boolean a(View view, Object obj) {
return view == obj;
}
public final void a(ViewGroup viewGroup, int i, Object obj) {
x.d("MicroMsg.MallProductImageAdapter", "destroy item");
if (this.lSM != null) {
viewGroup.removeView(((b) this.lSM.get(i)).bRk);
}
}
public final int k(Object obj) {
return -2;
}
public final Object b(ViewGroup viewGroup, int i) {
if (this.lSM == null) {
return super.b(viewGroup, i);
}
x.d("MicroMsg.MallProductImageAdapter", "data valid");
viewGroup.addView(((b) this.lSM.get(i)).bRk, 0);
return ((b) this.lSM.get(i)).bRk;
}
}
|
package com.commercetools.sunrise.shoppingcart;
import com.commercetools.sunrise.myaccount.CustomerSessionUtils;
import com.google.inject.Injector;
import io.sphere.sdk.carts.Cart;
import io.sphere.sdk.carts.CartState;
import io.sphere.sdk.carts.queries.CartQuery;
import io.sphere.sdk.client.SphereClient;
import io.sphere.sdk.queries.PagedResult;
import play.libs.concurrent.HttpExecutionContext;
import play.mvc.Http;
import javax.inject.Inject;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.function.UnaryOperator;
import static com.commercetools.sunrise.shoppingcart.CartSessionUtils.overwriteCartSessionData;
import static java.util.concurrent.CompletableFuture.completedFuture;
public class CartFinderBySession implements CartFinder<Http.Session> {
@Inject
private SphereClient sphereClient;
@Inject
private Injector injector;
@Inject
private HttpExecutionContext httpExecutionContext;
@Override
public CompletionStage<Optional<Cart>> findCart(final Http.Session session, final UnaryOperator<CartQuery> runHookOnCartQuery) {
final CompletionStage<Optional<Cart>> cartStage = fetchCart(session, runHookOnCartQuery);
cartStage.thenAcceptAsync(cart -> {
final MiniCartBeanFactory miniCartBeanFactory = injector.getInstance(MiniCartBeanFactory.class);
overwriteCartSessionData(cart.orElse(null), session, miniCartBeanFactory);
}, httpExecutionContext.current());
return cartStage;
}
private CompletionStage<Optional<Cart>> fetchCart(final Http.Session session, final UnaryOperator<CartQuery> runHookOnCartQuery) {
return buildQuery(session)
.map(runHookOnCartQuery)
.map(query -> sphereClient.execute(query)
.thenApply(PagedResult::head))
.orElseGet(() -> completedFuture(Optional.empty()));
}
private Optional<CartQuery> buildQuery(final Http.Session session) {
return CustomerSessionUtils.getCustomerId(session)
.map(this::buildQueryByCustomerId)
.map(Optional::of)
.orElseGet(() -> CartSessionUtils.getCartId(session)
.map(this::buildQueryByCartId))
.map(query -> query
.plusPredicates(cart -> cart.cartState().is(CartState.ACTIVE))
.plusExpansionPaths(c -> c.shippingInfo().shippingMethod()) // TODO use run hook on cart query instead
.plusExpansionPaths(c -> c.paymentInfo().payments())
.withSort(cart -> cart.lastModifiedAt().sort().desc())
.withLimit(1));
}
private CartQuery buildQueryByCartId(final String cartId) {
return CartQuery.of().plusPredicates(cart -> cart.id().is(cartId));
}
private CartQuery buildQueryByCustomerId(final String customerId) {
return CartQuery.of().plusPredicates(cart -> cart.customerId().is(customerId));
}
}
|
package com.pz.Dto;
import lombok.*;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PokojeZdjeciaDto {
private long id;
private long idPokoju;
private String zdjecie;
}
|
package com.example.demo.model.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class OrderedProductsDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public boolean addToOrdered(long order_id, long productId, long quantity) {
String sql = "INSERT INTO ordered_products (order_id, product_id, quantity) VALUES (?, ?, ?)";
return jdbcTemplate.update(sql, order_id, productId, quantity) > 0;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teg.file;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javafx.collections.ObservableList;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonReader;
import static teg.StartupConstants.PATH_DATA;
import teg.model.EPModel;
import javax.json.JsonWriter;
import teg.model.Component;
import teg.model.Content;
import teg.model.Font;
import teg.model.Hd;
import teg.model.HyperLink;
import teg.model.Img;
import teg.model.Paragraph;
import teg.model.Site;
import teg.model.Slide;
import teg.model.TList;
import teg.model.Vd;
/**
*
* @author HTC
*/
public class TEGFileMannager {
public static String JSON_STUDENT_NAME = "student_name";
public static String JSON_SITES = "sites";
public static String JSON_TITLE = "title";
public static String JSON_BANNER = "banner";
public static String JSON_CONTENTS = "contents";
public static String JSON_STYLE = "style";
public static String JSON_COMPONENT = "component";
public static String JSON_PARAGRAPH = "paragraph";
public static String JSON_TEXT = "text";
public static String JSON_HYPERLINKS = "hyperlinks";
public static String JSON_START_INDEX = "start_index";
public static String JSON_END_INDEX = "end_index";
public static String JSON_LINK = "link";
public static String JSON_HEADER = "header";
public static String JSON_LISTS = "lists";
public static String JSON_LIST_TEXT = "list_text";
public static String JSON_IMG = "img";
public static String JSON_IMAGE_NAME = "image_name";
public static String JSON_IMAGE_PATH = "image_path";
public static String JSON_IMAGE_ID = "imageID";
public static String JSON_HEIGHT = "height";
public static String JSON_WIDTH = "width";
public static String JSON_STATUS = "status";
public static String JSON_CAPTIONS = "captions";
public static String JSON_VIDEO = "video";
public static String JSON_VIDEO_NAME = "video_name";
public static String JSON_VIDEO_PATH = "video_path";
public static String JSON_VIDEo_CAPTIONS = "captions";
public static String JSON_SLIDES = "slides";
public static String JSON_FOOTER = "footer";
public static String JSON_FONT = "font";
public static String JSON_FONT_NAME = "name";
public static String JSON_FONT_PATH = "font_link";
public static String JSON_FONT_SIZE = "font_size";
public static String JSON_COLOR_THEME = "color_theme";
public static String JSON_LAYOUT = "layout";
public static String JSON_EXT = ".json";
public static String SLASH = "/";
public void saveEP(EPModel ePToSave, String path) throws IOException{
//String ePTitle = ""+ ePToSave.getStudentName();
//String jsonFilePath = PATH_DATA + SLASH + ePTitle + JSON_EXT;
String jsonFilePath = path;
OutputStream os = new FileOutputStream(jsonFilePath);
JsonWriter jsonWriter = Json.createWriter(os);
//try{
JsonArray sitesJsonArray = makeSitesJsonArray(ePToSave.getSites());
JsonObject courseJsonObject = Json.createObjectBuilder()
.add(JSON_STUDENT_NAME, ePToSave.getStudentName())
.add(JSON_SITES, sitesJsonArray)
.build();
// AND SAVE EVERYTHING AT ONCE
jsonWriter.writeObject(courseJsonObject);
//}catch (NullPointerException e) {
// System.out.println("WTF");
//}
}
public void loadEP(EPModel ePToLoad, String jsonFilePath) throws IOException {
// LOAD THE JSON FILE WITH ALL THE DATA
JsonObject json = loadJSONFile(jsonFilePath);
// NOW LOAD THE SITES
ePToLoad.reset();
ePToLoad.setStudentName(json.getString(JSON_STUDENT_NAME));
JsonArray jsonSitesArray = json.getJsonArray(JSON_SITES);
for (int i = 0; i < jsonSitesArray.size(); i++) {
JsonObject siteJso = jsonSitesArray.getJsonObject(i);
ePToLoad.addSite(siteJso.getString(JSON_TITLE),
siteJso.getString(JSON_FOOTER),
siteJso.getString(JSON_LAYOUT),
siteJso.getString(JSON_COLOR_THEME));
JsonObject bannerJso = siteJso.getJsonObject(JSON_BANNER);
ePToLoad.getSites().get(i).setBanner(bannerJso.getString(JSON_IMAGE_NAME),
bannerJso.getString(JSON_IMAGE_PATH)//,
//bannerJso.getString(JSON_TEXT)
);
JsonObject fontJso = siteJso.getJsonObject(JSON_FONT);
ePToLoad.getSites().get(i).setFont( fontJso.getString(JSON_FONT_NAME),
fontJso.getString(JSON_FONT_PATH),
fontJso.getString(JSON_FONT_SIZE));
JsonArray cJsA = siteJso.getJsonArray(JSON_CONTENTS);
for(int j = 0 ; j< cJsA.size(); j++){
JsonObject jsC = cJsA.getJsonObject(j);
ePToLoad.getSites().get(i).addContent(jsC.getString(JSON_STYLE));
//JsonObject cpJso = jsC.getJsonObject(JSON_COMPONENT);
JsonObject jsCP =jsC.getJsonObject(JSON_COMPONENT);
Component component = new Component();
JsonObject jsH = jsCP.getJsonObject(JSON_HEADER);
Hd hd = component.getHeader();
hd.text = jsH.getString(JSON_TEXT);
JsonArray hpA = jsH.getJsonArray(JSON_HYPERLINKS);
for(int inx = 0; inx < hpA.size(); inx++){
JsonObject hhp = hpA.getJsonObject(inx);
hd.addHyperLink(hhp.getString(JSON_START_INDEX),
hhp.getString(JSON_END_INDEX),
hhp.getString(JSON_LINK),
hhp.getString(JSON_TEXT));
}
JsonObject jsP = jsCP.getJsonObject(JSON_PARAGRAPH);
//component.setParagraph(jsP.getString(JSON_TEXT));
Paragraph paragraph = component.getParagraph();
paragraph.text = jsP.getString(JSON_TEXT);
JsonArray hpP = jsP.getJsonArray(JSON_HYPERLINKS);
for(int inx = 0; inx < hpP.size(); inx++){
JsonObject hhp = hpP.getJsonObject(inx);
paragraph.addHyperLink(hhp.getString(JSON_START_INDEX),
hhp.getString(JSON_END_INDEX),
hhp.getString(JSON_LINK),
hhp.getString(JSON_TEXT));
}
JsonArray jsL = jsCP.getJsonArray(JSON_LISTS);
for(int inx = 0; inx < jsL.size(); inx++){
JsonObject listJs = jsL.getJsonObject(inx);
TList list = new TList(listJs.getString(JSON_TEXT));
JsonArray hpL = listJs.getJsonArray(JSON_HYPERLINKS);
for (int jnx = 0; jnx < hpL.size(); jnx++) {
JsonObject hhp = hpL.getJsonObject(jnx);
list.addHyperLink(hhp.getString(JSON_START_INDEX),
hhp.getString(JSON_END_INDEX),
hhp.getString(JSON_LINK),
hhp.getString(JSON_TEXT));
}
component.getLists().add(list);
}
JsonObject jsI = jsCP.getJsonObject(JSON_IMG);
component.setImage( jsI.getString(JSON_IMAGE_NAME),
jsI.getString(JSON_IMAGE_PATH),
jsI.getString(JSON_STATUS),
jsI.getString(JSON_HEIGHT),
jsI.getString(JSON_WIDTH),
jsI.getString(JSON_CAPTIONS),
jsI.getString(JSON_IMAGE_ID));
JsonObject jsV = jsCP.getJsonObject(JSON_VIDEO);
component.setVideo( jsV.getString(JSON_VIDEO_NAME),
jsV.getString(JSON_VIDEO_PATH),
jsV.getString(JSON_CAPTIONS),
jsV.getString(JSON_HEIGHT),
jsV.getString(JSON_WIDTH));
JsonArray jsSS = jsCP.getJsonArray(JSON_SLIDES);
for(int jnx = 0; jnx < jsSS.size(); jnx++){
JsonObject jsS = jsSS.getJsonObject(jnx);
Slide slide = new Slide(jsS.getString(JSON_IMAGE_NAME),
jsS.getString(JSON_IMAGE_PATH),
jsS.getString(JSON_CAPTIONS));
component.slides.add(slide);
}
ePToLoad.getSites().get(i).getContents().get(j).setComponent(component);
/*for(int k = 0; k< cpJsA.size(); k++){
//content.addComponent();
JsonObject jsCP = cpJsA.getJsonObject(k);
Component component = new Component();
JsonObject jsH = jsCP.getJsonObject(JSON_HEADER);
Hd hd = component.getHeader();
hd.text = jsH.getString(JSON_TEXT);
JsonArray hpA = jsH.getJsonArray(JSON_HYPERLINKS);
for(int inx = 0; inx < hpA.size(); inx++){
JsonObject hhp = hpA.getJsonObject(inx);
hd.addHyperLink(hhp.getString(JSON_START_INDEX),
hhp.getString(JSON_END_INDEX),
hhp.getString(JSON_LINK));
}
JsonObject jsP = jsCP.getJsonObject(JSON_PARAGRAPH);
//component.setParagraph(jsP.getString(JSON_TEXT));
Paragraph paragraph = component.getParagraph();
paragraph.text = jsP.getString(JSON_TEXT);
JsonArray hpP = jsP.getJsonArray(JSON_HYPERLINKS);
for(int inx = 0; inx < hpP.size(); inx++){
JsonObject hhp = hpP.getJsonObject(inx);
paragraph.addHyperLink(hhp.getString(JSON_START_INDEX),
hhp.getString(JSON_END_INDEX),
hhp.getString(JSON_LINK));
}
JsonArray jsL = jsCP.getJsonArray(JSON_LISTS);
for(int inx = 0; inx < hpP.size(); inx++){
JsonObject listJs = jsL.getJsonObject(inx);
TList list = new TList(listJs.getString(JSON_TEXT));
JsonArray hpL = listJs.getJsonArray(JSON_HYPERLINKS);
for (int jnx = 0; jnx < hpL.size(); jnx++) {
JsonObject hhp = hpP.getJsonObject(jnx);
list.addHyperLink(hhp.getString(JSON_START_INDEX),
hhp.getString(JSON_END_INDEX),
hhp.getString(JSON_LINK));
}
component.getLists().add(list);
}
JsonObject jsI = jsCP.getJsonObject(JSON_IMG);
component.setImage( jsI.getString(JSON_IMAGE_NAME),
jsI.getString(JSON_IMAGE_PATH),
jsI.getString(JSON_STATUS),
jsI.getString(JSON_HEIGHT),
jsI.getString(JSON_WIDTH),
jsI.getString(JSON_CAPTIONS));
JsonObject jsV = jsCP.getJsonObject(JSON_VIDEO);
component.setVideo( jsV.getString(JSON_VIDEO_NAME),
jsV.getString(JSON_VIDEO_PATH),
jsV.getString(JSON_CAPTIONS),
jsV.getString(JSON_HEIGHT),
jsV.getString(JSON_WIDTH));
JsonArray jsSS = jsCP.getJsonArray(JSON_SLIDESHOW);
for(int jnx = 0; jnx < jsSS.size(); jnx++){
JsonObject jsS = jsSS.getJsonObject(jnx);
Slide slide = new Slide(jsS.getString(JSON_IMAGE_NAME),
jsS.getString(JSON_IMAGE_PATH),
jsS.getString(JSON_CAPTIONS));
component.slides.add(slide);
}
ePToLoad.getSites().get(i).getContents().get(j).addComponent(component);
}*/
}
}
}
private JsonObject loadJSONFile(String jsonFilePath) throws FileNotFoundException, IOException {
InputStream is = new FileInputStream(jsonFilePath);
JsonReader jsonReader = Json.createReader(is);
JsonObject json = jsonReader.readObject();
jsonReader.close();
is.close();
return json;
}
private JsonArray makeSitesJsonArray(ObservableList<Site> sites) {
JsonArrayBuilder jsb = Json.createArrayBuilder();
for (Site site : sites) {
JsonObject jso = makeSiteJsonObject(site);
jsb.add(jso);
}
JsonArray jA = jsb.build();
return jA;
}
private JsonObject makeSiteJsonObject(Site site) {
JsonObject jsb = makeBannerJsonObject(site);
JsonArray jsc = makeContentsJsonObject(site);
JsonObject jsf = makeFontJsonObject(site.getFont());
JsonObject jso = Json.createObjectBuilder()
.add(JSON_TITLE, site.getTitle())
.add(JSON_BANNER, jsb)
.add(JSON_CONTENTS, jsc)
.add(JSON_FOOTER, site.getFooter())
.add(JSON_LAYOUT, site.getLayout())
.add(JSON_FONT, jsf)
.add(JSON_COLOR_THEME, site.getColorTheme())
.build();
return jso;
}
private JsonObject makeBannerJsonObject(Site site){
JsonObject jso = Json.createObjectBuilder()
.add(JSON_IMAGE_NAME, site.getBanner().getName())
.add(JSON_IMAGE_PATH, site.getBanner().getPath())
.add(JSON_TEXT, site.getBanner().getText())
.build();
return jso;
}
private JsonArray makeContentsJsonObject(Site site) {
JsonArrayBuilder jsb = Json.createArrayBuilder();
for (Content content : site.getContents()) {
JsonObject jso = makeContentJsonObject(content);
jsb.add(jso);
}
JsonArray jA = jsb.build();
return jA;
}
private JsonObject makeContentJsonObject(Content content) {
JsonObject jsb = makeComponentJsonObject(content.getComponent());
JsonObject jso = Json.createObjectBuilder()
.add(JSON_STYLE, content.getStyle())
.add(JSON_COMPONENT, jsb)
.build();
return jso;
}
private JsonArray makeCompontentsJsonObject(ObservableList<Component> components) {
JsonArrayBuilder jsb = Json.createArrayBuilder();
for (Component component : components) {
JsonObject jso = makeComponentJsonObject(component);
jsb.add(jso);
}
JsonArray jA = jsb.build();
return jA;
}
private JsonObject makeComponentJsonObject(Component component){
JsonObject jsp = makeParagraphJsonObject(component.paragraph);
JsonArray jsl = makeListsJsonObject(component.lists);
JsonObject jsh = makeHeaderJsonObject(component.header);
JsonObject jsi = makeImageJsonObject(component.image);
JsonObject jsv = makeVideoJsonObject(component.video);
JsonArray jsss = makeSlidesJsonArray(component.slides);
JsonObject jso = Json.createObjectBuilder()
.add(JSON_PARAGRAPH, jsp)
.add(JSON_LISTS, jsl)
.add(JSON_HEADER, jsh)
.add(JSON_IMG, jsi)
.add(JSON_VIDEO, jsv)
.add(JSON_SLIDES, jsss)
.build();
return jso;
}
private JsonObject makeParagraphJsonObject(Paragraph paragraph) {
JsonArray jsa = makeHyperlinksJsonObject(paragraph.hyperlinks);
JsonObject jso = Json.createObjectBuilder()
.add(JSON_TEXT, paragraph.text)
.add(JSON_HYPERLINKS, jsa)
.build();
return jso;
}
private JsonArray makeHyperlinksJsonObject(ObservableList<HyperLink> hyperlinks) {
JsonArrayBuilder jsb = Json.createArrayBuilder();
for (HyperLink hyperlink : hyperlinks) {
JsonObject jso = makeHyperlinkJsonObject(hyperlink);
jsb.add(jso);
}
JsonArray jA = jsb.build();
return jA;
}
private JsonObject makeHyperlinkJsonObject(HyperLink hyperlink) {
JsonObject jso = Json.createObjectBuilder()
.add(JSON_START_INDEX, hyperlink.startIndex)
.add(JSON_END_INDEX, hyperlink.endIndex)
.add(JSON_LINK, hyperlink.link)
.add(JSON_TEXT, hyperlink.text)
.build();
return jso;
}
private JsonArray makeListsJsonObject(ObservableList<TList> lists) {
JsonArrayBuilder jsb = Json.createArrayBuilder();
for(TList list : lists){
JsonObject jso = makeListJsonObject(list);
jsb.add(jso);
}
JsonArray jA = jsb.build();
return jA;
}
private JsonObject makeListJsonObject(TList list) {
JsonArray jsa = makeHyperlinksJsonObject(list.hyperlinks);
JsonObject jso = Json.createObjectBuilder()
.add(JSON_TEXT, list.text)
.add(JSON_HYPERLINKS, jsa)
.build();
return jso;
}
private JsonObject makeHeaderJsonObject(Hd header) {
JsonArray jsa = makeHyperlinksJsonObject(header.hyperlinks);
JsonObject jso = Json.createObjectBuilder()
.add(JSON_TEXT, header.text)
.add(JSON_HYPERLINKS, jsa)
.build();
return jso;
}
private JsonObject makeImageJsonObject(Img image) {
JsonObject jso = Json.createObjectBuilder()
.add(JSON_IMAGE_NAME, image.imageName)
.add(JSON_IMAGE_PATH, image.imagePath)
.add(JSON_CAPTIONS, image.captions)
.add(JSON_HEIGHT, image.imageHeight)
.add(JSON_WIDTH, image.imageWidth)
.add(JSON_STATUS, image.imageStatus)
.add(JSON_IMAGE_ID,image.imageID)
.build();
return jso;
}
private JsonObject makeVideoJsonObject(Vd video) {
JsonObject jso = Json.createObjectBuilder()
.add(JSON_VIDEO_NAME, video.videoName)
.add(JSON_VIDEO_PATH, video.videoPath)
.add(JSON_CAPTIONS, video.videoCaptions)
.add(JSON_HEIGHT, video.videoHeight)
.add(JSON_WIDTH, video.videoWidth)
.build();
return jso;
}
/*private JsonObject makeSlideShowJsonObject(ObservableList<Slide> slides) {
JsonArray slidesJsonArray = makeSlidesJsonArray(slides);
JsonObject jso = Json.createObjectBuilder()
.add(JSON_SLIDESHOW, slidesJsonArray)
.build();
return jso;
}*/
private JsonArray makeSlidesJsonArray(ObservableList<Slide> slides) {
JsonArrayBuilder jsb = Json.createArrayBuilder();
for (Slide slide : slides) {
JsonObject jso = makeSlideJsonObject(slide);
jsb.add(jso);
}
JsonArray jA = jsb.build();
return jA;
}
private JsonObject makeSlideJsonObject(Slide slide) {
JsonObject jso = Json.createObjectBuilder()
.add(JSON_IMAGE_NAME, slide.getImageFileName())
.add(JSON_IMAGE_PATH, slide.getImagePath())
.add(JSON_CAPTIONS, slide.getImageCaptions())
.build();
return jso;
}
private JsonObject makeFontJsonObject(Font font) {
JsonObject jso= Json.createObjectBuilder()
.add(JSON_FONT_NAME, font.name)
.add(JSON_FONT_PATH, font.link)
.add(JSON_FONT_SIZE, font.size)
.build();
return jso;
}
}
|
package ch.fhnw.edu.cpib.cst;
import ch.fhnw.edu.cpib.cst.interfaces.IMechModeNTS;
import ch.fhnw.edu.cpib.scanner.enumerations.Mechmodes;
import ch.fhnw.edu.cpib.scanner.interfaces.IToken;
import ch.fhnw.edu.cpib.scanner.keywords.Mechmode;
// mechModeNTS ::= MECHMODE
public class MechModeNTS extends Production implements IMechModeNTS {
protected final IToken T_mechMode;
public MechModeNTS(final IToken T_mechMode) {
this.T_mechMode = T_mechMode;
}
@Override public Mechmodes toAbsSyntax() {
return ((Mechmode) T_mechMode).getMechmode();
}
}
|
/** ****************************************************************************
* Copyright (c) The Spray Project.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spray Dev Team - initial API and implementation
**************************************************************************** */
package org.eclipselabs.spray.runtime.graphiti.layout;
import org.eclipse.graphiti.datatypes.IDimension;
import org.eclipse.graphiti.mm.algorithms.AbstractText;
import org.eclipse.graphiti.mm.algorithms.Ellipse;
import org.eclipse.graphiti.mm.algorithms.GraphicsAlgorithm;
import org.eclipse.graphiti.mm.algorithms.MultiText;
import org.eclipse.graphiti.mm.algorithms.Polygon;
import org.eclipse.graphiti.mm.algorithms.Polyline;
import org.eclipse.graphiti.mm.algorithms.Rectangle;
import org.eclipse.graphiti.mm.algorithms.RoundedRectangle;
import org.eclipse.graphiti.mm.algorithms.Text;
import org.eclipse.graphiti.mm.algorithms.styles.Font;
import org.eclipse.graphiti.mm.pictograms.Shape;
import org.eclipse.graphiti.ui.services.GraphitiUi;
import org.eclipselabs.spray.runtime.graphiti.layout.SprayLayoutService.SprayAlignment;
/**
* A special layout manager for single non container shapes
*
* @author Jos Warmer (jos.warmer@openmodeling.nl)
*/
public class SprayShapeLayoutManager implements ISprayLayoutManager {
static final private int MARGIN = 5;
private Shape shape;
public SprayShapeLayoutManager(Shape shape) {
this.shape = shape;
}
@Override
public boolean isFlexible() {
return false;
}
@Override
public void layout() {
SprayAbstractLayoutManager.level++;
SprayAbstractLayoutManager.debug("ShapeLayoutManager.layout() " + SprayLayoutService.getId(shape) + " " + shape.getGraphicsAlgorithm().toString());
SprayLayoutData data = SprayLayoutService.getLayoutData(shape);
GraphicsAlgorithm ga = shape.getGraphicsAlgorithm();
if (data.isVisible()) {
if (ga instanceof MultiText) {
// http://www.eclipse.org/forums/index.php/mv/msg/203421/658899/#msg_658899
int width = 10;
int height = 10;
MultiText text = (MultiText) ga;
IDimension dim = GraphitiUi.getUiLayoutService().calculateTextSize(text.getValue(), getFont(text));
if (dim == null) {
width = data.getMinimumWidth();
height = data.getMinimumHeight();
} else {
String value = text.getValue();
int textHeight = dim.getHeight();
int currentWidth = data.getMinimumWidth();
int currentHeight = data.getMinimumHeight();
int maxCharsPerLine = Math.round((currentHeight / 15) * ((12 * currentWidth) / 90 ));
int valueLength = value.length();
int rowCount = Math.round(valueLength / maxCharsPerLine);
width = data.getMinimumWidth();
height = rowCount * textHeight;
}
width = data.getMinimumWidth();
height = data.getMinimumHeight();
int newWidth = width + (2 * MARGIN);
int newHeight = height + (2 * MARGIN);
layoutService.setSize(ga, newWidth, newHeight);
} else if (ga instanceof Text) {
int width = 10;
int height = 10;
Text text = (Text) ga;
IDimension dim = GraphitiUi.getUiLayoutService().calculateTextSize(text.getValue(), getFont(text));
if (dim == null) {
width = data.getMinimumWidth();
height = data.getMinimumHeight();
} else {
width = Math.max(dim.getWidth(), data.getMinimumWidth());
height = dim.getHeight();
}
int newWidth = width + (2 * MARGIN);
layoutService.setSize(ga, newWidth, height + 2 * MARGIN);
} else if (ga instanceof Polyline) {
Polyline pl = (Polyline) ga;
IDimension dim = layoutService.calculateSize(pl);
SprayAbstractLayoutManager.debug("ShapeLayout PolyLine");
layoutService.setSize(ga, dim.getWidth(), (dim.getHeight() < 1 ? 4 : dim.getHeight()));
} else if (ga instanceof Polygon) {
Polygon pl = (Polygon) ga;
IDimension dim = layoutService.calculateSize(pl);
SprayAbstractLayoutManager.debug("ShapeLayout Polygon");
layoutService.setSize(ga, dim.getWidth(), (dim.getHeight() < 1 ? 4 : dim.getHeight()));
} else if (ga instanceof Rectangle || ga instanceof RoundedRectangle || ga instanceof Ellipse) {
layoutService.calculateSize(ga);
layoutService.setSize(ga, data.getMinimumWidth(), data.getMinimumHeight());
}
} else {
layoutService.setSize(shape.getGraphicsAlgorithm(), 0, 0);
}
SprayAbstractLayoutManager.level--;
}
protected Font getFont(AbstractText text) {
if (text.getFont() != null) {
return text.getFont();
} else if (text.getStyle() != null) {
return text.getStyle().getFont();
} else {
return null;
}
}
@Override
public int getMargin() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setMargin(int margin) {
// TODO Auto-generated method stub
}
@Override
public int getSpacing() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setSpacing(int spacing) {
// TODO Auto-generated method stub
}
@Override
public void setAlignment(SprayAlignment alignment) {
// TODO Auto-generated method stub
}
@Override
public SprayAlignment getAlignment() {
// TODO Auto-generated method stub
return null;
}
}
|
package StepDefinitions;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import Exceptions.AdminNotFoundException;
import Exceptions.DeveloperNotFoundException;
import Exceptions.NotAuthorizedException;
import Exceptions.OperationNotAllowedException;
import Exceptions.OutOfBoundsException;
import Exceptions.ProjectAlreadyExistsException;
import Exceptions.ProjectNotFoundException;
import SoftwareAS.Controller.SoftwareAS;
import io.cucumber.java.en.*;
import SoftwareAS.Controller.ErrorMessageHolder;
import SoftwareAS.Model.*;
//This class is made by Simon Bang Hjortkilde - s183557
public class SeeAvailableDevelopersSteps {
private Developer developer;
private Admin admin;
private String adminName = "MOG1";
private DataBase database;
private Project project;
private List<Developer> availableDevelopers = new ArrayList<>();
private int startTime;
private int endTime;
private ErrorMessageHolder errorMessageHolder;
public SeeAvailableDevelopersSteps(SoftwareAS softwareAS, ErrorMessageHolder errorMessageHolder){
this.database = softwareAS.getDataBase();
this.errorMessageHolder = errorMessageHolder;
}
// # Main scenario
// Scenario: See available developers
// Given 9- there is an user with ID "SØR1"
// And 9- there is a project with name "211234"
// And 9- the user is a Project leader
// And 9- there are other developers
// When 9- the user provides information of the start week 32 and end week 40 of
// the activity where he needs developers
// Then 9- the system displays a list of available developers at the given time
// slot
@Given("9- there is an user with ID {string}")
public void thereIsAnUserWithIDAndDataBase(String userName) throws NotAuthorizedException,
OperationNotAllowedException, AdminNotFoundException, DeveloperNotFoundException, OutOfBoundsException {
database.createAdmin(adminName);
admin = database.getAdminById(adminName);
admin.createDeveloper(userName);
developer = database.getDeveloperById(userName);
assertTrue(database.containsDeveloper(userName));
}
@Given("9- there is a project with name {string}")
public void thereIsAProject(String projectname) throws ProjectAlreadyExistsException, ProjectNotFoundException,
NotAuthorizedException, OutOfBoundsException {
admin.createProject(projectname);
project = database.getProjectByName(projectname);
assertTrue(database.containsProject(projectname));
}
@Given("9- the user is a Project leader or admin")
public void theUserIsAProjectLeaderOrAdmin()
throws OperationNotAllowedException, DeveloperNotFoundException, NotAuthorizedException {
project.assignDeveloperToProject(admin, developer);
project.setProjectLeader(admin, developer);
assertTrue(project.isProjectLeader(developer) || developer.isAdmin());
}
@Given("9- there are other developers")
public void thereIsOtherUsers() throws OutOfBoundsException, DeveloperNotFoundException {
database.removeAllDevelopers();
admin.createDeveloper("1111");
admin.createDeveloper("2222");
admin.createDeveloper("3333");
}
@When("9- the user provides information of the start week {int} and end week {int} of the activity where he needs developers")
public void theUserProvidesTimeSlot(int start, int end) throws OutOfBoundsException {
startTime = start;
endTime = end;
}
@Then("9- the system displays a list of available developers at the given time slot")
public void theSystemProvidesListOfAvailableDevelopers() throws NotAuthorizedException, OutOfBoundsException {
availableDevelopers = database.seeAvailableDevelopers(startTime, endTime, developer);
assertTrue(availableDevelopers.size() == 3);
for (Developer developer : availableDevelopers) {
List<Activity> activities = developer.getActivities();
int k = 0;
for (Activity activity : activities) {
if (activity.getStartWeek() < startTime && activity.getEndWeek() > endTime) {
k++;
}
assertTrue(k < 21);
}
}
}
// # Alternate scenario one
// Scenario: Given time not valid length
// Given 9- there is an user with ID "MOG1"
// And 9- there is a project with name "214321"
// And 9- the user is a Project leader
// When 9- the user provides invalid input of the start week -32 and end week
// 400 of the activity where he needs developers
// Then 9- the system provides an error message that the start week and/or end
// week is invalid
@When("9- the user provides invalid input of the start week {int} and end week {int} of the activity where he needs developers")
public void theUserProvidesInvalidTimeInput(int start, int end)
throws OutOfBoundsException, NotAuthorizedException {
try {
database.seeAvailableDevelopers(start, end, developer);
} catch (OutOfBoundsException e) {
errorMessageHolder.setErrorMessage(e.getMessage());
}
}
@Then("9- the system provides an error message that the start week and\\/or end week is invalid")
public void theSystemProvidesAnErrorMessageThatTheTimeInputIsInvalid() throws OutOfBoundsException {
assertEquals("The start week and end week has to be an integer between 1 and 52",
errorMessageHolder.getErrorMessage());
}
// # Alternate scenario two
// Scenario: See available developers
// Given 9- there is an user with ID "JEP1"
// And 9- there is a project with name "212222"
// And 9- the user is not a Project leader
// And 9- there are other developers
// When 9- the user tries to provide information of the start week 32 and end week 40 of the activity where he needs developers
// Then 9- the system provides an error message that the user is not authorized for this action
@Given("9- the user is not a Project leader or admin")
public void theUserIsNotAProjectLeaderOrAdmin()
throws OperationNotAllowedException, DeveloperNotFoundException, NotAuthorizedException {
project.assignDeveloperToProject(admin, developer);
assertFalse(project.isProjectLeader(developer) && developer.isAdmin());
}
@When("9- the user tries to provide information of the start week {int} and end week {int} of the activity where he needs developers")
public void theUserTriesProvideInformation(int start, int end) throws OutOfBoundsException, NotAuthorizedException {
try {
database.seeAvailableDevelopers(start, end, developer);
} catch (NotAuthorizedException e) {
errorMessageHolder.setErrorMessage(e.getMessage());
}
}
@Then("9- the system provides an error message that the user is not authorized for this action")
public void theSystemProvidesAnErrorMessageThatTheUserIsNotAuthorized() throws OutOfBoundsException {
assertEquals("Only project leaders or admins can request to see available developers",
errorMessageHolder.getErrorMessage());
}
}
|
package com.leysoft.app.controller;
import java.net.URI;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.leysoft.app.assembler.AutorResourceAssembler;
import com.leysoft.app.assembler.LibroResourceAssembler;
import com.leysoft.app.entity.Autor;
import com.leysoft.app.exception.NotFoundException;
import com.leysoft.app.resource.AutorResource;
import com.leysoft.app.resource.LibroResource;
import com.leysoft.app.service.inter.AutorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@Api
@RestController
public class ApiAutorController {
@Autowired
private AutorService autorService;
@Autowired
private AutorResourceAssembler autorAssembler;
@Autowired
private LibroResourceAssembler libroAssembler;
@GetMapping(value = {"/autor"})
@ApiOperation(value = "get-autores", nickname = "get-autores")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 500, message = "Failure")})
public ResponseEntity<List<AutorResource>> list() {
return new ResponseEntity<List<AutorResource>>(autorAssembler.toResources(autorService.findAll()), HttpStatus.OK);
}
@GetMapping(value = {"/autor/search"})
@ApiOperation(value = "search-autores", nickname = "search-autores")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 500, message = "Failure")})
public ResponseEntity<List<AutorResource>> search(@RequestParam("nombre") String nombre) {
return new ResponseEntity<List<AutorResource>>(autorAssembler.toResources(autorService.findByNombreContainingIgnoreCase(nombre)), HttpStatus.OK);
}
@GetMapping(value = {"/autor/{id}"})
@ApiOperation(value = "get-autor", nickname = "get-autor")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")})
public ResponseEntity<AutorResource> detail(@PathVariable("id") Long id) {
Autor autor = autorService.findById(id);
if(autor == null) {
throw new NotFoundException("id - " + id);
}
AutorResource resource = autorAssembler.toResource(autor);
return new ResponseEntity<AutorResource>(resource, HttpStatus.OK);
}
@GetMapping(value = {"/autor/{id}/libro"})
@ApiOperation(value = "libros-autor", nickname = "libros-autor")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 500, message = "Failure")})
public ResponseEntity<List<LibroResource>> librosAutor(@PathVariable("id") Long id) {
Autor autor = autorService.findByIdJoinFetch(id);
if(autor == null) {
throw new NotFoundException("id - " + id);
}
List<LibroResource> resources = libroAssembler.toResources(autor.getLibros());
return new ResponseEntity<List<LibroResource>>(resources, HttpStatus.OK);
}
@PostMapping(value = {"/autor"})
@ApiOperation(value = "save-autor", nickname = "save-autor")
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created"),
@ApiResponse(code = 500, message = "Failure")})
public ResponseEntity<Void> create(@Valid @RequestBody Autor autor) {
Autor currentAutor = autorService.save(autor);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(currentAutor.getId()).toUri();
return ResponseEntity.created(location).build();
}
@PutMapping(value = {"/autor/{id}"})
@ApiOperation(value = "update-autor", nickname = "update-autor")
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created"),
@ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")})
public ResponseEntity<Void> update(@Valid @RequestBody Autor autor, @PathVariable("id") Long id) {
Autor currentAutor = autorService.findById(id);
if(currentAutor == null) {
throw new NotFoundException("id - " + id);
}
currentAutor.setNombre(autor.getNombre());
currentAutor.setLibros(autor.getLibros());
autorService.update(currentAutor);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(currentAutor.getId()).toUri();
return ResponseEntity.created(location).build();
}
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@DeleteMapping(value = {"/autor/{id}"})
@ApiOperation(value = "delete-autor", nickname = "delete-autor")
@ApiResponses(value = {@ApiResponse(code = 204, message = "No Content"),
@ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")})
public void delete(@PathVariable("id") Long id) {
Autor autor = autorService.findById(id);
if(autor == null) {
throw new NotFoundException("id - " + id);
}
autorService.delete(id);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package factoria;
import datos.Compra;
import datos.Persona;
import java.util.HashMap;
/**
*
* @author profesor
*/
public interface ToXMLable {
public void toXMLPersonas(HashMap<Integer, Persona> map,String file);
public void toXMLCompras(HashMap<Integer, Compra> map,String file);
public HashMap<Integer, Persona> fromXMLPersonas(String file);
public HashMap<Integer, Compra> fromXMLCompras(String file);
}
|
package ar.com.ada.second.tdvr.model.repository;
import ar.com.ada.second.tdvr.model.entity.Song;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SongRepository extends JpaRepository<Song, Long> {
}
|
package bit;
/**
* @Author: Mr.M
* @Date: 2019-04-04 17:33
* @Description:
**/
public class T1 {
public static void main(String[] args) {
int mask = 7;
int t = 2;
int mask1 = mask | (1 << t);
int mask2 = mask & (~(1 << t));
System.out.println(mask1);
System.out.println(mask2);
}
}
|
package TableSorter_IsSortedTests;
import cs5387.Table;
import cs5387.TableSorter;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class Size2x2MaxMinTest {
@Test
void test() {
//create TableSorter object to access methods
TableSorter ts = new TableSorter();
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
//Test 2 x 2 matrix
int [] vals = { max, 2, //minimum and maximum integer values
4, min
};
int N = vals.length;
Table t1 = null;
try {
t1 = new Table(N, vals);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertFalse(TableSorter.isSorted(t1));
System.out.printf("2x2 MaxMin Table sorted: %s", TableSorter.isSorted(t1)); //should return
//false
}
}
|
package com.chuxin.family.libs.gpuimage.activity;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;
import com.chuxin.family.R;
import com.chuxin.family.app.CxRootActivity;
import com.chuxin.family.libs.gpuimage.CxGpuImageConstants;
import com.chuxin.family.libs.gpuimage.GPUImageFilterAdapter;
import com.chuxin.family.libs.gpuimage.utils.CameraHelper;
import com.chuxin.family.libs.gpuimage.utils.CameraHelper.CameraInfo2;
import com.chuxin.family.libs.gpuimage.utils.HorizontalListView;
import com.chuxin.family.libs.gpuimage.utils.PictureUtils;
import com.chuxin.family.utils.CxLoadingUtil;
import com.chuxin.family.utils.CxLog;
import com.chuxin.family.utils.ToastUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import jp.co.cyberagent.android.gpuimage.GPUImage;
import jp.co.cyberagent.android.gpuimage.GPUImage.OnPictureSavedListener;
import jp.co.cyberagent.android.gpuimage.GPUImage.OnSetImageFinishListener;
/**
* 使用gpuimage库带滤镜的camera
*
* @author wangshichao
*/
public class ActivityCamera extends CxRootActivity implements OnClickListener,
OnPictureSavedListener, OnSetImageFinishListener {
private final static String TAG = "ActivityCamera";
protected static final String SAMSUNG = "samsung";
private GPUImage mGPUImage;
private CameraHelper mCameraHelper;
private CameraLoader mCamera;
private ImageButton mButtonCapture; // 拍照按钮
private ImageButton mButtonConfirm; // 确认按钮
private ImageButton mButtonTakenAgain; // 重拍按钮
private GLSurfaceView mGlSurfaceView;
private Bitmap mBitmap = null;
private static final int SAVE_IMAGE = 0;
private PictureUtils mPu;
public Handler mCameraHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SAVE_IMAGE:
saveImage();
break;
}
}
};
public static int getResId(String variableName, Class<?> c) {
try {
Field idField = c.getDeclaredField(variableName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.cx_fa_libgpu_activity_camera);
mButtonCapture = (ImageButton) findViewById(R.id.cx_fa_libgpu_button_capture);
mButtonCapture.setOnClickListener(this);
ImageButton mButtonCameraBack = (ImageButton) findViewById(R.id.cameraBack);
mButtonCameraBack.setOnClickListener(this);
mButtonConfirm = (ImageButton) findViewById(R.id.button_confirm);
mButtonConfirm.setOnClickListener(this);
mButtonTakenAgain = (ImageButton) findViewById(R.id.button_taken_again);
mButtonTakenAgain.setOnClickListener(this);
HorizontalListView listview = (HorizontalListView) findViewById(R.id.listview);
checkSdCardExist();
mGPUImage = new GPUImage(this);
GPUImageFilterAdapter mGpuImageFilterAdapter = new GPUImageFilterAdapter(this, mGPUImage);
// listview.setAdapter(mAdapter);
listview.setAdapter(mGpuImageFilterAdapter);
mGlSurfaceView = (GLSurfaceView) findViewById(R.id.surfaceViewCamera);
mGPUImage.setGLSurfaceView(mGlSurfaceView);
mCameraHelper = new CameraHelper(this);
mCamera = new CameraLoader();
View cameraSwitchView = findViewById(R.id.img_switch_camera);
cameraSwitchView.setOnClickListener(this);
if (!mCameraHelper.hasFrontCamera() || !mCameraHelper.hasBackCamera()) {
cameraSwitchView.setVisibility(View.GONE);
}
mCamera.onResume();
mPu = new PictureUtils(ActivityCamera.this);
}
@Override
protected void onResume() {
super.onResume();
// mCamera.onResume();
if (mCamera.mCameraInstance == null) {
ToastUtil.getSimpleToast(this, -3, "相机权限可能被拒绝了", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
protected void onPause() {
mCamera.onPause();
super.onPause();
}
@Override
public void onClick(final View v) {
if (v.getId() == R.id.cx_fa_libgpu_button_capture) {
mButtonCapture.setClickable(false);
if (mCamera.mCameraInstance.getParameters().getFocusMode()
.equals(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
takePicture();
} else {
mCamera.mCameraInstance
.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(final boolean success,
final Camera camera) {
takePicture();
}
});
}
}
if (v.getId() == R.id.img_switch_camera) {
mCamera.switchCamera();
}
if (v.getId() == R.id.button_confirm) {
Log.v("tag", "confirm image");
mButtonTakenAgain.setVisibility(View.INVISIBLE);
mButtonTakenAgain.setClickable(false);
Message message = Message.obtain(mCameraHandler, SAVE_IMAGE);
message.sendToTarget();
// saveImage();
// ActivityCamera.this.finish();
}
if (v.getId() == R.id.cameraBack) {
ActivityCamera.this.finish();
}
}
private void takePicture() {
WindowManager windowManager = getWindowManager();
DisplayMetrics dm = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(dm);
final int w = dm.widthPixels;
final int h = dm.heightPixels;
Log.v(TAG, "w=" + w + " h=" + h);
Camera.Parameters params = mCamera.mCameraInstance.getParameters();
DisplayMetrics metrics = getResources().getDisplayMetrics();
switch (metrics.densityDpi) {
case DisplayMetrics.DENSITY_XXHIGH:
params.setPictureSize(1280, 960);
break;
case DisplayMetrics.DENSITY_XHIGH:
case DisplayMetrics.DENSITY_HIGH:
params.setPictureSize(640, 480);
break;
case DisplayMetrics.DENSITY_MEDIUM:
case DisplayMetrics.DENSITY_LOW:
params.setPictureSize(320, 240);
break;
default:
params.setPictureSize(dm.widthPixels, dm.heightPixels);
break;
}
//
// List<Camera.Size> psize = params.getSupportedPictureSizes();// 取得相机所支持多少图片大小的个数
// if (null != psize && 0 < psize.size()) {
// int sizewidths[] = new int[psize.size()];
// int sizeheights[] = new int[psize.size()];
// float densitys[] = new float[psize.size()];
// for (int i = 0; i < psize.size(); i++) {
// Camera.Size size = (Camera.Size) psize.get(i);
// if (size.width > 1280) {
// params.setPictureSize(1280, 960);
// } else {
// params.setPictureSize(640, 480);
// }
// }
// } else {
// params.setPictureSize(display.getWidth(), display.getHeight());
// }
params.setRotation(90);
mCamera.mCameraInstance.setParameters(params);
// mCamera.mCameraInstance.setDisplayOrientation(90);
for (Camera.Size size2 : mCamera.mCameraInstance.getParameters()
.getSupportedPictureSizes()) {
Log.i(TAG, "Supported: " + size2.width + "x" + size2.height);
}
mCamera.mCameraInstance.takePicture(null, null,
new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, final Camera camera) {
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
// final File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
// if (pictureFile == null) {
// Log.d(TAG,
// "Error creating media file, check storage permissions");
// return;
// }
//
// try {
// FileOutputStream fos = new FileOutputStream(
// pictureFile);
// fos.write(data);
// fos.close();
// } catch (FileNotFoundException e) {
// Log.d(TAG, "File not found: " + e.getMessage());
// } catch (IOException e) {
// Log.d(TAG,
// "Error accessing file: " + e.getMessage());
// }
// data = null;
// PictureUtils pu = new PictureUtils(ActivityCamera.this);
// bMap = pu.rotateImage(bMap, pictureFile);
// Bitmap bitmap = null;
// if(null != mBitmap){
// mBitmap.recycle();
// mBitmap = null;
// }
// try {
// mBitmap = BitmapFactory.decodeFile(pictureFile
// .getAbsolutePath());
// } catch (OutOfMemoryError e) {
// mBitmap.recycle();
// e.printStackTrace();
// }
// TODO 需要机型适配
// if(getPhoneManufacturer().equals("samsung") && getPhoneModel().equals("GT-I9500")){
// //camera.stopPreview();
//// mCamera.onPause();
//// camera.release();
// mGPUImage.setImage(mBitmap);
// }
// mGPUImage.setImage(bitMap);
// Uri imageUri = pu.changeContentUri(Uri.fromFile(pictureFile));
// mGPUImage.setImage(imageUri, ActivityCamera.this);
mButtonCapture.setVisibility(View.GONE);
mButtonConfirm.setVisibility(View.VISIBLE);
mButtonTakenAgain.setVisibility(View.VISIBLE);
mButtonTakenAgain
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (getPhoneManufacturer().equals(SAMSUNG) && getPhoneModel().equals("GT-I9500")) {
//camera.stopPreview();
// mCamera.onResume();
camera.startPreview();
} else {
camera.startPreview();
}
mGlSurfaceView
.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
mButtonCapture
.setVisibility(View.VISIBLE);
mButtonCapture.setClickable(true);
mButtonConfirm.setVisibility(View.GONE);
mButtonTakenAgain
.setVisibility(View.GONE);
}
});
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
/*if(null != mBitmap){ //聂超 2013-12-9修复Bitmap为null的bug
mBitmap.recycle();
System.gc();
}*/
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private class CameraLoader {
private int mCurrentCameraId = 0;
private Camera mCameraInstance;
public void onResume() {
setUpCamera(mCurrentCameraId);
}
public void onPause() {
releaseCamera();
}
public void switchCamera() {
releaseCamera();
mCurrentCameraId = (mCurrentCameraId + 1)
% mCameraHelper.getNumberOfCameras();
setUpCamera(mCurrentCameraId);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // 这个API已做判断处理
private void setUpCamera(final int id) {
mCameraInstance = getCameraInstance(id);
if (null == mCameraInstance)
return;
Parameters parameters = mCameraInstance.getParameters();
// parameters.setPreviewSize(cs.width, cs.height);
// TODO 根据手机型号做相应适配
parameters.setPreviewSize(640, 480);
parameters.set("orientation", "portrait");
parameters.set("rotation", 90);
if (parameters.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH)
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
mCameraInstance.setParameters(parameters);
int orientation = mCameraHelper.getCameraDisplayOrientation(
ActivityCamera.this, mCurrentCameraId);
// mCameraHelper.setCameraDisplayOrientation(ActivityCamera.this, mCurrentCameraId, mCameraInstance);
CameraInfo2 cameraInfo = new CameraInfo2();
mCameraHelper.getCameraInfo(mCurrentCameraId, cameraInfo);
boolean flipHorizontal = cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT;
mGPUImage.setUpCamera(mCameraInstance, orientation, flipHorizontal,
false);
}
/**
* A safe way to get an instance of the Camera object.
*/
private Camera getCameraInstance(final int id) {
Camera c = null;
try {
c = mCameraHelper.openCamera(id);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
private void releaseCamera() {
if (null != mCameraInstance) {
mCameraInstance.setPreviewCallback(null);
mCameraInstance.release();
mCameraInstance = null;
}
}
}
private void saveImage() {
CxLoadingUtil.getInstance().showLoading(ActivityCamera.this, true);
String fileName = System.currentTimeMillis() + ".jpgbak";
mGPUImage.setImage(mBitmap);
mGPUImage.saveToPictures("Android/data/" + this.getPackageName() + "/images", fileName, this);
}
@Override
public void onPictureSaved(Uri uri) {
mGlSurfaceView.setVisibility(View.INVISIBLE);
// PictureUtils pu=new PictureUtils(getApplicationContext());
// try {
// int i = pu.getImageOrientation(uri.getPath());
// System.out.println(i);
// } catch (IOException e1) {
// e1.printStackTrace();
// }
Uri imageUri = uri;
// getPhoneManufacturer().equals("samsung") && getPhoneModel().equals("GT-N7000")
if (getPhoneManufacturer().equals(SAMSUNG) || getPhoneManufacturer().equals("Motorola")) {
Bitmap bitmap = mPu.getBitmapFromUri(uri.getPath());
File newFile = new File(uri.getPath());
Matrix matrix = new Matrix();
matrix.reset();
matrix.postRotate(90);
Bitmap bMapRotate = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
bitmap = bMapRotate;
File adjustFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
try {
bMapRotate.compress(CompressFormat.JPEG, 30, new FileOutputStream(adjustFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(adjustFile);
ActivitySelectPhoto.setCurrentPictureUri(imageUri);
if (newFile.exists()) {
newFile.delete();
}
if (null != bitmap) {
bitmap.recycle();
}
if (null != bMapRotate) {
bMapRotate.recycle();
}
} else {
ActivitySelectPhoto.setCurrentPictureUri(imageUri);
}
// Toast.makeText(this, imageUri.toString(), Toast.LENGTH_LONG).show();
CxLoadingUtil.getInstance().dismissLoading();
mButtonTakenAgain.setClickable(true);
if (ActivitySelectPhoto.kCallCamera) {
Intent intent = new Intent();
intent.putExtra(CxGpuImageConstants.KEY_PICTURE_URI, imageUri.toString());
setResult(Activity.RESULT_OK, intent);
} else {
setResult(Activity.RESULT_OK);
}
ActivityCamera.this.finish();
}
public static String getPhoneModel() {
return android.os.Build.MODEL;
}
public static String getPhoneManufacturer() {
return android.os.Build.MANUFACTURER;
}
private File getOutputMediaFile(final int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
checkSdCardExist();
File mediaStorageDir = new File(
Environment
.getExternalStorageDirectory(),
"Android/data/" + this.getPackageName() + "/images");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
CxLog.d("Android/data/" + this.getPackageName() + "/images", "failed to create directory");
return null;
}
}
// Create a media file name
// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
// .format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ System.currentTimeMillis() + ".jpgbak");
} else {
return null;
}
return mediaFile;
}
/**
* 检查sdcard是否存在
*/
private boolean checkSdCardExist() {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
new AlertDialog.Builder(this)
.setTitle(R.string.cx_fa_alert_dialog_tip)
.setMessage(R.string.cx_fa_unuseable_extralstorage)
.setPositiveButton(R.string.cx_fa_confirm_text, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCamera.this.finish();
}
})
.show();
return false;
} else {
return true;
}
}
@Override
public void onSetImageFinish(boolean finish) {
}
/* public void adjustImage(Uri imageUri){
Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageUri);
Matrix matrix = new Matrix();
// rotate the Bitmap (there a problem with exif so we'll query the mediaStore for orientation
Cursor cursor = getApplicationContext().getContentResolver().query(uri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() == 1) {
cursor.moveToFirst();
int orientation = cursor.getInt(0);
matrix.preRotate(orientation);
}
}*/
}
|
import java.util.Comparator;
import components.queue.Queue;
import components.queue.Queue1L;
import components.sequence.Sequence;
import components.simplereader.SimpleReader;
import components.simplereader.SimpleReader1L;
import components.simplewriter.SimpleWriter;
import components.simplewriter.SimpleWriter1L;
import components.stack.Stack;
import components.stack.Stack2;
import components.xmltree.XMLTree;
public final class Test {
private static class StringLT implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
private Test() {
}
public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
SimpleWriter out = new SimpleWriter1L();
///////////////////////////////////////////
String str1 = "~~ He has abdicated government here, by declaring us out of~ h ";
String str2 = "ted government here, by declaring ";
out.println(str1.indexOf(str2));
out.println(str2.indexOf(str1));
///////////////////////////////////////////
in.close();
out.close();
}
public static void flip(Stack<String> th) {
Stack<String> tempStack = new Stack2<String>();
int length = th.length();
for (int i = 1; i <= length; i++) {
tempStack.push(th.pop());
}
th.transferFrom(tempStack);
}
public static void flip(Sequence<String> th) {
if (th.length() > 1) {
Sequence<String> tempSequence = th.newInstance();
String last = th.entry(th.length() - 1);
String first = th.replaceEntry(0, last);
th.replaceEntry(th.length() - 1, first);
th.extract(1, th.length() - 1, tempSequence);
flip(tempSequence);
th.insert(1, tempSequence);
}
}
private static String removeMin(Queue<String> q, Comparator<String> order) {
String min = q.front();
boolean done = false;
for (String toTest : q) {
if (order.compare(toTest, min) < 0) {
min = toTest;
}
}
while (!done) {
String test = q.dequeue();
if (test.equals(min)) {
done = true;
} else {
q.enqueue(test);
}
}
return min;
}
public static void sort(Queue<String> q, Comparator<String> order) {
Queue<String> sorted = new Queue1L<String>();
while (q.length() > 0) {
sorted.enqueue(removeMin(q, order));
}
q.transferFrom(sorted);
}
private static void flip(Queue<Integer> q) {
if (q.length() != 0) {
int k = q.dequeue();
System.out.println(k);
flip(q);
System.out.println(k);
q.enqueue(k);
}
}
private static int min(Queue<Integer> q) {
int min = Integer.MAX_VALUE;
int qLength = q.length();
for (int i = 0; i < qLength; i++) {
int number = q.dequeue();
if (number < min) {
min = number;
}
q.enqueue(number);
}
return min;
}
private static int[] minAndMax(Queue<Integer> q) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int qLength = q.length();
for (int i = 0; i < qLength; i++) {
int num1 = q.dequeue();
int num2 = q.dequeue();
if (num1 > num2) {
if (num1 > max) {
max = num1;
}
if (num2 < min) {
min = num2;
}
} else {
if (num2 > max) {
max = num2;
}
if (num1 < min) {
min = num1;
}
}
q.enqueue(num1);
q.enqueue(num2);
}
int[] minAndMax = { min, max };
return minAndMax;
}
private static boolean findTag(XMLTree xml, String tag) {
boolean returnValue = false;
if (xml.isTag()) {
for (int i = 0; i < xml.numberOfChildren(); i++) {
if (xml.label().equals(tag)) {
returnValue = true;
i = xml.numberOfChildren();
} else {
returnValue = findTag(xml.child(i), tag);
if (returnValue == true) {
i = xml.numberOfChildren();
}
}
}
}
return returnValue;
}
}
|
/**
*
*/
package com.paytechnologies.DTO;
import java.util.ArrayList;
/**
* @author Sujay
*
*/
public class MatchUsersDTO {
private ArrayList<MatchingUserProfileDTO> liveUsers = new ArrayList<MatchingUserProfileDTO>();
private ArrayList<MatchingUserProfileDTO> deadUsers = new ArrayList<MatchingUserProfileDTO>();
public ArrayList<MatchingUserProfileDTO> getLiveUsers() {
return liveUsers;
}
public void setLiveUsers(ArrayList<MatchingUserProfileDTO> liveUsers) {
this.liveUsers = liveUsers;
}
public ArrayList<MatchingUserProfileDTO> getDeadUsers() {
return deadUsers;
}
public void setDeadUsers(ArrayList<MatchingUserProfileDTO> deadUsers) {
this.deadUsers = deadUsers;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
public class Prueba {
public static void main(String[] args) {
// TODO code application logic here
if (a == a){
System.out.println();
} else{
System.out.println("Hola mundo");
int xd;
int a = 5 * 10 + (a*b);
float b = 5 + a;
}
do{
int xd;
int a = xd * 10 + (a*b);
float b = 5 + a;
}while (a<b || a>=5);
private double lol;
while (a!=b){
System.out.println("Hola mundo");
}
System.out.println("Hola mundo");
int xd;
int a = 5 * 10 + (a*b);
float b = 5 + a;
System.out.println(b);
String letras = "Que hace";
char letra ='c';
System.out.println(letra);
}
}
|
package com.gerray.fmsystem.ManagerModule;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.gerray.fmsystem.Authentication.LoginActivity;
import com.gerray.fmsystem.ManagerModule.Assets.AssetFragment;
import com.gerray.fmsystem.ManagerModule.ChatRoom.ChatFragment;
import com.gerray.fmsystem.ManagerModule.Consultants.FacilityConsultant;
import com.gerray.fmsystem.ManagerModule.Lessee.LesseeFragment;
import com.gerray.fmsystem.ManagerModule.Location.FacilityLocation;
import com.gerray.fmsystem.ManagerModule.Profile.FacilityProfile;
import com.gerray.fmsystem.ManagerModule.WorkOrder.RequestFragment;
import com.gerray.fmsystem.ManagerModule.WorkOrder.WorkFragment;
import com.gerray.fmsystem.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.Objects;
public class FacilityManager extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private AssetFragment assetFragment;
private LesseeFragment lesseeFragment;
private ChatFragment chatFragment;
private WorkFragment workFragment;
private RequestFragment requestFragment;
Toolbar toolbar;
private FirebaseAuth auth;
FirebaseDatabase firebaseDatabase;
DatabaseReference firebaseDatabaseReference, reference, dbRef;
FirebaseUser firebaseUser;
@SuppressLint("NonConstantResourceId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facility_manager);
auth = FirebaseAuth.getInstance();
NavigationView navigationView = findViewById(R.id.nav_view);
View hView = navigationView.inflateHeaderView(R.layout.nav_header);
TextView textView = hView.findViewById(R.id.nav_fm_tv);
ImageView imageView = hView.findViewById(R.id.nav_fm_image);
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabaseReference = firebaseDatabase.getReference();
reference = firebaseDatabase.getReference();
dbRef = firebaseDatabase.getReference();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
firebaseDatabaseReference.child("Facilities")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.child(firebaseUser.getUid()).exists()) {
reference.child("Facilities").child(firebaseUser.getUid())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String facilityID = null, managerName = null, facilityName = null;
if (snapshot.child("facilityID").exists()) {
facilityID = Objects.requireNonNull(snapshot.child("facilityID").getValue()).toString();
}
if (snapshot.child("facilityManager").exists()) {
managerName = Objects.requireNonNull(snapshot.child("facilityManager").getValue()).toString();
}
if (snapshot.child("name").exists()) {
facilityName = Objects.requireNonNull(snapshot.child("name").getValue()).toString();
toolbar.setTitle(facilityName);
textView.setText(facilityName);
}
Bundle bundle = new Bundle();
bundle.putString("facilityID", facilityID);
LesseeFragment lesseeFragment = new LesseeFragment();
lesseeFragment.setArguments(bundle);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
Toast.makeText(FacilityManager.this, "Welcome Back", Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(FacilityManager.this, FacilityCreate.class));
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
dbRef.child("Facilities").child(firebaseUser.getUid()).child("Profile");
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.child("facilityImageUrl").exists()) {
String imageUrl = Objects.requireNonNull(snapshot.child("facilityImageUrl").getValue()).toString().trim();
Picasso.with(FacilityManager.this).load(imageUrl).into(imageView);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
BottomNavigationView mNav = findViewById(R.id.bottom_nav);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
assetFragment = new AssetFragment();
lesseeFragment = new LesseeFragment();
chatFragment = new ChatFragment();
workFragment = new WorkFragment();
requestFragment = new RequestFragment();
setFragment(workFragment);
navigationView.setNavigationItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.drawer_contact:
contactUs();
break;
case R.id.drawer_location:
startActivity(new Intent(FacilityManager.this, FacilityLocation.class));
break;
case R.id.drawer_team:
startActivity(new Intent(FacilityManager.this, FacilityConsultant.class));
break;
case R.id.drawer_profile:
startActivity(new Intent(FacilityManager.this, FacilityProfile.class));
break;
case R.id.drawer_share:
shareApp();
break;
case R.id.drawer_payment:
startActivity(new Intent(FacilityManager.this, TransactionActivity.class));
break;
case R.id.drawer_logOut:
auth.signOut();
startActivity(new Intent(FacilityManager.this, LoginActivity.class));
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
});
mNav.setOnNavigationItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.nav_assets:
setFragment(assetFragment);
return true;
case R.id.nav_chat:
setFragment(chatFragment);
return true;
case R.id.nav_work:
setFragment(workFragment);
return true;
case R.id.nav_request:
setFragment(requestFragment);
return true;
case R.id.nav_lessee:
setFragment(lesseeFragment);
return true;
default:
return false;
}
});
mNav.setSelectedItemId(R.id.nav_work);
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.mFrame, fragment);
fragmentTransaction.commit();
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private void shareApp() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, getTitle());
startActivity(Intent.createChooser(intent, "Choose One"));
}
private void contactUs() {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"facilityapp@gmail.com"});
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(FacilityManager.this, "There are no Email Clients installed.", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
return false;
}
}
|
package com.example.demo_boot.controller;
import com.example.demo_boot.persistence.BaseC;
import com.example.demo_boot.service.ExService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
@RestController
public class GenericrestController<T extends BaseC> {
private ExService exService;
private ObjectMapper objectMapper;
@Autowired
public GenericrestController(ExService exService, ObjectMapper objectMapper) {
this.exService = exService;
this.objectMapper = objectMapper;
}
@PostMapping("/post/{tableName}")
public void postGenericObject(@RequestBody ObjectNode obj, @PathVariable String tableName) {
System.out.println("************************************************************");
try {
String v = objectMapper.writeValueAsString(obj);
System.out.println(v);
String className = "com.example.demo_boot.persistence." + tableName;
Class c = Class.forName(className);
T d = (T) objectMapper.readValue(v, c);
exService.create(d, tableName);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("************************************************************");
}
@PostMapping("/postArray/{tableName}")
public void postGenericArray(@RequestBody ArrayNode obj, @PathVariable String tableName) {
System.out.println("************************************************************");
try {
String className = "com.example.demo_boot.persistence." + tableName;
Class c = Class.forName(className);
obj.forEach(e -> {
try {
String v = objectMapper.writeValueAsString(e);
T t = (T) objectMapper.readValue(v, c);
exService.create(t, tableName);
} catch (IOException e1) {
e1.printStackTrace();
}
});
} catch (ClassNotFoundException e) {
System.out.println(e);
}
System.out.println("************************************************************");
}
}
|
package com.localhost.gwt.client.service;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.localhost.gwt.shared.transport.ServiceRequest;
import com.localhost.gwt.shared.transport.ServiceResponse;
import com.localhost.gwt.shared.SharedRuntimeException;
import com.localhost.gwt.shared.model.Word;
import java.util.List;
/**
* Created by AlexL on 06.10.2017.
*/
public interface VocabularyServiceAsync {
void getLevels(AsyncCallback<ServiceResponse> callback) throws SharedRuntimeException;
void getWords(ServiceRequest request, AsyncCallback<ServiceResponse> callback) throws SharedRuntimeException;
void addWords(List<Word> words, AsyncCallback<Void> callback) throws SharedRuntimeException;
void getLanguages(AsyncCallback<ServiceResponse> callback) throws SharedRuntimeException;
}
|
package com.tencent.mm.plugin.welab.a;
import android.text.TextUtils;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.messenger.foundation.a.a.h;
import com.tencent.mm.plugin.messenger.foundation.a.i;
import com.tencent.mm.plugin.welab.a.a.a;
import com.tencent.mm.plugin.welab.e;
import com.tencent.mm.protocal.c.aqg;
import com.tencent.mm.protocal.c.aqh;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import java.util.HashMap;
import java.util.Map;
public final class b implements a {
private Map<String, Integer> qmR = new HashMap();
private String tag = "";
public b() {
bYM();
}
private void bYM() {
this.tag = (String) g.Ei().DT().get(aa.a.sXj, null);
x.i("LabAppLifeService", "load red tag " + this.tag);
if (!TextUtils.isEmpty(this.tag)) {
for (Object obj : this.tag.split("&")) {
if (!TextUtils.isEmpty(obj)) {
String[] split = obj.split("=");
if (split != null && split.length == 2) {
this.qmR.put(split[0], Integer.valueOf(bi.WU(split[1])));
}
}
}
}
}
public final boolean RX(String str) {
if (com.tencent.mm.plugin.welab.b.bYI().RT(str).field_Switch == 2) {
x.i("LabAppLifeService", "appid %s is open ", new Object[]{str});
return true;
}
x.i("LabAppLifeService", "appid %s is close", new Object[]{str});
return false;
}
public final boolean RY(String str) {
return this.qmR.get(str) == null || ((Integer) this.qmR.get(str)).intValue() == 0;
}
public final void open(String str) {
this.qmR.put(str, Integer.valueOf(1));
this.tag += "&" + str + "=1";
g.Ei().DT().a(aa.a.sXj, this.tag);
com.tencent.mm.plugin.welab.c.a.a RT = com.tencent.mm.plugin.welab.b.bYI().RT(str);
e.a aVar = new e.a();
aVar.bPS = str;
aVar.qmP = RT.field_expId;
aVar.timeStamp = System.currentTimeMillis();
aVar.action = 3;
e.a(aVar);
}
public final boolean RZ(String str) {
boolean z;
com.tencent.mm.plugin.welab.c.a.a RT = com.tencent.mm.plugin.welab.b.bYI().RT(str);
String str2 = "LabAppLifeService";
StringBuilder append = new StringBuilder("hitExp ").append(str).append(", ");
if (RT.isRunning()) {
z = true;
} else {
z = false;
}
x.i(str2, append.append(z).toString());
if (RT.isRunning()) {
return true;
}
return false;
}
public final void bh(String str, boolean z) {
int i = 1;
x.i("LabAppLifeService", "switchEntry " + str + "," + z);
com.tencent.mm.plugin.welab.c.a.a RT = com.tencent.mm.plugin.welab.b.bYI().RT(str);
int i2 = z ? 2 : 1;
if (RT.field_Switch != i2) {
RT.field_Switch = i2;
com.tencent.mm.plugin.welab.b.bYI().qmM.c(RT, new String[0]);
aqh aqh = new aqh();
aqg aqg = new aqg();
aqg.rSI = bi.WU(RT.field_expId);
aqg.rSJ = RT.field_LabsAppId;
if (RT.field_Switch != 2) {
i = 2;
}
aqg.rDF = i;
aqh.dav.add(aqg);
((i) g.l(i.class)).FQ().b(new h.a(207, aqh));
e.n(str, RT.field_Switch == 2 ? 4 : 5, false);
}
}
}
|
package wad.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class DefaultController {
@RequestMapping("*")
@ResponseBody
public String home() {
return "Hei Maailma! Tästä tulee minun ensimmäinen sovellus";
}
}
|
package com.toracode.myreminder.database;
import android.database.Cursor;
import android.database.CursorWrapper;
import com.toracode.myreminder.Task;
import com.toracode.myreminder.database.TaskDbSchema.TaskTable;
import java.util.Date;
import java.util.UUID;
public class TaskCursorWrapper extends CursorWrapper {
public TaskCursorWrapper(Cursor cursor) {
super(cursor);
}
public Task getTask() {
String uuidString = getString(getColumnIndex(TaskTable.Cols.UUID));
String title = getString(getColumnIndex(TaskTable.Cols.TITLE));
long date = getLong(getColumnIndex(TaskTable.Cols.DATE));
int isDone = getInt(getColumnIndex(TaskTable.Cols.DONE));
Task task = new Task(UUID.fromString(uuidString));
task.setTitle(title);
task.setDate(new Date(date));
task.setDone(isDone != 0);
return task;
}
}
|
package br.org.funcate.glue.utilities.patterns;
/**
* @author MOREIRA, Vinicius Fernandes \brief Interface that represents the
* Subject in the Observer Design Pattern. This kind of subject sends
* updates to its observers when there is some action on it.
*/
public interface ActionSubject {
/**
* @author MOREIRA, Vinicius Fernandes \brief Method to add the target
* action observer for this subject.
* @param o
* The target action observer
* @return TRUE - Added.
*/
boolean addActionObserver(ActionObserver o);
/**
* @author MOREIRA, Vinicius Fernandes \brief Method to remove the target
* action observer for this subject.
* @param o
* The target action observer
* @return TRUE - Removed.
*/
boolean removeActionObserver(ActionObserver o);
/**
* @author MOREIRA, Vinicius Fernandes \brief Method to notify the observers
* of this subject that an action occurred.
*/
void notifyActionObservers();
}
|
package com.eason.lottert.controller;
import com.eason.lottert.bean.BallHistory;
import com.eason.lottert.bean.Note;
import com.eason.lottert.service.ForumService;
import com.eason.lottert.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import javax.persistence.criteria.Order;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @ 文件名: TestController
* @ 创建者: Eason
* @ 时间: 2018/9/25 15:11
* @ 描述:
*/
@Controller
public class IndexController {
@Autowired
private HistoryService historyService;
@Autowired
private ForumService forumService;
@GetMapping("/")
public String index(Model model, Integer pageNumber) {
Page<BallHistory> page = historyService.findByPage(pageNumber);
model.addAttribute("page", page);
int number = page.getNumber();
model.addAttribute("pageNow", number);
Note note = forumService.findTheLast();
model.addAttribute("note", note);
// List<BallHistory> histories = historyService.findAll();
// model.addAttribute("histories", histories);
return "index.html";
}
// @GetMapping("/detail")
// public String detail(HttpServletRequest request, String code, Model model) {
// for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
// System.out.println(entry.getKey() + " : " + entry.getValue());
// }
//
// System.out.println(code);
//// BallHistory history = historyService.find(code);
//// model.addAttribute("history", history);
// return "detail.html";
// }
}
|
package tzh.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by 001 on 2016/5/18.
*/
public class SecondActivity extends AppCompatActivity {
@BindView(R.id.btn_next)
Button btnNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ButterKnife.bind(this);
}
@OnClick(R.id.btn_next)
public void onClick() {
int i = 8 / 0;
}
}
|
/*
* Copyright (C) 2019-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.hedera.mirror.importer.parser.record.transactionhandler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.hedera.mirror.common.domain.entity.Entity;
import com.hedera.mirror.common.domain.entity.EntityId;
import com.hedera.mirror.common.domain.entity.EntityType;
import com.hedera.mirror.common.domain.schedule.Schedule;
import com.hederahashgraph.api.proto.java.AccountID;
import com.hederahashgraph.api.proto.java.CryptoCreateTransactionBody;
import com.hederahashgraph.api.proto.java.ResponseCodeEnum;
import com.hederahashgraph.api.proto.java.SchedulableTransactionBody;
import com.hederahashgraph.api.proto.java.ScheduleCreateTransactionBody;
import com.hederahashgraph.api.proto.java.ScheduleID;
import com.hederahashgraph.api.proto.java.TransactionBody;
import com.hederahashgraph.api.proto.java.TransactionReceipt;
import org.junit.jupiter.api.Test;
class ScheduleCreateTransactionHandlerTest extends AbstractTransactionHandlerTest {
@Override
protected TransactionHandler getTransactionHandler() {
return new ScheduleCreateTransactionHandler(entityIdService, entityListener, entityProperties);
}
@Override
protected TransactionBody.Builder getDefaultTransactionBody() {
SchedulableTransactionBody.Builder scheduledTransactionBodyBuilder = SchedulableTransactionBody.newBuilder()
.setCryptoCreateAccount(CryptoCreateTransactionBody.getDefaultInstance());
return TransactionBody.newBuilder()
.setScheduleCreate(ScheduleCreateTransactionBody.newBuilder()
.setAdminKey(DEFAULT_KEY)
.setPayerAccountID(AccountID.newBuilder()
.setShardNum(0)
.setRealmNum(0)
.setAccountNum(1)
.build())
.setMemo("schedule memo")
.setScheduledTransactionBody(scheduledTransactionBodyBuilder)
.build());
}
@Override
protected TransactionReceipt.Builder getTransactionReceipt(ResponseCodeEnum responseCodeEnum) {
return TransactionReceipt.newBuilder()
.setStatus(responseCodeEnum)
.setScheduleID(ScheduleID.newBuilder()
.setScheduleNum(DEFAULT_ENTITY_NUM)
.build());
}
@Override
protected EntityType getExpectedEntityIdType() {
return EntityType.SCHEDULE;
}
@Test
void updateTransactionSchedulesDisabled() {
// given
entityProperties.getPersist().setSchedules(false);
var recordItem = recordItemBuilder
.scheduleCreate()
.receipt(r -> r.setScheduleID(recordItemBuilder.scheduleId()))
.build();
var timestamp = recordItem.getConsensusTimestamp();
var transaction = domainBuilder
.transaction()
.customize(t -> t.consensusTimestamp(timestamp))
.get();
// when
transactionHandler.updateTransaction(transaction, recordItem);
// then
verify(entityListener, times(1)).onEntity(assertArg(t -> assertThat(t)
.isNotNull()
.returns(timestamp, Entity::getCreatedTimestamp)
.returns(false, Entity::getDeleted)
.satisfies(e -> assertThat(e.getMemo()).isNotEmpty())
.satisfies(e -> assertThat(e.getKey()).isNotEmpty())
.returns(timestamp, Entity::getTimestampLower)));
verify(entityListener, never()).onSchedule(any());
assertThat(recordItem.getEntityTransactions())
.containsExactlyInAnyOrderEntriesOf(getExpectedEntityTransactions(recordItem, transaction));
}
@Test
void updateTransactionSuccessful() {
// given
var recordItem = recordItemBuilder
.scheduleCreate()
.receipt(r -> r.setScheduleID(recordItemBuilder.scheduleId()))
.build();
var timestamp = recordItem.getConsensusTimestamp();
var transaction = domainBuilder
.transaction()
.customize(t -> t.consensusTimestamp(timestamp))
.get();
var schedulePayerAccountId =
EntityId.of(recordItem.getTransactionBody().getScheduleCreate().getPayerAccountID());
// when
transactionHandler.updateTransaction(transaction, recordItem);
// then
verify(entityListener, times(1)).onEntity(assertArg(t -> assertThat(t)
.isNotNull()
.returns(timestamp, Entity::getCreatedTimestamp)
.returns(false, Entity::getDeleted)
.satisfies(e -> assertThat(e.getMemo()).isNotEmpty())
.satisfies(e -> assertThat(e.getKey()).isNotEmpty())
.returns(timestamp, Entity::getTimestampLower)));
verify(entityListener, times(1)).onSchedule(assertArg(t -> assertThat(t)
.isNotNull()
.returns(timestamp, Schedule::getConsensusTimestamp)
.returns(recordItem.getPayerAccountId(), Schedule::getCreatorAccountId)
.returns(null, Schedule::getExecutedTimestamp)
.satisfies(s -> assertThat(s.getExpirationTime()).isPositive())
.returns(schedulePayerAccountId, Schedule::getPayerAccountId)
.satisfies(s -> assertThat(s.getScheduleId()).isPositive())
.satisfies(s -> assertThat(s.getTransactionBody()).isNotEmpty())
.returns(true, Schedule::isWaitForExpiry)));
assertThat(recordItem.getEntityTransactions())
.containsExactlyInAnyOrderEntriesOf(
getExpectedEntityTransactions(recordItem, transaction, schedulePayerAccountId));
}
@Test
void updateTransactionSuccessfulNoExpirationTime() {
// given
var recordItem = recordItemBuilder
.scheduleCreate()
.transactionBody(
b -> b.clearExpirationTime().clearPayerAccountID().setWaitForExpiry(false))
.receipt(r -> r.setScheduleID(recordItemBuilder.scheduleId()))
.build();
var payerAccountId = recordItem.getPayerAccountId();
var timestamp = recordItem.getConsensusTimestamp();
var transaction = domainBuilder
.transaction()
.customize(t -> t.consensusTimestamp(timestamp))
.get();
// when
transactionHandler.updateTransaction(transaction, recordItem);
// then
verify(entityListener, times(1)).onEntity(assertArg(t -> assertThat(t)
.isNotNull()
.returns(timestamp, Entity::getCreatedTimestamp)
.returns(false, Entity::getDeleted)
.satisfies(e -> assertThat(e.getMemo()).isNotEmpty())
.satisfies(e -> assertThat(e.getKey()).isNotEmpty())
.returns(timestamp, Entity::getTimestampLower)));
verify(entityListener, times(1)).onSchedule(assertArg(t -> assertThat(t)
.isNotNull()
.returns(timestamp, Schedule::getConsensusTimestamp)
.returns(recordItem.getPayerAccountId(), Schedule::getCreatorAccountId)
.returns(null, Schedule::getExecutedTimestamp)
.returns(null, Schedule::getExpirationTime)
.returns(payerAccountId, Schedule::getPayerAccountId)
.satisfies(s -> assertThat(s.getScheduleId()).isPositive())
.satisfies(s -> assertThat(s.getTransactionBody()).isNotEmpty())
.returns(false, Schedule::isWaitForExpiry)));
assertThat(recordItem.getEntityTransactions())
.containsExactlyInAnyOrderEntriesOf(
getExpectedEntityTransactions(recordItem, transaction, payerAccountId));
}
}
|
package com.yida.design.adapter.extension.impl;
import java.util.HashMap;
import java.util.Map;
import com.yida.design.adapter.extension.IOuterUserHomeInfo;
/**
*********************
* @author yangke
* @version 1.0
* @created 2018年5月31日 下午5:33:15
***********************
*/
public class OuterUserHomeInfo implements IOuterUserHomeInfo {
/*
* 员工的家庭信息
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Map getUserHomeInfo() {
HashMap homeInfo = new HashMap();
homeInfo.put("homeTelNumbner", "员工的家庭电话是...");
homeInfo.put("homeAddress", "员工的家庭地址是...");
return homeInfo;
}
}
|
package com.s24.redjob.queue;
import com.s24.redjob.worker.AbstractWorkerFactoryBean;
import java.util.List;
import org.springframework.beans.factory.FactoryBean;
/**
* {@link FactoryBean} for easy creation of a {@link FifoWorker}.
*/
public class FifoWorkerFactoryBean extends AbstractWorkerFactoryBean<FifoWorker> {
/**
* Queue dao.
*/
private FifoDaoImpl fifoDao;
/**
* Should worker start paused?. Defaults to false.
*/
private boolean startPaused = false;
/**
* Constructor.
*/
public FifoWorkerFactoryBean() {
super(new FifoWorker());
}
@Override
public void afterPropertiesSet() throws Exception {
worker.setFifoDao(fifoDao);
worker.pause(startPaused);
super.afterPropertiesSet();
}
//
// Injections.
//
/**
* Queue dao.
*/
public FifoDaoImpl getFifoDao() {
return fifoDao;
}
/**
* Queue dao.
*/
public void setFifoDao(FifoDaoImpl fifoDao) {
this.fifoDao = fifoDao;
}
/**
* Queues to listen to.
*/
public List<String> getQueues() {
return worker.getQueues();
}
/**
* Queues to listen to.
*/
public void setQueues(String... queues) {
worker.setQueues(queues);
}
/**
* Queues to listen to.
*/
public void setQueues(List<String> queues) {
worker.setQueues(queues);
}
/**
* Should worker start paused?. Defaults to false.
*/
public boolean isStartPaused() {
return startPaused;
}
/**
* Should worker start paused?. Defaults to false.
*/
public void setStartPaused(boolean startPaused) {
this.startPaused = startPaused;
}
}
|
package model;
import Database.HBConnection;
/**
*
* @author khattry
*
*/
public class Setup
{
public static void main(String[] args)
{
HBConnection db = new HBConnection();
// Mitarbeiter mitarbeiter=Mitarbeiter.createrMitarbeiter("heba",
// "emam", 67000);
// db.saveObject(mitarbeiter);
//
// Objekt von DB abholen
// Mitarbeiter mit=(Mitarbeiter) db.getObject(Mitarbeiter.class, 9);
// System.out.println(mit.toString());
// Object von DB löschen
// db.deleteObject(Mitarbeiter.class,10);
// Object updaten
// db.updateGehalt(Mitarbeiter.class,6,9999);
// List<Object> result =
// db.createSQLQuery("select * from Mitarbeiter where gehalt <9999",Mitarbeiter.class);
// for (Iterator<Object> iter = result.iterator(); iter.hasNext();)
// {
// Mitarbeiter mit = (Mitarbeiter) iter.next();
// System.out.println(mit.toString());
// }
// }
Pers p1=new Pers("khattry");
Pers p2=new Pers("heba");
Pers p3=new Pers("ammar");
Pers p4=new Pers("sabina");
Pers p5=new Pers("stefan");
Pers p6=new Pers("julia");
db.saveObject(p1);
db.saveObject(p2);
db.saveObject(p3);
db.saveObject(p4);
db.saveObject(p5);
db.saveObject(p6);
Projekt pro1=new Projekt();
Projekt pro2=new Projekt();
pro1.setBezeichnung("VW");
pro2.setBezeichnung("DB");
pro1.getPersonen().add(p6);
pro1.getPersonen().add(p5);
pro1.getPersonen().add(p4);
pro1.getPersonen().add(p3);
pro1.getPersonen().add(p2);
pro2.getPersonen().add(p1);
db.saveObject(pro1);
db.saveObject(pro2);
Abt hamburg=new Abt("IT","Hamburg");
hamburg.getPersonen().add(p1);
hamburg.getPersonen().add(p2);
hamburg.getPersonen().add(p3);
hamburg.getPersonen().add(p4);
Abt kiel=new Abt("Personal","Kiel");
kiel.getPersonen().add(p5);
kiel.getPersonen().add(p6);
db.saveObject(hamburg);
db.saveObject(kiel);
}
}
|
package com.zhouyi.business.core.dao;
public interface BuffBaseMapper<T,V> extends BaseMapper<T,V> {
int deleteByPrimaryKey(String pkId);
int insert(T t);
int insertSelective(T t);
T selectByPrimaryKey(String pkId);
int updateByPrimaryKeySelective(T t);
int updateByPrimaryKey(T t);
int findTotal(V v);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.