text
stringlengths 10
2.72M
|
|---|
package com.plenumsoft.vuzee.controllers;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.plenumsoft.vuzee.entities.Candidate;
import com.plenumsoft.vuzee.services.CandidateService;
import com.plenumsoft.vuzee.viewmodels.CandidateCreateViewModel;
@Controller
@RequestMapping(value= {"/candidates"})
public class CandidatesController {
String prefix = "candidates/";
private CandidateService candidateService;
public CandidatesController() {
}
@Autowired
public CandidatesController(CandidateService candidateService) {
super();
this.candidateService = candidateService;
}
@RequestMapping(value = { "/", "" })
public ModelAndView Index() {
ModelAndView mv = new ModelAndView(prefix +"index");
List<Candidate> candidates= candidateService.getAll();
mv.addObject("candidates", candidates);
return mv;
}
@RequestMapping(value = { "/create"})
public String PrepareCreate(CandidateCreateViewModel candidateCreateViewModel) {
return prefix+"create";
}
@RequestMapping(value="/create",method=RequestMethod.POST)
public String PostCreateCandidate(@Valid CandidateCreateViewModel candidateCreateViewModel, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return prefix+"create";
}
Candidate candidate = new Candidate();
candidate.setName(candidateCreateViewModel.getName());
candidate.setPositionApplied(candidateCreateViewModel.getPositionApplied());
candidate.setCreatedBy("msoberanis");//TODO: hard-code
Date now = new Date();
candidate.setCreatedAt(new Date());
candidateService.addCandidate(candidate);
return "redirect:/"+ prefix +"/";
}
@RequestMapping(value = { "/edit/{id}"})
public String PrepareEdit(@PathVariable("id") int id) {
//"id" es el id del candidato
return prefix+"edit";
}
}
|
package com.gp.beershop.mock;
import com.gp.beershop.dto.CustomerOrder;
import com.gp.beershop.dto.Orders;
import com.gp.beershop.dto.UserDTO;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public final class OrderMock {
private OrderMock() {
}
private static Map<Integer, Orders> ordersMap = new HashMap<>() {{
put(1, Orders.builder()
.id(1)
.userDTO(UsersMock.getById(1))
.processed(true)
.total(BigDecimal.valueOf(25).setScale(2))
.canceled(false)
.customerOrders(
List.of(
CustomerOrder.builder()
.beer(BeerMock.getById(1))
.amount(2)
.build(),
CustomerOrder.builder()
.beer(BeerMock.getById(2))
.amount(5)
.build()
))
.build());
put(2, Orders.builder()
.id(2)
.userDTO(UsersMock.getById(2))
.processed(false)
.canceled(false)
.total(BigDecimal.valueOf(27).setScale(2))
.customerOrders(
List.of(
CustomerOrder.builder()
.beer(BeerMock.getById(2))
.amount(1)
.build(),
CustomerOrder.builder()
.beer(BeerMock.getById(3))
.amount(3)
.build()
))
.build());
put(4, Orders.builder()
.id(2)
.userDTO(UsersMock.getById(4))
.processed(false)
.canceled(false)
.total(BigDecimal.valueOf(27).setScale(2))
.customerOrders(
List.of(
CustomerOrder.builder()
.beer(BeerMock.getById(2))
.amount(1)
.build(),
CustomerOrder.builder()
.beer(BeerMock.getById(3))
.amount(3)
.build()
))
.build());
}};
public static Orders getById(final Integer id) {
return ordersMap.get(id);
}
public static List<Orders> getAllValues() {
return ordersMap.values()
.stream()
.map(order -> Orders.builder()
.id(order.getId())
.userDTO(
UserDTO.builder()
.id(order.getUserDTO().getId())
.firstName(order.getUserDTO().getFirstName())
.secondName(order.getUserDTO().getSecondName())
.email(order.getUserDTO().getEmail())
.phone(order.getUserDTO().getPhone())
.build())
.processed(order.getProcessed())
.canceled(order.getCanceled())
.total(order.getTotal())
.customerOrders(order.getCustomerOrders())
.build()).collect(Collectors.toList());
}
public static List<Orders> getAllValuesBusinessLogic() {
return ordersMap.entrySet().stream()
.filter(order -> order.getKey() == 1 || order.getKey() == 4)
.map(Map.Entry::getValue)
.map(order -> Orders.builder()
.id(order.getId())
.userDTO(
UserDTO.builder()
.id(order.getUserDTO().getId())
.firstName(order.getUserDTO().getFirstName())
.secondName(order.getUserDTO().getSecondName())
.email(order.getUserDTO().getEmail())
.phone(order.getUserDTO().getPhone())
.build())
.processed(order.getProcessed())
.canceled(order.getCanceled())
.total(order.getTotal())
.customerOrders(order.getCustomerOrders())
.build()).collect(Collectors.toList());
}
}
|
package com.example.currencyrestfulservice.service;
import com.example.currencyrestfulservice.model.Gif;
public interface GifCurrencyService {
Gif getRelevantGif(String symbol);
}
|
package interfaces;
import java.util.List;
import modelo.Administrativo;
import modelo.Cliente;
import modelo.Profesional;
import modelo.Usuario;
public interface Iusuario {
public List<Usuario> obtenerUsuario();
public boolean crearUsuario(Usuario Usr);
boolean crearCliente(Cliente cli);
boolean crearAdministrativo(Administrativo Adm);
boolean crearProfesional(Profesional Pro);
public Profesional obtenerProfesionalPorRun(int runusuario);
boolean editarProfessional(Profesional editpro);
public Cliente obtenerClientePorRun(int runusuario);
boolean editarCliente(Cliente editcli);
public Administrativo obtenerAdministrativoPorRun(int runusuario);
boolean editarAdministrativo(Administrativo editadm);
}
|
package test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Test8 {
public static void main(String[] args) {
try {
List<String> messages = Files.readAllLines(Paths.get("D:\\my_all_messages_20160118\\unparsedMessages_0.txt"));
int sum=0;
for(String message: messages){
sum+=message.length();
}
System.out.println("Average length: "+ sum/messages.size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// current result
// Average length: 152
|
package umk.net.slafs.domain;
import java.util.Calendar;
import org.junit.Test;
import org.springframework.transaction.annotation.Transactional;
public class ProjektTest extends EwidenterionTest {
protected Long doAdd() {
Projekt p = new Projekt();
Calendar cal = Calendar.getInstance();
FazaTest ft = new FazaTest();
Faza f = ft.doAdd();
f.persist();
Long FazaIDEK = f.getId();
p.setName("Nowa aplikacja");
p.setClient("Leroy Merlin");
p.setDescription("Taki dość długaśny opis");
p.setStarted(cal.getTime());
p.setTerm(cal.getTime());
p.setDefaultFaza(Faza.findFaza(FazaIDEK));
p.persist();
return p.getId();
}
@Test
@Transactional
public void addTest() {
int before = Projekt.findAllProjekts().size();
doAdd();
int after = Projekt.findAllProjekts().size();
assertTrue(before < after);
}
@Test
@Transactional
public void deleteTest() {
Long IDEK = doAdd();
int before = Projekt.findAllProjekts().size();
Projekt forDelete = Projekt.findProjekt(IDEK);
forDelete.remove();
int after = Projekt.findAllProjekts().size();
assertNull(Projekt.findProjekt(IDEK));
assertTrue(after < before);
}
@Test
@Transactional
public void updateTest() {
String newWord = "Inna aplikacja";
Long IDEK = doAdd();
Projekt u = Projekt.findProjekt(IDEK);
u.setName(newWord);
u.merge();
Projekt afterUpdate = Projekt.findProjekt(IDEK);
assertSame(u.getName(), afterUpdate.getName());
}
}
|
package com.tencent.mm.plugin.wallet_core.ui;
import com.tencent.mm.protocal.c.fd;
import java.util.Comparator;
class WalletSwitchVerifyPhoneUI$2 implements Comparator<fd> {
final /* synthetic */ WalletSwitchVerifyPhoneUI pyw;
WalletSwitchVerifyPhoneUI$2(WalletSwitchVerifyPhoneUI walletSwitchVerifyPhoneUI) {
this.pyw = walletSwitchVerifyPhoneUI;
}
public final /* synthetic */ int compare(Object obj, Object obj2) {
fd fdVar = (fd) obj;
fd fdVar2 = (fd) obj2;
if (fdVar.rfW.equals("wx") && fdVar2.rfW.equals("cft")) {
return -1;
}
return (fdVar.rfW.equals("cft") && fdVar2.rfW.equals("wx")) ? 1 : 0;
}
}
|
class Solution {
List<String>
ans = new ArrayList();
public List<String> generateParenthesis(int n) {
generate(n, 0, 0, "");
return ans;
}
void generate(int n, int open, int close, String temp)
{
if(open == close && open == n)
{
ans.add(temp);
return;
}
if(open < n)
{
generate(n, open + 1, close, temp + '(');
}
if(close < open)
{
generate(n, open, close + 1, temp + ')');
}
}
}
|
package JavaSE.OO.guanjianzi;
/*
* 例子,未传参数时默认显示1970年1月1号
* this可以用在哪里
* 可以使用在实例方法中,代表当前对象,语法格式:this.
* 可以使用在构造方法中,通过当前的构造方法调用其他的构造方法,语法格式:this(实参)
*/
class Data{
int year;
int mouth;
int day;
//构造函数
public Data() {
//System.out.println();
// this.day=1;
// this.mouth=1;
// this.year=1970;
//以上代码可以通过调用另一个构造方法来完成
//但前提是不能创建新的对象,但以下代码创建了一个新的对象
//new Data(1970,1,1);
//需要采用以下的方式来完成构造方法的调用,这种方式不会创建新的java对象
this(1970,1,1);//这个语句只能出现在构造函数第一行,所以只能出现一次
}
public Data(int year,int mouth,int day) {
this.day=day;
this.year=year;
this.mouth=mouth;
}
//get,set方法
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMouth() {
return mouth;
}
public void setMouth(int mouth) {
this.mouth = mouth;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public void print() {
System.out.println(this.year+"年"+this.mouth+"月"+this.day+"号");
}
}
public class ThisTest04 {
public static void main(String[] args) {
Data d=new Data();
d.print();
Data dd=new Data(2020,1,1);
dd.print();
}
}
|
package com.challenge.interfaces;
import java.math.BigDecimal;
public interface Calculavel {
BigDecimal somar(Object klass) throws IllegalAccessException;
BigDecimal subtrair(Object klass) throws IllegalAccessException;
BigDecimal totalizar(Object klass) throws IllegalAccessException;
}
|
package com.ibeiliao.pay.platform.api.dto;
import java.io.Serializable;
/**
* 平台授权的信息
* @author linyi 2016/7/20.
*/
public class PlatformAuth implements Serializable {
private static final long serialVersionUID = 1;
/** authId */
private int authId;
/** 平台ID */
private int platformId;
/** accessPlatformId */
private int accessPlatformId;
/** accessFunc */
private String accessFunc;
/**
* 说明
*/
private String remark;
public int getAuthId() {
return authId;
}
public void setAuthId(int authId) {
this.authId = authId;
}
public int getPlatformId() {
return platformId;
}
public void setPlatformId(int platformId) {
this.platformId = platformId;
}
public int getAccessPlatformId() {
return accessPlatformId;
}
public void setAccessPlatformId(int accessPlatformId) {
this.accessPlatformId = accessPlatformId;
}
public String getAccessFunc() {
return accessFunc;
}
public void setAccessFunc(String accessFunc) {
this.accessFunc = accessFunc;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
|
package com.janfranco.datifysongbasedmatchapplication;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Typeface;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class BlockedListRecyclerAdapter extends RecyclerView.Adapter<BlockedListRecyclerAdapter.BlockHolder> {
private ArrayList<Block> blocks;
private static Typeface metropolisLight;
private static Typeface metropolisExtraLightItalic;
BlockedListRecyclerAdapter(Context context, ArrayList<Block> blocks) {
metropolisLight = Typeface.createFromAsset(context.getAssets(), "fonts/Metropolis-Light.otf");
metropolisExtraLightItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Metropolis-ExtraLightItalic.otf");
this.blocks = blocks;
}
@NonNull
@Override
public BlockHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.blocklist_row, parent, false);
return new BlockHolder(view);
}
@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(@NonNull BlockHolder holder, int position) {
Block block = blocks.get(position);
holder.username.setText(block.getUsername());
holder.reason.setText(block.getReason());
holder.date.setText(DateFormat.format(
Constants.DATE_MESSAGE,
block.getCreateDate() * 1000L
).toString());
Picasso.get().load(block.getAvatarUrl()).into(holder.avatar);
}
@Override
public int getItemCount() {
return blocks.size();
}
static class BlockHolder extends RecyclerView.ViewHolder {
ImageView avatar;
TextView username, reason, date;
BlockHolder(@NonNull View itemView) {
super(itemView);
avatar = itemView.findViewById(R.id.blockListAvatar);
username = itemView.findViewById(R.id.blockListUsername);
reason = itemView.findViewById(R.id.blockListReason);
date = itemView.findViewById(R.id.blockListDate);
username.setTypeface(metropolisLight);
reason.setTypeface(metropolisLight);
date.setTypeface(metropolisExtraLightItalic);
}
}
}
|
package com.cse.sportsplus.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.cse.sportsplus.models.Coach;
public interface CoachRepository extends JpaRepository<Coach, Long> {
@Query(value="select coach_id from tbl_coach", nativeQuery=true)
public List<java.math.BigInteger>getAllCoachID();
}
|
package net.tyas.laundry.ui.detail;
import net.tyas.laundry.ui.base.MvpPresenter;
public interface DetailMvpPresenter<V extends DetailView> extends MvpPresenter<V> {
void getService(int categoryId);
}
|
package br.com.pcmaker.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "ordem_servico_acessorio")
public class OrdemServicoAcessorio extends AutoIncrementIdEntity {
/**
*
*/
private static final long serialVersionUID = 1L;
private OrdemServico ordemServico;
private Acessorio acessorio;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ordem_servico_id", nullable = false)
public OrdemServico getOrdemServico() {
return ordemServico;
}
public void setOrdemServico(OrdemServico ordemServico) {
this.ordemServico = ordemServico;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "acessorio_id", nullable = false)
public Acessorio getAcessorio() {
return acessorio;
}
public void setAcessorio(Acessorio acessorio) {
this.acessorio = acessorio;
}
}
|
package at.ebinterface.validation.web.pages;
import javax.annotation.Nullable;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import com.helger.commons.annotation.UsedViaReflection;
import at.ebinterface.validation.validator.ValidationResult;
import at.ebinterface.validation.web.pages.resultpages.ResultPanel;
public final class ServicePage extends BasePage
{
/**
* Default constructor for initial showing.
*/
@UsedViaReflection
public ServicePage ()
{
// Add the input form
final ServiceForm inputForm = new ServiceForm ("inputForm");
add (inputForm);
add (new EmptyPanel ("resultPanel"));
}
/**
* Constructor for the result page
*
* @param validationResult
* Validation result
* @param pdf
* Created PDF
*/
public ServicePage (final ValidationResult validationResult, @Nullable final byte [] pdf)
{
// Add the input form
final ServiceForm inputForm = new ServiceForm ("inputForm");
add (inputForm);
if (validationResult != null)
add (new ResultPanel ("resultPanel", validationResult, pdf, null, null, null));
else
add (new EmptyPanel ("resultPanel"));
}
}
|
package great.dog.api.util;
import java.sql.Timestamp;
public class TypeUtils {
public static Timestamp StringToTimestamp(String s){
return Timestamp.valueOf(s);
}
}
|
package chapter05;
import java.util.Scanner;
public class Exercise05_29 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the year:");
int year = input.nextInt();
boolean isLeap = (year % 4 == 0 && year % 100 != 0 ) || (year % 400 == 0 && year % 4000 != 0);
System.out.println("Enter first day of the year: ");
int firstDay = input.nextInt();
int daysOfTheMonth = 0;
int count = firstDay;
for (int month = 1; month <= 12; month++) {
System.out.println();
switch (month) {
case 1:daysOfTheMonth=31;System.out.println("\t\tJanuary");break;
case 2:if(isLeap)daysOfTheMonth=29;else daysOfTheMonth=28;System.out.println("\t\tFebruary");break;
case 3:daysOfTheMonth=31;System.out.println("\t\tMarch");break;
case 4:daysOfTheMonth=30;System.out.println("\t\tApril");break;
case 5:daysOfTheMonth=31;System.out.println("\t\tMay");break;
case 6:daysOfTheMonth=30;System.out.println("\t\tJune");break;
case 7:daysOfTheMonth=31;System.out.println("\t\tJuly");break;
case 8:daysOfTheMonth=31;System.out.println("\t\tAugust");break;
case 9:daysOfTheMonth=30;System.out.println("\t\tSeptember");break;
case 10:daysOfTheMonth=31;System.out.println("\t\tOctober");break;
case 11:daysOfTheMonth=30;System.out.println("\t\tNovember");break;
case 12:daysOfTheMonth=31;System.out.println("\t\tDecember");break;}
System.out.println("---------------------------------");
System.out.printf("%-5s%-5s%-5s%-5s%-5s%-5s%-5s\n","Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
for (int spaces = 0; spaces < firstDay%7; spaces++) {
System.out.print(" ");
}
for(int i=1;i<=daysOfTheMonth;i++) {
if(count%7==0)System.out.println();
System.out.printf("%-5d",i);
count++;count%=7;
}
System.out.println();
firstDay=(firstDay+daysOfTheMonth)%7;
}
}
}
|
package com.tencent.mm.plugin.qqmail.ui;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.R;
import com.tencent.mm.ui.base.h;
class ComposeUI$8 implements OnClickListener {
final /* synthetic */ ComposeUI mfs;
ComposeUI$8(ComposeUI composeUI) {
this.mfs = composeUI;
}
public final void onClick(View view) {
h.a(this.mfs, null, new String[]{this.mfs.getString(R.l.plugin_qqmail_composeui_attach_take_phote), this.mfs.getString(R.l.plugin_qqmail_composeui_attach_choose_album), this.mfs.getString(R.l.plugin_qqmail_composeui_attach_choose_file)}, null, new 1(this));
}
}
|
package fr.insy2s.service.mapper;
import fr.insy2s.domain.*;
import fr.insy2s.service.dto.AddressDTO;
import org.mapstruct.*;
/**
* Mapper for the entity {@link Address} and its DTO {@link AddressDTO}.
*/
@Mapper(componentModel = "spring", uses = {})
public interface AddressMapper extends EntityMapper<AddressDTO, Address> {
@Named("id")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
AddressDTO toDtoId(Address address);
}
|
package com.tencent.mm.g.a;
public final class ec$b {
public boolean bLW;
}
|
package com.mtsmda.tools.gui.logic;
import com.mtsmda.tools.gui.util.CollectionUtil;
import com.mtsmda.tools.gui.util.FileUtil;
import com.mtsmda.tools.gui.util.StringUtil;
import jdk.internal.org.xml.sax.ErrorHandler;
import jdk.internal.org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Created by c-DMITMINZ on 23.07.2015.
*/
public class XMLValidationXSD {
public static void main(String[] args) throws Exception {
/*// String parent = "C:\\PROJECTS\\IntegrationFramework\\src\\test\\resources\\integrationTestData\\CA_RX\\CA_RX_2.2\\";
String parent = "c:\\PROJECTS\\IntegrationFramework\\src\\test\\resources\\integrationTestData\\CA_RX\\CA_RX_4.2\\";
String xsd = "C:\\Edifecs\\ArtifactsRepository\\Guidelines\\EdctResponse.xsd";
List<String> paths = new ArrayList<>();
System.out.println(findFilesRecursively(parent, "resp_ca_cl", paths));
System.out.println(paths.size());
for (String path : paths) {
System.out.println(path);
// DomParserEncounterValidationResponse.modifyEncounterType(path);
List<SAXParseException> saxParseExceptions = validateXMLSchema(xsd, path);
for (SAXParseException saxParseException : saxParseExceptions) {
System.out.println(saxParseException.getMessage());
}
}*/
}
private static String findFilesRecursively(String fileName, String fileNamePattern, List<String> paths) {
if (fileName != null && !fileName.trim().isEmpty()) {
return findFilesRecursively(new File(fileName), fileNamePattern, paths);
}
return "";
}
private static String findFilesRecursively(File fileDirectory, String fileNamePattern, List<String> paths) {
if (fileDirectory.exists()) {
if (fileDirectory.isDirectory()) {
if (fileDirectory.listFiles().length != 0) {
for (File currentFile : fileDirectory.listFiles())
findFilesRecursively(currentFile, fileNamePattern, paths);
}
} else {
if (fileDirectory.getAbsolutePath().contains(fileNamePattern) && fileDirectory.getAbsolutePath().endsWith(".xml")) {
paths.add(fileDirectory.getAbsolutePath());
}
}
}
return "";
}
public static List<SAXParseException> validateXMLSchema(String xsdPath, String xmlPath) {
final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
/*validator.setErrorHandler(new org.xml.sax.ErrorHandler() {
@Override
public void warning(org.xml.sax.SAXParseException exception) throws org.xml.sax.SAXException {
exceptions.add(exception);
}
@Override
public void error(org.xml.sax.SAXParseException exception) throws org.xml.sax.SAXException {
exceptions.add(exception);
}
@Override
public void fatalError(org.xml.sax.SAXParseException exception) throws org.xml.sax.SAXException {
exceptions.add(exception);
}
});*/
} catch (Exception e) {
System.out.println(e.getMessage());
}
return exceptions;
}
}
|
package com.sixmac.service;
import com.sixmac.entity.Order;
import com.sixmac.entity.Reserve;
import com.sixmac.entity.UserReserve;
import com.sixmac.service.common.ICommonService;
import org.springframework.data.domain.Page;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2016/5/19 0019 上午 11:54.
*/
public interface ReserveService extends ICommonService<Reserve> {
public List<Reserve> findByUserId(Long userId);
public Page<Reserve> page(Integer timelimit, Integer type, Long areaId, Integer pageNum, Integer pageSize);
public List<Reserve> findNew();
// 约球邀请
public void order(HttpServletResponse response,
Long reserveId,
Long userId,
Long toUserId);
// 球友的赛事列表
public Map<String, Object> raceList(HttpServletResponse response, Long playerId);
public Order pay(HttpServletResponse response, Long reserveId, Long userId, Long messageId, Double money);
}
|
package ru.job4j.list;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 3. Конвертация ArrayList в двухмерный массив [#10035]
*/
public class ConvertList2Array {
/**
* Метод принимает коллекцию лист, и количество строк в двумерном массиве. Если в массиве не хватает элементов,
* метод ставит туда нули.
* @param list - принимаемая коллекция List
* @param rows - количество рядов (строк) в двумерном массиве
* @return Возвращает двумерный массив типа int[][]
*/
public int[][] toArray(List<Integer> list, int rows) {
int cells = (int) Math.ceil((list.size() / (double) rows)); //получили количество столбцов
int[][] array = new int[rows][cells]; //Создали ммассив для возвращения и в цикле заполнили его
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cells; j++) {
if (index < list.size()) {
array[i][j] = list.get(index);
index++;
} else {
break;
}
}
}
return array;
}
public static void main(String[] args) {
ConvertList2Array convertList2Array = new ConvertList2Array();
Integer[] a = {1, 2, 3, 4, 5, 6, 7};
List<Integer> list = new ArrayList<>(Arrays.asList(a));
int[][] w = convertList2Array.toArray(list, 3);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(w[i][j] + " ");
}
System.out.println("");
}
}
}
|
package com.smxknife.java.ex11;
public class IntTypeSwap {
public static void main(String[] args) {
IntType type1 = new IntType();
type1.setValue(1);
IntType type2 = new IntType();
type2.setValue(2);
swap1(type1, type2);
System.out.printf("type1.value = %s, type2.value = %s", type1.getValue(), type2.getValue());
swap2(type1, type2);
System.out.println();
System.out.printf("type1.value = %s, type2.value = %s", type1.getValue(), type2.getValue());
}
public static void swap2(IntType type1, IntType type2) {
int temp = type1.getValue();
type1.setValue(type2.getValue());
type2.setValue(temp);
}
public static void swap1(IntType type1, IntType type2) {
IntType type = type1;
type1 = type2;
type2 = type;
}
}
|
package step._09_Basic_Math_02;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
/* date : 2021-07-31 (토)
* author : develiberta
* number : 04153
*
* [단계]
* 09. 기본 수학 2
* 소수와 기하를 다뤄 봅시다.
* [제목]
* 09. 직각삼각형 (04153)
* 피타고라스의 정리에 대해 배우는 문제
* [문제]
* 과거 이집트인들은 각 변들의 길이가 3, 4, 5인 삼각형이 직각 삼각형인것을 알아냈다.
* 주어진 세변의 길이로 삼각형이 직각인지 아닌지 구분하시오.
* [입력]
* 입력은 여러개의 테스트케이스로 주어지며 마지막줄에는 0 0 0이 입력된다.
* 각 테스트케이스는 모두 30,000보다 작은 양의 정수로 주어지며, 각 입력은 변의 길이를 의미한다.
* [출력]
* 각 입력에 대해 직각 삼각형이 맞다면 "right", 아니라면 "wrong"을 출력한다.
* (예제 입력 1)
* 6 8 10
* 25 52 60
* 5 12 13
* 0 0 0
* (예제 출력 1)
* right
* wrong
* right
*/
public class _09_04153_RightTriangle {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
String input;
while ((input = br.readLine()).equals("0 0 0") == false) {
st = new StringTokenizer(input, " ");
List<Integer> inputList = new ArrayList<>();
while (st.hasMoreTokens()) {
inputList.add(Integer.parseInt(st.nextToken()));
}
Collections.sort(inputList);
if (Math.pow(inputList.get(0), 2) + Math.pow(inputList.get(1), 2) == Math.pow(inputList.get(2), 2)) {
bw.write("right");
} else {
bw.write("wrong");
}
bw.write("\n");
}
br.close();
bw.flush();
bw.close();
}
}
|
package com.pybeta.daymatter.yiji.db;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.pybeta.daymatter.Config;
import android.content.Context;
public class DBManager {
/*
*
* ClassName: FileTool Function: TODO date: 2014-3-11 下午2:10:50
* @author Devin.Yu
*
*/
private Context mContext;
public static String DB_PATH=Config.APP_PATH;
public static final String DB_Name="yiji.db";
public static DBManager dbmanager;
public static DBManager getDBManager(Context context)
{
if(dbmanager==null)
{
dbmanager=new DBManager(context);
}
return dbmanager;
}
public DBManager(Context context)
{
this.mContext=context;
}
public static void WriteDBFile(Context context,int rawID,String DB_Name) {
try {
File file=new File(DB_PATH);
if(!file.exists())
{
file.mkdir();
}
File dbfile=new File(DB_PATH+DB_Name);
if(!dbfile.exists())
{
InputStream input =context.getResources().openRawResource(rawID);
byte[] buf = new byte[1024];
int Sum = 0;
FileOutputStream fout = null;
fout = new FileOutputStream(DB_PATH+DB_Name);
while ((Sum = input.read(buf)) != -1) {
fout.write(buf, 0, Sum);
}
fout.flush();
fout.close();
input.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.ecomerce.web.webservice.repository;
import com.ecomerce.web.webservice.model.Usuario;
import com.ecomerce.web.webservice.utils.Enums.TipoUsuario;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface UsuarioRepository extends CrudRepository<Usuario, Long> {
List<Usuario> findByTipoUsuario(TipoUsuario tipoUsuario);
}
|
import java.io.Serializable;
public class User implements Serializable{
private String name;
public User(Client c){
name = new String("default");
}
public User(String name){
this.name = new String("name");
}
public String getName(){
return name;
}
public void setName(String name){
this.name = new String(name);
}
}
|
package com.kmilewsk.github.Web.Controller;
import com.kmilewsk.github.Model.UserOutputDto;
import com.kmilewsk.github.Service.GitHubService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GitHubController {
private final GitHubService gitHubService;
public GitHubController(GitHubService gitHubService) {
this.gitHubService = gitHubService;
}
@GetMapping(value = "/users/{login}")
@ResponseStatus(HttpStatus.OK)
public UserOutputDto getUserInfo(@PathVariable String login){
return gitHubService.getInfoForUser(login); }
}
|
package org.apache.commons.net.examples.nntp;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.SocketException;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ProtocolCommandListener;
import org.apache.commons.net.nntp.Article;
import org.apache.commons.net.nntp.NNTPClient;
import org.apache.commons.net.nntp.NewsgroupInfo;
import org.apache.commons.net.nntp.Threader;
public class MessageThreading {
public static void main(String[] args) throws SocketException, IOException {
if (args.length != 2 && args.length != 4) {
System.out.println("Usage: MessageThreading <hostname> <groupname> [<user> <password>]");
return;
}
String hostname = args[0];
String newsgroup = args[1];
NNTPClient client = new NNTPClient();
client.addProtocolCommandListener((ProtocolCommandListener)new PrintCommandListener(new PrintWriter(System.out), true));
client.connect(hostname);
if (args.length == 4) {
String user = args[2];
String password = args[3];
if (!client.authenticate(user, password)) {
System.out.println("Authentication failed for user " + user + "!");
System.exit(1);
}
}
String[] fmt = client.listOverviewFmt();
if (fmt != null) {
System.out.println("LIST OVERVIEW.FMT:");
byte b;
int i;
String[] arrayOfString;
for (i = (arrayOfString = fmt).length, b = 0; b < i; ) {
String s = arrayOfString[b];
System.out.println(s);
b++;
}
} else {
System.out.println("Failed to get OVERVIEW.FMT");
}
NewsgroupInfo group = new NewsgroupInfo();
client.selectNewsgroup(newsgroup, group);
long lowArticleNumber = group.getFirstArticleLong();
long highArticleNumber = lowArticleNumber + 5000L;
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\examples\nntp\MessageThreading.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package br.com.helpdev.quaklog.parser.impl;
import br.com.helpdev.quaklog.processor.parser.GameParserException;
import br.com.helpdev.quaklog.processor.parser.impl.KillParser;
import br.com.helpdev.quaklog.processor.parser.objects.KillObParser;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class KillParserTest {
private final KillParser parser = new KillParser();
private enum Kill {
FIRST("14:52 Kill: 5 3 3: Oootsimo killed Dono da Bola by MOD_MACHINEGUN", "14:52", 5, 3, 3, "Oootsimo", "Dono da Bola", "MOD_MACHINEGUN"),
SECOND("14:54 Kill: 1022 7 22: <world> killed Assasinu Credi by MOD_TRIGGER_HURT", "14:54", 1022, 7, 22, "<world>", "Assasinu Credi", "MOD_TRIGGER_HURT"),
THIRD("14:57 Kill: 2 6 13: Isgalamido killed Chessus by MOD_BFG_SPLASH", "14:57", 2, 6, 13, "Isgalamido", "Chessus", "MOD_BFG_SPLASH"),
FOURTH("15:13 Kill: 7 4 7: Assasinu Credi killed Zeh by MOD_ROCKET_SPLASH", "15:13", 7, 4, 7, "Assasinu Credi", "Zeh", "MOD_ROCKET_SPLASH");
String line;
KillObParser killObParser;
Kill(String line, String expectedTime,
Integer killerID,
Integer killedID,
Integer modeID,
String killerName,
String killedName,
String mode
) {
this.line = line;
killObParser = KillObParser.builder()
.gameTime(expectedTime)
.killerID(killerID)
.killedID(killedID)
.killedModeID(modeID)
.killer(killerName)
.killed(killedName)
.killedMode(mode)
.build();
}
}
@Test
void shouldThrowGameParseExceptionWhenParseInvalidFormat() {
assertThrows(GameParserException.class, () -> parser.parse("abc abc abc"));
}
@Test
void parseClientBeginWithSuccess() {
assertTrue(Arrays.stream(Kill.values()).allMatch(this::assertParse));
}
private boolean assertParse(Kill valueToParse) {
KillObParser parse = parse(valueToParse.line);
return parse.equals(valueToParse.killObParser);
}
private KillObParser parse(String value) {
try {
return parser.parse(value);
} catch (GameParserException e) {
throw new RuntimeException(e);
}
}
}
|
package tema13.estrutura;
import tema13.interfaces.IContato;
import tema13.interfaces.IMensagem;
import java.util.Optional;
public class MensagemOlaCliente implements IMensagem {
private String emailRemetente;
private IContato iContato;
private String assunto;
private String mensagem;
public MensagemOlaCliente(IContato iContato) {
this.setiContato(iContato);
this.setEmailRemetente("ola.cliente@ilegra.com");
this.setAssunto("Tema 13");
this.setMensagem("Hello, " + iContato.getNome() + "!");
}
public String getEmailRemetente() {
return this.emailRemetente;
}
private void setEmailRemetente(String emailRemetente) {
this.emailRemetente = emailRemetente;
}
@Override
public void setMensagemPadrao() {
this.setAssunto("Tema 13");
this.setMensagem("Hello, " + iContato.getNome() + "!");
}
@Override
public IContato getiContato() {
return iContato;
}
@Override
public Optional<String> getTelefone() {
return this.iContato.getTelefone();
}
@Override
public String getEmailDestinatario() {
if(this.iContato.temTelefone()) {
return this.iContato.getTelefone().get() + "@tmomail.net";
}
return this.iContato.getEmail();
}
public void setiContato(IContato iContato) {
this.iContato = iContato;
}
@Override
public String getMensagem() {
return this.mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
@Override
public String getAssunto() {
return this.assunto;
}
public void setAssunto(String assunto) {
this.assunto = assunto;
}
}
|
package lt.kaunascoding.web.model.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class MysqlConnector {
public Connection Connect() {
Connection conn = null;
try {
// db parameters
String url = "jdbc:sqlite:D:\\Programs\\Projects\\springTest\\src\\main\\resources\\static\\webdata.db";
// create a connection to the database
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
}
return conn;
}
/*
public Connection Connect() {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
}catch (SQLException o){
} catch (ClassNotFoundException e){
}
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://192.168.100.100:3306/webpage?useUnicode=yes&characterEncoding=UTF-8","root", "root");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
} else {
System.out.println("Failed to make connection!");
}
return connection;
}
*/
}
|
package com.sharjeelmk.classes_objects;
public class Developer extends Person {
public Developer(String name,int age){
super(name,age); //super is ues for calling parent constructor
}
public void greetings(){
System.out.println("Howdy dev");
}
}
|
package trivagoPages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BasePage extends Page {
public BasePage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
@Override
public String getElementText(By locator) {
return getElement(locator).getText();
}
@Override
public WebElement getElement(By locator) {
WebElement element = null;
try {
element = driver.findElement(locator);
//return element;
} catch (Exception e) {
e.getMessage();
}
return element;
}
@Override
public void waitForElementPresent(By locator,long timeOutInSeconds) {
//wait.until(ExpectedConditions.presenceOfElementLocated(locator));
new WebDriverWait(driver, timeOutInSeconds).until(ExpectedConditions.elementToBeClickable(locator));
}
@Override
public Actions doAction(By locator) {
Actions action= new Actions(driver);
WebElement element=driver.findElement(locator);
action.moveToElement(element).build().perform();
return action;
}
}
|
class Solution {
public int maxDistToClosest(int[] seats) {
int len = seats.length;
int []left = new int[len];
int []right = new int[len];
int pos = len;
for (int i = 0; i < len; i++)
{
if(seats[i] == 1)
{
pos = i;
left[i] = 0;
}
else
{
if(pos < len)
left[i] = i - pos;
else
left[i] = pos;
}
}
pos = len;
for (int j = len - 1; j >= 0; j--)
{
if(seats[j] == 1)
{
pos = j;
right[j] = 0;
}
else
{
if(pos < len)
right[j] = pos - j;
else
right[j] = len;
}
}
|
package com.manage.salary.employee;
import com.manage.salary.employee.detail.EmployeeDetail;
import com.manage.salary.salary.Salary;
import lombok.*;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
@Entity
@Table(name = "employee")
@Data
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@NotEmpty(message = "is required")
@Column(name = "first_name")
private String firstName;
@NotEmpty(message = "is required")
@Column(name = "last_name")
private String lastName;
@Column(name = "position")
private String position;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "employee_detail_id")
private EmployeeDetail employeeDetail;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "employee_id")
private List<Salary> salary;
private Double totalNet;
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class pk extends b {
public a cah;
public b cai;
public pk() {
this((byte) 0);
}
private pk(byte b) {
this.cah = new a();
this.cai = new b();
this.sFm = false;
this.bJX = null;
}
}
|
package main3x3;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class StartScreen extends JPanel{
private JTextArea instructions;
public StartScreen(int i){
setLayout(new BorderLayout());
if (i==0) {
instructions = new JTextArea("This Test will be 20 rounds and about 60 seconds long."
+ "\n On each screen you will have to click the "
+ "\n one image (flower/snake) that is not like the other."
+ "\n Once the test is complete you will get your average response time.");
} else if (i==1){
instructions = new JTextArea("Ready...");
} else if(i==2){
instructions = new JTextArea("Set...");
}
add(instructions,BorderLayout.CENTER);
}
}
|
package com.zzlz13.zmusic.greendao;
import android.database.sqlite.SQLiteDatabase;
import java.util.Map;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.AbstractDaoSession;
import de.greenrobot.dao.identityscope.IdentityScopeType;
import de.greenrobot.dao.internal.DaoConfig;
import com.zzlz13.zmusic.greendao.PlaySong;
import com.zzlz13.zmusic.greendao.LoveSong;
import com.zzlz13.zmusic.greendao.PlaySongDao;
import com.zzlz13.zmusic.greendao.LoveSongDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig playSongDaoConfig;
private final DaoConfig loveSongDaoConfig;
private final PlaySongDao playSongDao;
private final LoveSongDao loveSongDao;
public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
playSongDaoConfig = daoConfigMap.get(PlaySongDao.class).clone();
playSongDaoConfig.initIdentityScope(type);
loveSongDaoConfig = daoConfigMap.get(LoveSongDao.class).clone();
loveSongDaoConfig.initIdentityScope(type);
playSongDao = new PlaySongDao(playSongDaoConfig, this);
loveSongDao = new LoveSongDao(loveSongDaoConfig, this);
registerDao(PlaySong.class, playSongDao);
registerDao(LoveSong.class, loveSongDao);
}
public void clear() {
playSongDaoConfig.getIdentityScope().clear();
loveSongDaoConfig.getIdentityScope().clear();
}
public PlaySongDao getPlaySongDao() {
return playSongDao;
}
public LoveSongDao getLoveSongDao() {
return loveSongDao;
}
}
|
package net.optifine.entity.model;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelArmorStand;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.entity.RenderArmorStand;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.item.EntityArmorStand;
public class ModelAdapterArmorStand extends ModelAdapter {
public ModelAdapterArmorStand() {
super(EntityArmorStand.class, "armor_stand", 0.7F);
}
public ModelBase makeModel() {
return (ModelBase)new ModelArmorStand();
}
public ModelRenderer getModelRenderer(ModelBase model, String modelPart) {
if (!(model instanceof ModelArmorStand))
return null;
ModelArmorStand modelarmorstand = (ModelArmorStand)model;
if (modelPart.equals("right"))
return modelarmorstand.standRightSide;
if (modelPart.equals("left"))
return modelarmorstand.standLeftSide;
if (modelPart.equals("waist"))
return modelarmorstand.standWaist;
return modelPart.equals("base") ? modelarmorstand.standBase : null;
}
public IEntityRenderer makeEntityRender(ModelBase modelBase, float shadowSize) {
RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager();
RenderArmorStand renderarmorstand = new RenderArmorStand(rendermanager);
renderarmorstand.mainModel = modelBase;
renderarmorstand.shadowSize = shadowSize;
return (IEntityRenderer)renderarmorstand;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\optifine\entity\model\ModelAdapterArmorStand.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.sun.mapper;
import com.sun.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl1 implements UserMapper {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> selectUsers() {
User user = new User(88, "孙测试插入", "123456");
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(88);
return mapper.selectUsers();
}
@Override
public int addUser(User user) {
return sqlSessionTemplate.getMapper(UserMapper.class).addUser(user);
}
@Override
public int deleteUser(int id) {
return sqlSessionTemplate.getMapper(UserMapper.class).deleteUser(id);
}
}
|
package com.freak.printtool.hardware.module.wifi.printerutil;
import android.util.Log;
import com.freak.printtool.hardware.utils.DateUtil;
import com.freak.printtool.hardware.utils.LogUtil;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
/**
* @author Freak
* @date 2019/8/14.
*/
public class SocketPrint {
//定义编码方式
private static String encoding = null;
private String ip;
private Socket sock = null;
private int port;
/**
* 连接超时时间
*/
private final static int SOCKET_RECEIVE_TIME_OUT = 2500;
/**
* 初始化Pos实例
*
* @param ip 打印机IP
* @param port 打印机端口号
* @param encoding 编码
* @throws IOException
*/
public SocketPrint(String ip, int port, String encoding) {
try {
this.ip = ip;
this.port = port;
if (sock != null) {
closeIOAndSocket();
} else {
SocketAddress socketAddress = new InetSocketAddress(ip, port);
sock = new Socket();
sock.connect(socketAddress, SOCKET_RECEIVE_TIME_OUT);
}
if (sock.isConnected()) {
//中文打印要看设置设置的中文格式对应的是哪一个,这个佳博wifi打印机是串口的,编码是GB2312,如果设置不对就会乱码
String time = DateUtil.getTime();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), encoding));
bufferedWriter.write("打印测试");
bufferedWriter.newLine();
bufferedWriter.write("----------------------------");
bufferedWriter.newLine();
bufferedWriter.write("收银员:10001");
bufferedWriter.newLine();
bufferedWriter.write("测试时间:" + time);
bufferedWriter.newLine();
bufferedWriter.write("----------------------------");
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedWriter.close();
sock.close();
LogUtil.e("已打开");
} else {
LogUtil.e("没有打开");
}
} catch (Exception e) {
Log.e("king", e.toString());
}
}
/**
* 关闭IO流和Socket
*
* @throws IOException
*/
public void closeIOAndSocket() {
try {
sock.close();
} catch (Exception e) {
}
}
}
|
package com.example.maogai.othersActivity;
import android.os.Bundle;
import android.view.View;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.example.maogai.R;
import androidx.appcompat.app.AppCompatActivity;
public class videoActivity extends AppCompatActivity implements View.OnClickListener {
private StyledPlayerView s1;
private SimpleExoPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MediaItem mediaItem = null;
player = new SimpleExoPlayer.Builder(this).build();
setContentView(R.layout.activity_video);
s1 = (StyledPlayerView) findViewById(R.id.svideo);
s1.setPlayer(player);
String var = getIntent().getStringExtra("name");
if (var.equals("1"))
mediaItem = MediaItem.fromUri("https://vkceyugu.cdn.bspapp.com/VKCEYUGU-imgbed/4089da93-fa9d-4bd0-aaf2-afa9868251df.mp4");
if(var.equals("2"))
mediaItem = MediaItem.fromUri("https://vkceyugu.cdn.bspapp.com/VKCEYUGU-imgbed/3ad36d2b-23aa-48fd-b874-4ea4a6c2348c.mp4");
if(var.equals("3"))
mediaItem = MediaItem.fromUri("https://vkceyugu.cdn.bspapp.com/VKCEYUGU-imgbed/8dddd85e-25f0-4ef1-9395-ad207f030b68.mp4");
if(var.equals("4"))
mediaItem = MediaItem.fromUri("https://vkceyugu.cdn.bspapp.com/VKCEYUGU-imgbed/20204c35-6d00-4300-aed6-14c35ddf83a4.mp4");
player.setMediaItem(mediaItem);
player.prepare();
player.play();
}
@Override
public void onClick(View v) {
}
public void onDestroy() {
super.onDestroy();
player.release();
}
}
|
package com.twu.infrastructure;
import com.twu.model.User;
import java.util.Scanner;
public class ManageMovieMenu {
private User user;
private ManageMainMenu menu;
public ManageMovieMenu(User user, ManageMainMenu menu) {
this.user = user;
this.menu = menu;
}
public void showMovieSubMenu(){
String menuMessage = "Please choose one of the following options:\n" +
"A: Movie List\n" + "B: Check out Movie\n" + "C: Return Movie\n" + "D: Exit\n" + "E: Main Menu";
System.out.println(menuMessage);
getMovieSubMenuChoice();
}
public void getMovieSubMenuChoice() {
User testUser = user;
ManageMovies movieManager = new ManageMovies(testUser, this);
Scanner scanMovieMenuChoice = new Scanner(System.in);
while(scanMovieMenuChoice.hasNextLine()) {
String choiceMovieMenu = scanMovieMenuChoice.nextLine();
if(!choiceMovieMenu.toUpperCase().equals("A") && !choiceMovieMenu.toUpperCase().equals("B") &&
!choiceMovieMenu.toUpperCase().equals("C") && !choiceMovieMenu.toUpperCase().equals("D")
&& !choiceMovieMenu.toUpperCase().equals("E")){
choiceMovieMenu = "OTHER";
}
ManageMessages.menuOptions option = ManageMessages.menuOptions.valueOf(choiceMovieMenu.toUpperCase());
switch(option){
case A:
movieManager.showAvailableMovies();
showMovieSubMenu();
break;
case B:
System.out.println("What movie would you like to check out?");
movieManager.checkOutMovie();
break;
case C:
System.out.println("What movie would you like to return?");
movieManager.returnMovie();
break;
case D:
System.exit(0);
break;
case E:
ManageMainMenu menu = new ManageMainMenu(user);
menu.mainMenu();
case OTHER:
System.out.println("Please select a valid option!");
getMovieSubMenuChoice();
break;
}
}
}
public void movieCheckOutSuccess(){
System.out.println("Thank you! Enjoy the movie!");
showMovieSubMenu();
}
public void movieCheckOutError(){
System.out.println("Sorry, that movie is not available!");
showMovieSubMenu();
}
public void movieReturnSuccess(){
System.out.println("Thank you for returning the movie");
showMovieSubMenu();
}
public void movieReturnError(){
System.out.println("That is not a valid movie to return");
showMovieSubMenu();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.config;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.stream.Stream;
import org.apache.webbeans.exception.WebBeansConfigurationException;
import org.apache.webbeans.logger.WebBeansLoggerFacade;
import org.apache.webbeans.spi.BeanArchiveService;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
/**
* Defines configuration for OpenWebBeans.
*
* The algorithm is easy:
* <ul>
* <li>Load all properties you can find with the name (META-INF/openwebbeans/openwebbeans.properties),</li>
* <li>Sort the property files via their configuration.ordinal in ascending order,</li>
* <li>Overload them in a loop,</li>
* <li><Overload them via System.getProperties/li>
* <li><Overload them via System.getenv/li>
* <li>Use the final list of properties.</li>
* </ul>
*/
public class OpenWebBeansConfiguration
{
/**Timeout interval in ms*/
public static final String CONVERSATION_TIMEOUT_INTERVAL = "org.apache.webbeans.conversation.Conversation.timeoutInterval";
/**
* Environment property which comma separated list of classes which
* should NOT fail with UnproxyableResolutionException
*/
public static final String ALLOW_PROXYING_PARAM = "jakarta.enterprise.inject.allowProxying.classes";
/**
* Lifycycle methods like {@link jakarta.annotation.PostConstruct} and
* {@link jakarta.annotation.PreDestroy} must not define a checked Exception
* regarding to the spec. But this is often unnecessary restrictive so we
* allow to disable this check application wide.
*/
public static final String INTERCEPTOR_FORCE_NO_CHECKED_EXCEPTIONS = "org.apache.webbeans.forceNoCheckedExceptions";
/**
* Enable that calls to various methods get strictly validated.
* Defaults to 'false' for more performance.
*/
public static final String STRICT_DYNAMIC_VALIDATION = "org.apache.webbeans.strictDynamicValidation";
/**If generics should be taken into account for the matching*/
public static final String FAST_MATCHING = "org.apache.webbeans.container.InjectionResolver.fastMatching";
/**Use EJB Discovery or not*/
public static final String USE_EJB_DISCOVERY = "org.apache.webbeans.spi.deployer.useEjbMetaDataDiscoveryService";
/**Container lifecycle*/
public static final String CONTAINER_LIFECYCLE = "org.apache.webbeans.spi.ContainerLifecycle";
/**JNDI Service SPI*/
public static final String JNDI_SERVICE = "org.apache.webbeans.spi.JNDIService";
/**Scanner Service*/
public static final String SCANNER_SERVICE = "org.apache.webbeans.spi.ScannerService";
/**Contexts Service*/
public static final String CONTEXTS_SERVICE = "org.apache.webbeans.spi.ContextsService";
/**Conversation Service*/
public static final String CONVERSATION_SERVICE = "org.apache.webbeans.spi.ConversationService";
/**Resource Injection Service*/
public static final String RESOURCE_INJECTION_SERVICE = "org.apache.webbeans.spi.ResourceInjectionService";
/**Security Service*/
public static final String SECURITY_SERVICE = "org.apache.webbeans.spi.SecurityService";
/**Validator Service*/
public static final String VALIDATOR_SERVICE = "org.apache.webbeans.spi.ValidatorService";
/**Transaction Service*/
public static final String TRANSACTION_SERVICE = "org.apache.webbeans.spi.TransactionService";
/**Application is core JSP*/
public static final String APPLICATION_IS_JSP = "org.apache.webbeans.application.jsp";
/**Supports conversations*/
public static final String APPLICATION_SUPPORTS_CONVERSATION = "org.apache.webbeans.application.supportsConversation";
/** @Produces with interceptor/decorator support */
public static final String PRODUCER_INTERCEPTION_SUPPORT = "org.apache.webbeans.application.supportsProducerInterception";
/**EL Adaptor*/
public static final String EL_ADAPTOR_SERVICE = "org.apache.webbeans.spi.adaptor.ELAdaptor";
/**
* prefix followed by the fully qualified scope name, for configuring NormalScopedBeanInterceptorHandler
* for our proxies.
*
* The format is like the following:
* 'org.apache.webbeans.proxy.mapping.' followed by the scope annotation = a subclass of a NormalScopedBeanInterceptorHandler
*
* Example:
* <pre>
* org.apache.webbeans.proxy.mapping.jakarta.enterprise.context.ApplicationScoped=org.apache.webbeans.intercept.ApplicationScopedBeanInterceptorHandler
* org.apache.webbeans.proxy.mapping.jakarta.enterprise.context.RequestScoped=org.apache.webbeans.intercept.RequestScopedBeanInterceptorHandler
* org.apache.webbeans.proxy.mapping.jakarta.enterprise.context.SessionScoped=org.apache.webbeans.intercept.SessionScopedBeanInterceptorHandler
* </pre>
*
*/
public static final String PROXY_MAPPING_PREFIX = "org.apache.webbeans.proxy.mapping.";
/**
* Use BDABeansXmlScanner to determine if interceptors, decorators, and
* alternatives are enabled in the beans.xml of a given BDA. For an
* application containing jar1 and jar2, this implies that an interceptor
* enabled in the beans.xml of jar1 is not automatically enabled in jar2
* @deprecated as spec section 5 and 12 contradict each other and the BDA per jar handling is broken anyway
**/
public static final String USE_BDA_BEANSXML_SCANNER = "org.apache.webbeans.useBDABeansXMLScanner";
/** A list of known JARs/paths which should not be scanned for beans */
public static final String SCAN_EXCLUSION_PATHS = "org.apache.webbeans.scanExclusionPaths";
/**
* Flag which indicates that only jars with an explicit META-INF/beans.xml marker file shall get parsed.
* Default is {@code false}.
*
* This might be switched on to improve boot time in cases where you always have beans.xml in
* your jars or classpath entries.
*/
public static final String SCAN_ONLY_BEANS_XML_JARS = "org.apache.webbeans.scanBeansXmlOnly";
/**
* a comma-separated list of fully qualified class names that should be ignored
* when determining if a decorator matches its delegate. These are typically added by
* weaving or bytecode modification.
*/
public static final String IGNORED_INTERFACES = "org.apache.webbeans.ignoredDecoratorInterfaces";
/**
* A comma-separated list of fully qualified class names of CDI Extensions that should be ignored.
*
*
*/
public static final String IGNORED_EXTENSIONS = "org.apache.webbeans.ignoredExtensions";
/**
* A boolean to enable CDI 1.1 behavior to not scan "extension JARs".
* "extensions JARs" are JARs, without a beans.xml but with CDI extensions.
*
* IMPORTANT: this can break CDI 1.0 extensions.
*/
public static final String SCAN_EXTENSION_JARS = "org.apache.webbeans.scanExtensionJars";
/**
* By default we do _not_ force session creation in our WebBeansConfigurationListener. We only create the
* Session if we really need the SessionContext. E.g. when we create a Contextual Instance in it.
* Sometimes this creates a problem as the HttpSession can only be created BEFORE anything got written back
* to the client.
* With this configuration you can choose between 3 settings
* <ul>
* <li>"true" the Session will <u>always</u> eagerly be created at the begin of a request</li>
* <li>"false" the Session will <u>never</u> eagerly be created but only lazily when the first @SessionScoped bean gets used</li>
* <li>any other value will be interpreted as Java regular expression for request URIs which need eager Session initialization</li>
* </ul>
*/
public static final String EAGER_SESSION_INITIALISATION = "org.apache.webbeans.web.eagerSessionInitialisation";
/**
* The Java Version to use for the generated proxy classes.
* If "auto" then we will pick the version of the current JVM.
* The default is set to "1.6" as some tools in jetty/tomcat/etc still
* cannot properly handle Java8 (mostly due to older Eclipse JDT versions).
*/
public static final String GENERATOR_JAVA_VERSION = "org.apache.webbeans.generator.javaVersion";
/**
* Default bean discovery mode for empty beans.xml
* There was a really wicked change in the CDI-4.0 specification which will break many applications.
* They switched the bean-discovery-mode of an empty beans.xml file (or a beans.xml without any version)
* from ALL to ANNOTATED (Despite warnings that his is totally backward incompatible and could easily have been avoided).
*
* The default in OWB is still ALL, but it can be configured to any other bean-discovery-mode with this config switch
*/
public static final String DEFAULT_BEAN_DISCOVERY_MODE = "org.apache.webbeans.defaultBeanDiscoveryMode";
/**Default configuration files*/
private static final String DEFAULT_CONFIG_PROPERTIES_NAME = "META-INF/openwebbeans/openwebbeans.properties";
/**
* A value which indicates an 'automatic' behaviour.
*/
private static final String AUTO_CONFIG = "auto";
/**Property of application*/
private final Properties configProperties = new Properties();
/**
* @see #IGNORED_INTERFACES
*/
private Set<String> ignoredInterfaces;
/**
* @see #IGNORED_EXTENSIONS
*/
private Set<String> ignoredExtensions;
/**
* @see #SCAN_EXTENSION_JARS
*/
private Boolean scanExtensionJars;
/**
* All configured lists per key.
*
* For a single key the following configuration sources will get parsed:
* <ul>
* <li>all {@link #DEFAULT_CONFIG_PROPERTIES_NAME} files</li>
* <li>{@code System.getProperties()}</li>
* <li>{@code System.env()}</li>
* </ul>
*
* All the found values will get split by comma (',') and all trimmed values
* will get stored in a Set.
*
*/
private Map<String, Set<String>> configuredLists = new HashMap<>();
/**
* List of packages which can't be used to generate a proxy.
*
* Important: changing this default has runtime impacts on proxies name.
* It is recommended to not tune it until really needed.
* Also ensure it is consistent between generation and runtime if you use stable proxy names.
*/
private volatile List<String> proxyReservedPackages;
/**
* you can configure this externally as well.
*
* @param properties
*/
public OpenWebBeansConfiguration(Properties properties)
{
this();
// and override all settings with the given properties
configProperties.putAll(properties);
}
/**
* Parse configuration.
*/
public OpenWebBeansConfiguration()
{
parseConfiguration();
}
/**
* (re)read the configuration from the resources in the classpath.
* @see #DEFAULT_CONFIG_PROPERTIES_NAME
* @see #DEFAULT_CONFIG_PROPERTIES_NAME
*/
public synchronized void parseConfiguration() throws WebBeansConfigurationException
{
Properties newConfigProperties = PropertyLoader.getProperties(DEFAULT_CONFIG_PROPERTIES_NAME);
configProperties.clear();
// set the new one as perfect fit.
if(newConfigProperties != null)
{
overrideWithGlobalSettings(newConfigProperties);
configProperties.putAll(newConfigProperties);
}
}
/**
* Take the given commaSeparatedVals and spit them by ',' and trim them.
* @return all trimmed values or an empty list
*/
public List<String> splitValues(String commaSeparatedVals)
{
ArrayList<String> values = new ArrayList<>();
if (commaSeparatedVals != null)
{
for (String value : commaSeparatedVals.split(","))
{
value = value.trim();
if (!value.isEmpty())
{
values.add(value);
}
}
}
return values;
}
private void overrideWithGlobalSettings(Properties configProperties)
{
Properties systemProperties;
if(System.getSecurityManager() != null)
{
systemProperties = doPrivilegedGetSystemProperties();
}
else
{
systemProperties = System.getProperties();
}
Map<String, String> systemEnvironment = System.getenv();
for (Map.Entry property : configProperties.entrySet())
{
String key = (String) property.getKey();
String value = (String) property.getValue();
value = systemProperties.getProperty(key) != null ? systemProperties.getProperty(key) : value;
String envKey = key.replace('.', '_');
value = systemEnvironment.get(envKey) != null ? systemEnvironment.get(envKey) : value;
if (value != null)
{
configProperties.put(key, value);
}
}
}
private Properties doPrivilegedGetSystemProperties()
{
return AccessController.doPrivileged(
new PrivilegedAction<Properties>()
{
@Override
public Properties run()
{
return System.getProperties();
}
}
);
}
/**
* Gets property.
* @param key
* @return String with the property value or <code>null</code>
*/
public String getProperty(String key)
{
return configProperties.getProperty(key);
}
/**
* Gets property value.
* @param key
* @param defaultValue
* @return String with the property value or <code>null</code>
*/
public String getProperty(String key,String defaultValue)
{
return configProperties.getProperty(key, defaultValue);
}
/**
* Sets given property.
* @param key property name
* @param value property value
*/
public synchronized void setProperty(String key, Object value)
{
configProperties.put(key, value);
}
/**
* Gets jsp property.
* @return true if jsp
*/
public boolean isJspApplication()
{
String value = getProperty(APPLICATION_IS_JSP);
return Boolean.valueOf(value);
}
/**
* Gets conversation supports property.
* @return true if supports
*/
public boolean supportsConversation()
{
String value = getProperty(APPLICATION_SUPPORTS_CONVERSATION);
return Boolean.valueOf(value);
}
/**
* Flag which indicates that only jars with an explicit META-INF/beans.xml marker file shall get paresed.
* Default is {@code false}
*/
public boolean scanOnlyBeansXmlJars()
{
String value = getProperty(SCAN_ONLY_BEANS_XML_JARS);
return "true".equalsIgnoreCase(value);
}
/**
* Flag which indicates that programmatic invocations to vaious BeanManager methods
* should get strictly validated.
* E.g. whether qualifier parameters are really qualifiers, etc.
* Default is {@code false}
*/
public boolean strictDynamicValidation()
{
String value = getProperty(STRICT_DYNAMIC_VALIDATION);
return "true".equalsIgnoreCase(value);
}
public synchronized Set<String> getIgnoredInterfaces()
{
if (ignoredInterfaces == null)
{
ignoredInterfaces = getPropertyList(IGNORED_INTERFACES);
}
return ignoredInterfaces;
}
public synchronized Set<String> getIgnoredExtensions()
{
if (ignoredExtensions == null)
{
ignoredExtensions = getPropertyList(IGNORED_EXTENSIONS);
}
return ignoredExtensions;
}
public synchronized boolean getScanExtensionJars()
{
if (scanExtensionJars == null)
{
final String property = getProperty(SCAN_EXTENSION_JARS);
// default must stay true for backward compatibility
scanExtensionJars = property == null || Boolean.parseBoolean(property.trim());
}
return scanExtensionJars;
}
private Set<String> getPropertyList(String configKey)
{
String configValue = getProperty(configKey);
if (configValue != null)
{
return new HashSet<>(Arrays.asList(configValue.split("[,\\p{javaWhitespace}]")));
}
return Collections.emptySet();
}
/**
* Scan all openwebbeans.properties files + system properties +
* syste.env for the given key.
* If the key is comma separated then use the separate tokens.
* All the values get put into a big set.
*/
public synchronized Set<String> getConfigListValues(String keyName)
{
Set<String> allValues = configuredLists.get(keyName);
if (allValues != null)
{
return allValues;
}
allValues = new HashSet<>();
try
{
List<Properties> properties = PropertyLoader.loadAllProperties(DEFAULT_CONFIG_PROPERTIES_NAME);
if (properties != null)
{
for (Properties property : properties)
{
String values = (String) property.get(keyName);
allValues.addAll(splitValues(values));
}
}
}
catch (IOException e)
{
WebBeansLoggerFacade.getLogger(OpenWebBeansConfiguration.class)
.log(Level.SEVERE, "Error while loading the propertyFile " + DEFAULT_CONFIG_PROPERTIES_NAME, e);
return Collections.EMPTY_SET;
}
// search for the key in the properties
String value = System.getProperty(keyName);
allValues.addAll(splitValues(value));
// search for the key in the environment
String envKeyName = keyName.toUpperCase().replace(".", "_");
value = System.getenv(envKeyName);
allValues.addAll(splitValues(value));
configuredLists.put(keyName, allValues);
return allValues;
}
/**
* Add a configuration value to the Set of configured values registered
* under the keyName.
*
* Calling this method ensures that all the configured values are first
* read from the environment and configuration properties.
*
* @see #getConfigListValues(String) get's called internally to insure the list is initialised
*/
public synchronized void addConfigListValue(String keyName, String value)
{
Set<String> configListValues = getConfigListValues(keyName);
configListValues.add(value);
}
public boolean supportsInterceptionOnProducers()
{
return Boolean.parseBoolean(getProperty(PRODUCER_INTERCEPTION_SUPPORT, "true"));
}
public String getGeneratorJavaVersion()
{
String generatorJavaVersion = getProperty(GENERATOR_JAVA_VERSION);
if (generatorJavaVersion == null || AUTO_CONFIG.equals(generatorJavaVersion))
{
return System.getProperty("java.version");
}
return generatorJavaVersion;
}
public boolean isSkipNoClassDefFoundErrorTriggers()
{
return Boolean.parseBoolean(getProperty(
"org.apache.webbeans.spi.deployer.skipNoClassDefFoundTriggers"));
}
public List<String> getProxyReservedPackages()
{
if (proxyReservedPackages == null)
{
synchronized (this)
{
if (proxyReservedPackages == null)
{
final String conf = getProperty("org.apache.webbeans.generator.proxyReservedPackages");
if (conf == null)
{
proxyReservedPackages = asList("java.", "javax.", "jakarta.", "sun.misc.");
}
else
{
proxyReservedPackages = Stream.concat(
Stream.of("java.", "javax.", "jakarta.", "sun.misc."),
Stream.of(conf.split(","))
.map(String::trim)
.filter(it -> !it.isEmpty()))
.distinct()
.collect(toList());
}
}
}
}
return proxyReservedPackages;
}
/**
* @see #DEFAULT_BEAN_DISCOVERY_MODE
*/
public BeanArchiveService.BeanDiscoveryMode getDefaultBeanDiscoveryMode()
{
return BeanArchiveService.BeanDiscoveryMode.valueOf(getProperty(OpenWebBeansConfiguration.DEFAULT_BEAN_DISCOVERY_MODE));
}
}
|
package me.ljseokd.basicboard.modules.account;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import me.ljseokd.basicboard.modules.account.form.ProfileForm;
import me.ljseokd.basicboard.modules.notice.Notice;
import me.ljseokd.basicboard.modules.notification.Notification;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import static lombok.AccessLevel.PROTECTED;
@Entity
@Getter
@EqualsAndHashCode(of = "id")
@NoArgsConstructor(access = PROTECTED)
public class Account {
@Id @GeneratedValue
@Column(name = "account_id")
private Long id;
@Column(unique = true)
private String nickname;
private String password;
private String bio;
@OneToMany(mappedBy = "account")
private List<Notice> notices = new ArrayList<>();
@OneToMany(mappedBy = "account")
private List<Notification> notificationList = new ArrayList<>();
public Account(String nickname, String password) {
this.nickname = nickname;
this.password = password;
}
public boolean isOwner(Account account) {
if (account != null){
return this.equals(account);
}
return false;
}
public void addNotification(Notification notification){
notificationList.add(notification);
}
public void changeProfile(ProfileForm profileForm) {
bio = profileForm.getBio();
}
}
|
package com.lis2.demo;
import org.junit.Test;
public class Double {
@Test
public void test() {
double e = Math.E;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
/**
Pentru structura Tara ->judet -> oras am implementat relatii "has a".
Se mai pot aduce modificari in sensul aduagarii de sate, comune prin crearea a unor noi prototipuri
* si adaugarea lor succesiva ca si membrii in clasele deja create.
*/
public class Tara {
private String numeTara;
private Judet judet;
public Tara(String numeTara) {
this.numeTara = numeTara;
}
}
|
//shows a basic gui input and output to display guests in each room without having to open the txt file.
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
@SuppressWarnings("serial")//suppresses warnings when JFrame is extended something to do with SerialUID.
public class jframepreset extends JFrame {
//int guests [] = {1, 2, 3, 2, 1};//array initializer.
int guests [];//creates variable but yet to refer to array as array has not yet been instantiated.
public void assignRoom() throws IOException {
guests = new int [5];
BufferedReader fr = new BufferedReader(new FileReader("src/hotelgp.txt"));
for (int roomNum = 0; roomNum < 5; roomNum++) {
guests[roomNum] = Integer.parseInt(fr.readLine());
}
fr.close();//close for good practice to prevent conflict
}
public jframepreset() throws IOException{
assignRoom();
setTitle("room guest display");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(1,2));
//setSize(500,400);
pack();
setVisible(true);
int roomnum;
roomnum = Integer.parseInt(JOptionPane.showInputDialog("input room number: "));
add(new JLabel("room number "+roomnum+": "));
add(new JLabel(String.valueOf(guests[roomnum])));
revalidate();
pack();
}
public static void main (String [] args) throws IOException{
jframepreset roomguestdisplay = new jframepreset();
}
}
|
package com.user.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 测试servlet
* 要在wen.xml文件中进行注册(包含名字,路径,访问的类)
* init方法在启动servlet的时候使用
* @author user
*
*/
public class TestServlet extends HttpServlet{
@Override
public void init() throws ServletException {
super.init();
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse arg1) throws ServletException, IOException {
PrintWriter pw =arg1.getWriter();
pw.print("hello word");
pw.close();
}
@Override
public void destroy() {
super.destroy();
}
}
|
package com.laurenelder.aquapharm;
public class Weather {
public String location;
public String day;
public String month;
public String year;
public String lowTemp;
public String highTemp;
public Weather(String thisLocation, String thisDay, String thisMonth, String thisYear,
String thisLowTemp, String thisHighTemp) {
this.location = thisLocation;
this.day = thisDay;
this.month = thisMonth;
this.year = thisYear;
this.lowTemp = thisLowTemp;
this.highTemp = thisHighTemp;
}
public String toString() {
return location + ": " + month + "/" + day + "/" + year;
}
}
|
package de.zarncke.lib.err;
/**
* This exception should be thrown if a requested Resource is not available for whatever reasons in general.
*/
public class NotAvailableException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public NotAvailableException()
{
super();
}
public NotAvailableException(final String msg)
{
super(msg);
}
public NotAvailableException(final Throwable wrapped)
{
super(wrapped);
}
public NotAvailableException(final String msg, final Throwable wrapped)
{
super(msg, wrapped);
}
}
|
package com.pfchoice.springboot.repositories;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.pfchoice.springboot.model.LeadMembership;
import com.pfchoice.springboot.model.LeadMembershipFlag;
import com.pfchoice.springboot.repositories.intf.RecordDetailsAwareRepository;
@Repository
public interface LeadMembershipFlagRepository
extends PagingAndSortingRepository<LeadMembershipFlag, Integer>, JpaSpecificationExecutor<LeadMembershipFlag>, RecordDetailsAwareRepository<LeadMembershipFlag, Integer> {
public LeadMembershipFlag findById(Integer id);
public LeadMembershipFlag findByLead(LeadMembership lead);
}
|
package klaicm.backlayer.tennisscores.services.jpadata;
import klaicm.backlayer.tennisscores.model.ArchData;
import klaicm.backlayer.tennisscores.model.Match;
import klaicm.backlayer.tennisscores.model.Player;
import klaicm.backlayer.tennisscores.repositories.PlayerRepository;
import klaicm.backlayer.tennisscores.services.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Profile("jpaservice")
public class PlayerJpaService implements PlayerService {
private static final int K = 32;
@Autowired
ArchDataJpaService archDataJpaService;
@Autowired
MatchJpaService matchJpaService;
private final PlayerRepository playerRepository;
public PlayerJpaService(PlayerRepository playerRepository) {
this.playerRepository = playerRepository;
}
@Override
public Set<Player> findAll() {
Set<Player> players = new HashSet<>();
playerRepository.findAll().forEach(players::add);
return players;
}
@Override
public Player findById(Long id) {
Player player = playerRepository.findById(id).orElse(null);
Set<ArchData> archData = archDataJpaService.getArchDataByPlayerId(player.getId());
player.setArchData(archData);
return player;
}
@Override
public Player save(Player player) {
return playerRepository.save(player);
}
@Override
public void delete(Player player) {
playerRepository.delete(player);
}
@Override
public void deleteById(Long id) {
playerRepository.deleteById(id);
}
public void updatePlayer(Match match) {
Player playerW = findById(match.getPlayerW().getId());
Player playerL = findById(match.getPlayerL().getId());
Map<String, Double> probabilityMap = this.calculateProbabilityOfWin(playerW.getElo(), playerL.getElo());
// double raUpdated = ra + K*(1 - ea);
// double rbUpdated = rb + K*(0 - eb);
int raUpdated = (int) Math.round(playerW.getElo() + K*(1 - probabilityMap.get("ea")));
int rbUpdated = (int) Math.round(playerL.getElo() + K*(0 - probabilityMap.get("eb")));
if (match.getResult().length() == 7) {
playerW.setWinsInTwo(playerW.getWinsInTwo() + 1);
playerW.setPoints(playerW.getPoints() + 3);
playerL.setLosesInTwo(playerL.getLosesInTwo() + 1);
} else if (match.getResult().length() > 7) {
playerW.setWinsInTb(playerW.getWinsInTb() + 1);
playerW.setPoints(playerW.getPoints() + 2);
playerL.setLosesInTb(playerL.getLosesInTb() + 1);
playerL.setPoints(playerL.getPoints() + 1);
} else {
throw new IllegalArgumentException("Uneseni rezultat neispravan");
}
playerW.setElo(raUpdated);
playerL.setElo(rbUpdated);
this.save(playerW);
this.save(playerL);
ArchData playerWArch = insertArchData(playerW, raUpdated, match, true);
ArchData playerLArch = insertArchData(playerL, rbUpdated, match, false);
archDataJpaService.save(playerWArch);
archDataJpaService.save(playerLArch);
}
public Map<String, Double> calculateProbabilityOfWin(Integer playerAElo, Integer playerBElo) {
Map<String, Double> probabilityMap = new HashMap<String, Double>();
double ra = playerAElo;
double rb = playerBElo;
double ea = 1/(1+ Math.pow(10, ((rb-ra)/400)));
probabilityMap.put("ea", ea);
double eb = 1/(1+ Math.pow(10, ((ra-rb)/400)));
probabilityMap.put("eb", eb);
return probabilityMap;
}
private ArchData insertArchData(Player player, int ratingUpdated, Match match, boolean isWinner) {
ArchData playerArch = new ArchData();
Set<Player> allPlayersSet = this.findAll();
List<Player> allPlayersList = allPlayersSet.stream().sorted(Comparator.comparing(Player::getPoints).reversed()).collect(Collectors.toList());
playerArch.setPlayer(player);
playerArch.setDate(match.getDate());
playerArch.setEloRating(ratingUpdated);
int totalGames = player.getLosesInTb() + player.getLosesInTwo() + player.getWinsInTb() + player.getWinsInTwo();
double winPercentageW = (((double)player.getWinsInTb() + (double)player.getWinsInTwo())/totalGames)*100;
playerArch.setWinPercentage((int)Math.round(winPercentageW));
int position = allPlayersList.indexOf(player) + 1;
playerArch.setPosition(position);
if (isWinner) {
playerArch.setTotalWins((allPlayersList.get(allPlayersList.indexOf(player)).getWinsInTb() +
allPlayersList.get(allPlayersList.indexOf(player)).getWinsInTwo()) + 1);
playerArch.setTotalLoses((allPlayersList.get(allPlayersList.indexOf(player)).getLosesInTb() +
allPlayersList.get(allPlayersList.indexOf(player)).getLosesInTwo()));
} else {
playerArch.setTotalLoses((allPlayersList.get(allPlayersList.indexOf(player)).getLosesInTb() +
allPlayersList.get(allPlayersList.indexOf(player)).getLosesInTwo()) + 1);
playerArch.setTotalWins((allPlayersList.get(allPlayersList.indexOf(player)).getWinsInTb() +
allPlayersList.get(allPlayersList.indexOf(player)).getWinsInTwo()));
}
return playerArch;
}
}
|
package algorithms;
public class MaximumProductSubArray {
public static void main(String[] args) {
int arr[] = {6, -3, -10, 0, 2};
System.out.println(maxProduct(arr));
}
public static int maxProduct(int arr[]) {
int currMax = arr[0];
int prevMax = arr[0];
int prevMin = arr[0];
int sum = arr[0];
for(int i = 1; i < arr.length; i++) {
currMax = Math.max(prevMax * arr[i], Math.max(prevMin * arr[i], arr[i]));
int currMin = Math.min(prevMax * arr[i], Math.min(prevMin * arr[i], arr[i]));
sum = Math.max(sum, currMax);
prevMax = currMax;
prevMin = currMin;
}
return sum;
}
}
|
package com.tencent.mm.plugin.facedetect.e;
public enum a$a {
;
static {
iSN = 1;
iSO = 2;
iSP = 3;
iSQ = 4;
iSR = 5;
iSS = 6;
iST = new int[]{iSN, iSO, iSP, iSQ, iSR, iSS};
}
}
|
package java_code.server.handlers;
import com.google.gson.JsonObject;
import com.pubnub.api.PubNub;
import java_code.database.DBManager;
import java_code.server.MessageHandler;
import java_code.server.Server;
public class DeletePatronHandler implements MessageHandler {
Server server;
public DeletePatronHandler(Server server){this.server = server;}
@Override
public void handleMessage(JsonObject data, PubNub pubnub, String clientId) {
int venueID = data.get("venueID").getAsInt();
String name = data.get("user_name").getAsString();
String email = data.get("email").getAsString();
if(DBManager.deletePatronFromVenueWaitlist(venueID, name, email)){
server.updateCurrentVenueData();
server.sendUpdateWaitlistData();
server.sendUpdateWaitlist(venueID);
server.updateManagerPage(data);
server.updateVenueListData();
}
}
}
|
package com.ahmetkizilay.yatlib4j.trends;
import com.ahmetkizilay.yatlib4j.oauthhelper.OAuthHolder;
public class GetAvailableTrends {
private static final String BASE_URL = "https://api.twitter.com/1.1/trends/available.json";
private static final String HTTP_METHOD = "GET";
public static GetAvailableTrends.Response sendRequest(GetAvailableTrends.Parameters params, OAuthHolder oauthHolder) {
throw new UnsupportedOperationException();
}
public static class Response {
}
public static class Parameters {
}
}
|
package com.google.android.gms.common.internal;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.c.e;
protected class k$f implements e {
final /* synthetic */ k aOj;
public k$f(k kVar) {
this.aOj = kVar;
}
public final void b(ConnectionResult connectionResult) {
if (connectionResult.isSuccess()) {
this.aOj.a(null, k.d(this.aOj));
} else if (k.e(this.aOj) != null) {
k.e(this.aOj).a(connectionResult);
}
}
public final void c(ConnectionResult connectionResult) {
throw new IllegalStateException("Legacy GmsClient received onReportAccountValidation callback.");
}
}
|
package il.ac.tau.cs.sw1.ex9.starfleet;
import java.util.Objects;
public abstract class myAbstractCrewMember implements CrewMember {
protected int age;
protected int yearsInService;
protected String name;
public myAbstractCrewMember(int age, int yearsInService, String name) {
this.age = age;
this.yearsInService = yearsInService;
this.name = name;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public int getYearsInService() {
return this.yearsInService;
}
public String toString() {
return "\tName="+ this.getName() + System.lineSeparator() +
"\tAge=" + this.getAge() + System.lineSeparator() +
"\tYearInService=" + this.getYearsInService();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
myAbstractCrewMember that = (myAbstractCrewMember) o;
return age == that.age && yearsInService == that.yearsInService && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(age, yearsInService, name);
}
}
|
package com.google.android.gms.wearable.internal;
import com.google.android.gms.common.api.c;
import com.google.android.gms.wearable.h;
class bg$2 extends aw<h> {
final /* synthetic */ bg bft;
bg$2(bg bgVar, c cVar) {
this.bft = bgVar;
super(cVar);
}
}
|
package com.dzz.authority.config;
import com.dzz.user.api.domain.bo.UserDetailBo;
import com.dzz.user.api.service.UserService;
import com.dzz.util.response.ResponsePack;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
* 用户接口实现
*
* @author dzz
* @version 1.0.0
* @since 2019年08月08 11:28
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
ResponsePack<UserDetailBo> responsePack = userService.detailUser(username);
if(responsePack.checkFail() || null == responsePack.getData()) {
throw new UsernameNotFoundException("Invalid username or password.");
}
UserDetailBo userDetailBo = responsePack.getData();
return User.builder().username(userDetailBo.getUserName()).password(userDetailBo.getPassword())
.authorities(userDetailBo.getAuthorities().stream().map(s -> new Authority(s.getAuthority())).collect(
Collectors.toList())).build();
}
}
|
package br.com.maykoone.app.bancohoras;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import java.util.Map;
import br.com.maykoone.app.bancohoras.db.RegistroPontoEntity;
import static br.com.maykoone.app.bancohoras.Util.calculeTime;
import static br.com.maykoone.app.bancohoras.Util.formatTime;
/**
* Created by maykoone on 09/08/15.
*/
public class ExpandableAdapter extends BaseExpandableListAdapter {
private Map<String, List<RegistroPontoEntity>> mListChildren;
private List<String> mListGroup;
private Context mContext;
private LayoutInflater mInflater;
public ExpandableAdapter(Context context, List<String> listGroup, Map<String, List<RegistroPontoEntity>> list) {
mContext = context;
mListChildren = list;
mListGroup = listGroup;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getGroupCount() {
return mListGroup.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return mListChildren.get(mListGroup.get(groupPosition)).size();
}
@Override
public Object getGroup(int groupPosition) {
return mListGroup.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return mListChildren.get(mListGroup.get(groupPosition)).get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
//view holder for recycling
ViewHolder viewHolder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.group_item_expandable_list, null);
viewHolder = new ViewHolder();
convertView.setTag(viewHolder);
viewHolder.textView = (TextView) convertView.findViewById(R.id.textViewGroup);
viewHolder.tvTotalTime = (TextView) convertView.findViewById(R.id.tvTotalTime);
viewHolder.tvCountTime = (TextView) convertView.findViewById(R.id.tvCountTime);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(mListGroup.get(groupPosition));
long totalTimeMillis = calculeTime(mListChildren.get(mListGroup.get(groupPosition)));
String formattedTotalTime = formatTime(totalTimeMillis);
viewHolder.tvTotalTime.setText("Total: " + formattedTotalTime);
String formattedCountTime = formatTime(totalTimeMillis - (8 * 60 * 60 * 1000));//8 hours
viewHolder.tvCountTime.setText("Saldo: " + formattedCountTime);
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
//view holder for recycling
ViewHolder viewHolder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listview_custom_item, null);
viewHolder = new ViewHolder();
convertView.setTag(viewHolder);
viewHolder.textView = (TextView) convertView.findViewById(R.id.textview);
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageview);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(((RegistroPontoEntity) getChild(groupPosition, childPosition)).getDataEvento());
if (childPosition % 2 == 0) {
viewHolder.imageView.setImageResource(R.drawable.ic_action_in_green);
} else {
viewHolder.imageView.setImageResource(R.drawable.ic_action_out_red);
}
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void updateData(List<String> listHeaders, Map<String, List<RegistroPontoEntity>> listChildren) {
Log.i(ExpandableAdapter.class.getName(), "updateData");
this.mListGroup = listHeaders;
this.mListChildren = listChildren;
this.notifyDataSetChanged();
}
static class ViewHolder {
TextView textView;
ImageView imageView;
TextView tvTotalTime;
TextView tvCountTime;
}
}
|
package com.yunussandikci.GithubImporter.Models.Response;
import com.yunussandikci.GithubImporter.Models.Owner;
import com.yunussandikci.GithubImporter.Models.Project;
import java.util.List;
public class ImportedProjectsResponse extends BaseResponse {
public ImportedProjectsResponse(List<Project> importedProjects, Owner owner, String message) {
this.importedProjects = importedProjects;
this.owner = owner;
this.setMessage(message);
}
private List<Project> importedProjects;
private Owner owner;
public List<Project> getImportedProjects() {
return importedProjects;
}
public void setImportedProjects(List<Project> importedProjects) {
this.importedProjects = importedProjects;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
}
|
package com.tencent.mm.plugin.order.ui.a;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.q;
import com.tencent.mm.plugin.order.model.MallTransactionObject;
import com.tencent.mm.plugin.wxpay.a.i;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.storage.ab;
import com.tencent.mm.ui.base.h;
import com.tencent.mm.ui.base.preference.Preference;
import com.tencent.mm.ui.base.preference.PreferenceSmallCategory;
import com.tencent.mm.ui.base.preference.f;
import com.tencent.mm.wallet_core.ui.c;
import com.tencent.mm.wallet_core.ui.e;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public final class a implements com.tencent.mm.plugin.order.model.a.a {
public c lQc;
public final List<Preference> a(final Context context, f fVar, final MallTransactionObject mallTransactionObject) {
Object obj;
CharSequence string;
f fVar2;
ab Yg;
String BL;
f fVar3;
String string2;
h hVar;
List<Preference> arrayList = new ArrayList();
if (mallTransactionObject.bCK == 2) {
obj = 1;
} else {
obj = null;
}
if (!(bi.oW(mallTransactionObject.lNX) || bi.oW(mallTransactionObject.fqJ))) {
d dVar = new d(context);
dVar.iAb = mallTransactionObject.fqJ;
dVar.mName = mallTransactionObject.lNX;
dVar.mOnClickListener = new 1(this, mallTransactionObject, context);
arrayList.add(dVar);
arrayList.add(new PreferenceSmallCategory(context));
}
i iVar = new i(context);
iVar.lQC = e.e(mallTransactionObject.hUL, mallTransactionObject.lNV);
if (obj != null) {
string = context.getString(i.wallet_order_info_amount_income);
} else if (mallTransactionObject.lNG == 11) {
string = context.getString(i.wallet_order_info_save_amount);
} else {
string = context.getString(i.wallet_order_info_amount);
}
iVar.setTitle(string);
if (!bi.oW(mallTransactionObject.lNN)) {
iVar.Jx(mallTransactionObject.lNN);
}
arrayList.add(iVar);
boolean z = false;
if (mallTransactionObject.hUL != mallTransactionObject.lOb) {
h hVar2 = new h(context);
hVar2.lQz = false;
hVar2.lQA = true;
arrayList.add(hVar2);
fVar2 = new f(context);
fVar2.setContent(e.e(mallTransactionObject.lOb, mallTransactionObject.lNV));
fVar2.setTitle(i.wallet_order_info_orginal_amount);
arrayList.add(fVar2);
z = true;
}
if (!(mallTransactionObject.hUL == mallTransactionObject.lOb || bi.oW(mallTransactionObject.lOa))) {
g gVar = new g(context);
gVar.setTitle(i.wallet_order_info_discount);
gVar.gua = fVar;
String[] split = mallTransactionObject.lOa.split("\n");
if (split.length == 1) {
gVar.lQs = split[0];
} else {
gVar.lQs = context.getString(i.wallet_order_info_discount_summary, new Object[]{Integer.valueOf(split.length), e.e(mallTransactionObject.lOb - mallTransactionObject.hUL, mallTransactionObject.lNV)});
gVar.a(split, TruncateAt.MIDDLE);
}
arrayList.add(gVar);
}
h hVar3 = new h(context);
hVar3.lQz = z;
hVar3.lQA = true;
arrayList.add(hVar3);
if (obj == null && !bi.oW(mallTransactionObject.lOk)) {
g.Ek();
Yg = ((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FR().Yg(mallTransactionObject.lOk);
if (Yg != null && ((int) Yg.dhP) > 0) {
BL = Yg.BL();
fVar3 = new f(context);
fVar3.setTitle(i.wallet_order_info_spid);
fVar3.setContent(BL);
arrayList.add(fVar3);
}
}
if (!(mallTransactionObject.lNG != 31 || obj == null || bi.oW(mallTransactionObject.lOr))) {
g.Ek();
Yg = ((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FR().Yg(mallTransactionObject.lOr);
if (Yg != null && ((int) Yg.dhP) > 0) {
BL = Yg.BL();
fVar3 = new f(context);
fVar3.setTitle(i.wallet_order_info_from);
fVar3.setContent(BL);
arrayList.add(fVar3);
}
}
if (!bi.oW(mallTransactionObject.desc)) {
if (obj != null) {
fVar2 = new f(context);
if (mallTransactionObject.lNG == 32 || mallTransactionObject.lNG == 33 || mallTransactionObject.lNG == 31) {
fVar2.setTitle(i.wallet_order_info_collect_remark_txt);
} else {
fVar2.setTitle(i.wallet_order_info_from);
}
fVar2.setContent(mallTransactionObject.desc);
arrayList.add(fVar2);
} else {
fVar2 = new f(context);
if (mallTransactionObject.lNG == 31) {
fVar2.setTitle(i.wallet_order_info_remittance_memo);
} else {
fVar2.setTitle(i.wallet_order_info_desc);
}
if (bi.oW(mallTransactionObject.lNL)) {
fVar2.setContent(mallTransactionObject.desc);
} else {
string2 = context.getString(i.wallet_order_info_check_detail);
fVar2.a(mallTransactionObject.desc + " " + string2, mallTransactionObject.desc.length() + 1, string2.length() + (mallTransactionObject.desc.length() + 1), new 2(this, mallTransactionObject, fVar2, fVar));
}
arrayList.add(fVar2);
}
}
if (!bi.oW(mallTransactionObject.lOv)) {
fVar2 = new f(context);
fVar2.setTitle(i.wallet_order_original_feeinfo_title);
fVar2.setContent(mallTransactionObject.lOv);
arrayList.add(fVar2);
}
if (!bi.oW(mallTransactionObject.lOu)) {
fVar2 = new f(context);
fVar2.setTitle(i.wallet_order_rate_title);
fVar2.setContent(mallTransactionObject.lOu);
arrayList.add(fVar2);
}
if (!TextUtils.isEmpty(mallTransactionObject.lOm)) {
fVar2 = new f(context);
fVar2.setTitle(i.wallet_order_info_charge_fee);
fVar2.setContent(mallTransactionObject.lOm);
arrayList.add(fVar2);
}
if (!bi.oW(mallTransactionObject.lNK)) {
fVar2 = new f(context);
fVar2.setTitle(i.wallet_order_info_merchant_name);
fVar2.setContent(mallTransactionObject.lNK);
arrayList.add(fVar2);
}
if (!bi.oW(mallTransactionObject.lNP)) {
fVar2 = new f(context);
fVar2.setTitle(i.wallet_order_info_status);
if (mallTransactionObject.lNG != 31 || q.GF().equals(mallTransactionObject.lOk) || mallTransactionObject.lOl <= 0 || bi.oW(mallTransactionObject.lOk) || bi.oW(mallTransactionObject.bOe)) {
fVar2.setContent(mallTransactionObject.lNP);
if (!bi.oW(mallTransactionObject.lNQ)) {
fVar2.Jw(mallTransactionObject.lNQ);
}
} else {
string2 = context.getString(i.remittance_resend_transfer_msg);
fVar2.a(mallTransactionObject.lNP + " " + string2, mallTransactionObject.lNP.length() + 1, (string2.length() + mallTransactionObject.lNP.length()) + 1, new 3(this, context, mallTransactionObject));
}
arrayList.add(fVar2);
}
fVar2 = new f(context);
fVar2.setTitle(i.wallet_order_info_deal_time);
fVar2.setContent(e.hb(mallTransactionObject.dTR));
arrayList.add(fVar2);
if (!bi.oW(mallTransactionObject.lNT)) {
f fVar4 = new f(context);
fVar4.setTitle(i.wallet_order_info_pay_method);
BL = mallTransactionObject.lNT;
if (!bi.oW(mallTransactionObject.lNU)) {
BL = BL + "(" + mallTransactionObject.lNU + ")";
}
fVar4.setContent(BL);
arrayList.add(fVar4);
}
if (!bi.oW(mallTransactionObject.bOe)) {
fVar2 = new f(context);
fVar2.setTitle(i.wallet_order_info_trans_id);
fVar2.setContent(mallTransactionObject.bOe);
arrayList.add(fVar2);
}
if (!bi.oW(mallTransactionObject.lNS)) {
fVar2 = new f(context);
fVar2.setTitle(i.wallet_order_info_sp_billno);
if (mallTransactionObject.lNG == 8) {
fVar2.setContent(context.getString(i.wallet_order_info_sp_billno_tip));
c cVar = new c(context);
final Bitmap b = com.tencent.mm.bm.a.a.b(context, mallTransactionObject.lNS, 5, 0);
cVar.lQk = e.acd(mallTransactionObject.lNS);
cVar.dHf = b;
cVar.mOnClickListener = new OnClickListener() {
public final void onClick(View view) {
if (a.this.lQc != null) {
a aVar = a.this;
Bitmap bitmap = b;
String str = mallTransactionObject.lNS;
if (aVar.lQc != null) {
aVar.lQc.gn(str, str);
aVar.lQc.lLl = bitmap;
aVar.lQc.lLm = bitmap;
aVar.lQc.cDE();
}
a.this.lQc.v(view, true);
}
}
};
arrayList.add(fVar2);
arrayList.add(cVar);
} else {
fVar2.setContent(mallTransactionObject.lNS);
arrayList.add(fVar2);
}
}
Object obj2 = mallTransactionObject.lNv.size() == 0 ? null : 1;
if (obj2 != null || (bi.oW(mallTransactionObject.lOf) && bi.oW(mallTransactionObject.lNW) && bi.oW(mallTransactionObject.lNy))) {
hVar = new h(context);
hVar.lQz = true;
hVar.gOc = false;
arrayList.add(hVar);
} else {
hVar = new h(context);
hVar.lQz = true;
arrayList.add(hVar);
arrayList.add(com.tencent.mm.plugin.order.model.a.a(context, mallTransactionObject));
}
if (obj2 != null) {
j jVar = new j(context);
if (mallTransactionObject.lNw == 1) {
if (!(bi.oW(mallTransactionObject.lOf) && bi.oW(mallTransactionObject.lNW) && bi.oW(mallTransactionObject.lNy))) {
if (bi.oW(mallTransactionObject.lOg)) {
jVar.lQD = context.getString(i.wallet_order_info_support_customer_service);
} else {
jVar.lQD = mallTransactionObject.lOg;
}
jVar.lQE = new OnClickListener() {
public final void onClick(View view) {
List linkedList = new LinkedList();
List linkedList2 = new LinkedList();
if (!bi.oW(mallTransactionObject.lNW)) {
linkedList2.add(Integer.valueOf(0));
linkedList.add(context.getString(i.wallet_order_info_support_biz));
}
if (!bi.oW(mallTransactionObject.lNy)) {
linkedList2.add(Integer.valueOf(1));
linkedList.add(context.getString(i.wallet_order_info_support_call));
}
if (!bi.oW(mallTransactionObject.lOf)) {
linkedList2.add(Integer.valueOf(2));
linkedList.add(context.getString(i.wallet_order_info_support_safeguard));
}
if (linkedList2.size() == 1) {
com.tencent.mm.plugin.order.model.a.a(((Integer) linkedList2.get(0)).intValue(), context, mallTransactionObject);
return;
}
h.a(context, null, linkedList, linkedList2, null, true, new 1(this));
}
};
}
} else if (!bi.oW(mallTransactionObject.lOg)) {
jVar.lQD = mallTransactionObject.lOg;
jVar.lQE = new OnClickListener() {
public final void onClick(View view) {
a.a(context, mallTransactionObject.lOf, mallTransactionObject);
}
};
}
jVar.lNv = mallTransactionObject.lNv;
jVar.mOnClickListener = new 7(this, context, mallTransactionObject);
hVar = new h(context);
hVar.lQz = true;
arrayList.add(hVar);
arrayList.add(jVar);
}
return arrayList;
}
}
|
package com.example.myitemstock.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Entity
public class User {
@Id
private Long id;
private String email;
private String nickname;
private String passwd;
// 1대다 단방향 관계
@OneToMany
@JoinColumn(name = "USER_ID")
private Set<Item> items;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public Set<Item> getItems() {
return items;
}
public void addItem(Item item) {
this.items.add(item);
}
public void removeItem(Item item){
this.items.remove(item);
}
}
|
package br.org.funcate.glue.main;
import java.util.Locale;
import br.org.funcate.glue.controller.Mediator;
import br.org.funcate.glue.model.ContextToGroupMap;
import br.org.funcate.glue.model.InfoClick;
import br.org.funcate.glue.model.canvas.CanvasState;
import br.org.funcate.glue.model.toolbar.ToolbarState;
import br.org.funcate.glue.model.tree.TreeState;
import br.org.funcate.glue.service.TerraJavaClient;
import br.org.funcate.glue.service.utils.NetworkService;
public class AppSingleton {
private static AppSingleton instance;
private TreeState treeState;
private ToolbarState toolbarState;
private Mediator mediator;
private CanvasState canvasState;
private TerraJavaClient services;
private ContextToGroupMap contextToGroupMap;
private Locale locale;
private InfoClick infoClick;
private NetworkService networkService;
private AppSingleton() {
services = new TerraJavaClient();
toolbarState = new ToolbarState();
treeState = new TreeState();
mediator = new Mediator();
canvasState = new CanvasState();
this.contextToGroupMap = new ContextToGroupMap();
networkService = new NetworkService();
locale = Locale.getDefault();
this.infoClick = new InfoClick();
}
public static AppSingleton getInstance() {
if (instance == null) {
instance = new AppSingleton();
}
return instance;
}
public TerraJavaClient getServices() {
return services;
}
public Mediator getMediator() {
return mediator;
}
public ToolbarState getToolbarState() {
return toolbarState;
}
public CanvasState getCanvasState() {
return canvasState;
}
public TreeState getTreeState() {
return treeState;
}
public ContextToGroupMap getGroupMapParameters() {
return contextToGroupMap;
}
public void setGroupMapParameters(ContextToGroupMap groupMapParameters) {
this.contextToGroupMap = groupMapParameters;
}
public Locale getLocale() {
return locale;
}
public InfoClick getInfoClick() {
return this.infoClick;
}
public NetworkService getNetworkService() {
return networkService;
}
}
|
import java.util.Vector;
import java.util.Iterator;
import java.util.Random;
/*
This program attempts to find layouts for the coloured-card matching
game 'Line Up' that use all 90 cards.
To Do:
------
- Add a '-h' or '-html' command line switch for html output mode?
- Could use existing map drawing methods - add " if (!printHTML) return; "
to HTML printers and equivalent for TXT printers
- Could also add a debug method to wrap all System.out.print/println fns
with a level
*/
public class LineUp {
private Piece[] pieces = new Piece[90];
// Pieces are placed into a 90 x 90 X-Y grid layout with the first
// piece always being placed at position (45,45). It would be
// possible for an unusual layout to exceed these bounds!
private Piece[][] layout = new Piece[90][90]; // 180 x 180?
private Vector available = new Vector(90);
private boolean outputHTML = false;
// Setting this greater than 0 provides more verbose information while running.
private int debugLevel = 0;
private int piecesTried = 0;
private int mapsFound = 0;
//
// Constructor.
//
public LineUp(){
createPieces();
clearLayout();
resetAvailablePieces();
}
//
// Define the 90 pieces.
//
public void createPieces() {
int count = 0;
// The comments for each piece are as follows:
// The photograph containing this piece:
//
// Image: X.jpg
// A rough visual description to help distinguish this piece:
//
// Type: X
// The position of this piece in the photograph (labelled, left
// to right, top to bottom):
//
// Position: X (1..12)
// Create a new piece by defining the colours for the two
// matching points on each side of the piece as you proceed in
// a clockwise direction starting from the top left corner.
// See 'Piece.java' for more information:
//
// pieces[X] = new Piece(new char[] {'','','','','','','',''});
// Image: a.jpg
// Type: A 'j + r'
// Position: 1
pieces[0] = new Piece(new char[] {'B','Y',' ','Y',' ',' ',' ','B'}, count++);
// Image: a.jpg
// Type: B 'double rainbow'
// Position: 2
pieces[1] = new Piece(new char[] {' ',' ','R','Y','Y','O',' ',' '}, count++);
// Image: a.jpg
// Type: C '| + C'
// Position: 3
pieces[2] = new Piece(new char[] {'R',' ','Y','G',' ','R',' ',' '}, count++);
// Image: a.jpg
// Type: D '='
// Position: 4
pieces[3] = new Piece(new char[] {' ',' ','O','Y',' ',' ','Y','R'}, count++);
// Image: a.jpg
// Type: E '|'
// Position: 5
pieces[4] = new Piece(new char[] {' ',' ',' ','G',' ',' ','Y',' '}, count++);
// Image: a.jpg
// Type: F '| + r'
// Position: 6
pieces[5] = new Piece(new char[] {'O',' ',' ','G',' ',' ','Y','O'}, count++);
// Image: a.jpg
// Type: G 'single large rainbow'
// Position: 7
pieces[6] = new Piece (new char[] {'G',' ',' ','Y',' ',' ',' ',' '}, count++);
// Image: a.jpg
// Type: F '| + r'
// Position: 8
pieces[7] = new Piece(new char[] {' ',' ','G',' ',' ','O','O','Y'}, count++);
// Image: a.jpg
// Type: C '| + C'
// Position: 9
pieces[8] = new Piece(new char[] {' ','R',' ',' ','O',' ','B','G'}, count++);
// Image: a.jpg
// Type: H 'single stop'
// Position: 10
pieces[9] = new Piece(new char[] {'G',' ',' ',' ',' ',' ',' ',' '}, count++);
// Image: a.jpg
// Type: F '| + r'
// Position: 11
pieces[10] = new Piece(new char[] {'Y',' ',' ','G',' ',' ','G','Y'}, count++);
// Image: a.jpg
// Type: F '| + r'
// Position: 12
pieces[11] = new Piece(new char[] {'O','R','R',' ',' ','Y',' ',' '}, count++);
// Next highest type: I
// Image: b.jpg
// Type: B 'double rainbow'
// Position: 1
pieces[12] = new Piece(new char[] {' ',' ','G','Y','Y','B',' ',' '}, count++);
// Image: b.jpg
// Type: F '| + r'
// Position: 2
pieces[13] = new Piece(new char[] {' ','B',' ',' ','B','R','R',' '}, count++);
// Image: b.jpg
// Type: A 'j + r'
// Position: 3
pieces[14] = new Piece(new char[] {'B',' ','G','Y','Y',' ',' ',' '}, count++);
// Image: b.jpg
// Type: I 'j + |'
// Position: 4
pieces[15] = new Piece(new char[] {' ','R',' ','R',' ',' ','R','O'}, count++);
// Image: b.jpg
// Type: G 'single large rainbow'
// Position: 5
pieces[16] = new Piece(new char[] {'R',' ',' ','O',' ',' ',' ',' '}, count++);
// Image: b.jpg
// Type: I 'j + |'
// Position: 6
pieces[17] = new Piece(new char[] {'G','O',' ',' ','R',' ','G',' '}, count++);
// Image: b.jpg
// Type: B 'double rainbow'
// Position: 7
pieces[18] = new Piece (new char[] {' ',' ','G','O','O','G',' ',' '}, count++);
// Image: b.jpg
// Type: J 'C'
// Position: 8
pieces[19] = new Piece(new char[] {' ',' ',' ',' ',' ',' ','Y','G'}, count++);
// Image: b.jpg
// Type: B 'double rainbow'
// Position: 9
pieces[20] = new Piece(new char[] {'B','R','R','B',' ',' ',' ',' '}, count++);
// Image: b.jpg
// Type: E '|'
// Position: 10
pieces[21] = new Piece(new char[] {' ',' ',' ','O',' ',' ','Y',' '}, count++);
// Image: b.jpg
// Type: B 'double rainbow'
// Position: 11
pieces[22] = new Piece(new char[] {'G','O','O','Y',' ',' ',' ',' '}, count++);
// Image: b.jpg
// Type: D '='
// Position: 12
pieces[23] = new Piece(new char[] {' ',' ','O','B',' ',' ','B','R'}, count++);
// Next highest type: K
// Image: c.jpg
// Type: D '='
// Position: 1
pieces[24] = new Piece(new char[] {' ',' ','Y','G',' ',' ','G','O'}, count++);
// Image: c.jpg
// Type: K 'U'
// Position: 2
pieces[25] = new Piece(new char[] {' ',' ','R','Y',' ',' ',' ',' '}, count++);
// Image: c.jpg
// Type: E '|'
// Position: 3
pieces[26] = new Piece(new char[] {' ','G',' ',' ','B',' ',' ',' '}, count++);
// Image: c.jpg
// Type: L 'stop + |'
// Position: 4
pieces[27] = new Piece(new char[] {' ','O',' ',' ','Y','G',' ',' '}, count++);
// Image: c.jpg
// Type: M 'r + stop'
// Position: 5
pieces[28] = new Piece(new char[] {' ',' ',' ',' ','O','G','G',' '}, count++);
// Image: c.jpg
// Type: K 'U'
// Position: 6
pieces[29] = new Piece(new char[] {'Y','G',' ',' ',' ',' ',' ',' '}, count++);
// Image: c.jpg
// Type: L 'stop + |'
// Position: 7
pieces[30] = new Piece (new char[] {' ',' ',' ','B',' ',' ','B','R'}, count++);
// Image: c.jpg
// Type: F '| + r'
// Position: 8
pieces[31] = new Piece(new char[] {' ',' ','Y','G','G',' ',' ','G'}, count++);
// Image: c.jpg
// Type: C '| + C'
// Position: 9
pieces[32] = new Piece(new char[] {' ','R',' ',' ','O',' ','G','Y'}, count++);
// Image: c.jpg
// Type: M 'j'
// Position: 10
pieces[33] = new Piece(new char[] {' ',' ','B',' ','G',' ',' ',' '}, count++);
// Image: c.jpg
// Type: N 'double stop'
// Position: 11 ? - NOT SURE!!
pieces[34] = new Piece(new char[] {' ',' ',' ',' ','O','G',' ',' '}, count++);
// Image: c.jpg
// Type: N 'stop + j'
// Position: 12
pieces[35] = new Piece(new char[] {' ',' ',' ','G',' ','G',' ','O'}, count++);
// Next highest type: O
// Image: d.jpg
// Type: ? '='
// Position: 1
pieces[36] = new Piece(new char[] {'O','G',' ',' ','B','O',' ',' '}, count++);
// Image: d.jpg
// Type: ? '| + r'
// Position: 2
pieces[37] = new Piece(new char[] {'Y',' ',' ','G','G','O',' ',' '}, count++);
// Image: d.jpg
// Type: ? ''
// Position: 3
pieces[38] = new Piece(new char[] {'R','B',' ',' ','G','Y','Y','R'}, count++);
// Image: d.jpg
// Type: ? ''
// Position: 4
pieces[39] = new Piece(new char[] {' ','G',' ',' ','Y','O',' ',' '}, count++);
// Image: d.jpg
// Type: ? ''
// Position: 5
pieces[40] = new Piece(new char[] {'O',' ',' ',' ',' ',' ','O',' '}, count++);
// Image: d.jpg
// Type: ? ''
// Position: 6
pieces[41] = new Piece(new char[] {'Y',' ','Y','G',' ',' ','G',' '}, count++);
// Image: d.jpg
// Type: ? ''
// Position: 7
pieces[42] = new Piece(new char[] {'Y',' ',' ',' ','Y',' ','G','Y'}, count++);
// Image: d.jpg
// Type: ? '|'
// Position: 8
pieces[43] = new Piece(new char[] {' ',' ',' ','O',' ',' ','O',' '}, count++);
// Image: d.jpg
// Type: ? ''
// Position: 9
pieces[44] = new Piece(new char[] {' ',' ',' ','B','B','O',' ','R'}, count++);
// Image: d.jpg
// Type: ? ''
// Position: 10
pieces[45] = new Piece(new char[] {' ','R',' ','O',' ','Y',' ','Y'}, count++);
// Image: d.jpg
// Type: ? '|'
// Position: 11
pieces[46] = new Piece(new char[] {' ',' ',' ','B',' ',' ','B',' '}, count++);
// Image: d.jpg
// Type: ? ''
// Position: 12
pieces[47] = new Piece(new char[] {'B',' ',' ',' ',' ',' ','G',' '}, count++);
// Next Highest Type: ?
// Image: e.jpg
// Type: ? ''
// Position: 1
pieces[48] = new Piece(new char[] {'Y','B','B',' ',' ','O',' ',' '}, count++);
// Image: e.jpg
// Type: ? ''
// Position: 2
pieces[49] = new Piece(new char[] {'Y','O',' ','O',' ','G','G','Y'}, count++);
// Image: e.jpg
// Type: ? '='
// Position: 3
pieces[50] = new Piece(new char[] {'Y','G',' ',' ','G','Y',' ',' '}, count++);
// Image: e.jpg
// Type: ? 'U'
// Position: 4
pieces[51] = new Piece(new char[] {' ',' ',' ',' ','O','Y',' ',' '}, count++);
// Image: e.jpg
// Type: ? ''
// Position: 5
pieces[52] = new Piece(new char[] {' ','Y',' ',' ',' ',' ','G',' '}, count++);
// Image: e.jpg
// Type: ? ''
// Position: 6
pieces[53] = new Piece(new char[] {' ',' ',' ','O','O',' ','Y','G'}, count++);
// Image: e.jpg
// Type: ? '|'
// Position: 7
pieces[54] = new Piece(new char[] {' ',' ',' ','G',' ',' ','G',' '}, count++);
// Image: e.jpg
// Type: ? ''
// Position: 8
pieces[55] = new Piece(new char[] {'G','Y',' ',' ','O',' ',' ','G'}, count++);
// Image: e.jpg
// Type: ? '|'
// Position: 9
pieces[56] = new Piece(new char[] {' ',' ',' ','R',' ',' ','R',' '}, count++);
// Image: e.jpg
// Type: ? ''
// Position: 10
pieces[57] = new Piece(new char[] {' ',' ','O','G',' ','Y',' ','R'}, count++);
// Image: e.jpg
// Type: ? ''
// Position: 11
pieces[58] = new Piece(new char[] {' ','B',' ',' ','B','Y','Y',' '}, count++);
// Image: e.jpg
// Type: ? ''
// Position: 12
pieces[59] = new Piece(new char[] {'Y','G','G','B','B',' ','O',' '}, count++);
// Next highest type: O
// Image: f.jpg
// Type: ? ''
// Position: 1
pieces[60] = new Piece(new char[] {' ',' ',' ','R','R',' ',' ',' '}, count++);
// Image: f.jpg
// Type: ? '='
// Position: 2
pieces[61] = new Piece(new char[] {'R','G',' ',' ','Y','O',' ',' '}, count++);
// Image: f.jpg
// Type: ? 'U'
// Position: 3
pieces[62] = new Piece(new char[] {' ',' ',' ',' ','Y','O',' ',' '}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 4
pieces[63] = new Piece(new char[] {'O','B',' ','G',' ','R',' ',' '}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 5
pieces[64] = new Piece(new char[] {'O','Y',' ',' ','G',' ','Y',' '}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 6
pieces[65] = new Piece(new char[] {'Y',' ',' ','Y',' ',' ',' ',' '}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 7
pieces[66] = new Piece(new char[] {' ',' ','G','R','R','B',' ',' '}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 8
pieces[67] = new Piece(new char[] {'G','B',' ',' ',' ',' ','B','G'}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 9
pieces[68] = new Piece(new char[] {' ','Y','Y','R',' ',' ','R',' '}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 10
pieces[69] = new Piece(new char[] {' ','R','R',' ',' ','O','O',' '}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 11
pieces[70] = new Piece(new char[] {'R','Y',' ',' ','O',' ','R',' '}, count++);
// Image: f.jpg
// Type: ? ''
// Position: 12
pieces[71] = new Piece(new char[] {' ',' ',' ','O',' ',' ','O','Y'}, count++);
// Next highest type: O
// Image: g.jpg
// Type: ? ''
// Position: 1
pieces[72] = new Piece(new char[] {' ',' ',' ','Y',' ',' ','Y','B'}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 2
pieces[73] = new Piece(new char[] {' ',' ','G',' ',' ','B',' ',' '}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 3
pieces[74] = new Piece(new char[] {'B',' ',' ','Y','Y',' ',' ','B'}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 4
pieces[75] = new Piece(new char[] {'G',' ','R',' ','R','B',' ',' '}, count++);
// Image: g.jpg
// Type: ? 'C'
// Position: 5
pieces[76] = new Piece(new char[] {'Y','O',' ',' ',' ',' ',' ',' '}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 6
pieces[77] = new Piece(new char[] {'O','Y',' ',' ','O','Y',' ',' '}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 7
pieces[78] = new Piece(new char[] {'O','B',' ',' ','B','Y',' ',' '}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 8
pieces[79] = new Piece(new char[] {' ',' ','G','Y','Y','B','B','G'}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 9
pieces[80] = new Piece(new char[] {' ',' ',' ','R','R','B',' ',' '}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 10
pieces[81] = new Piece(new char[] {' ',' ',' ',' ','B',' ','B','O'}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 11
pieces[82] = new Piece(new char[] {'B','Y',' ','G',' ','B',' ',' '}, count++);
// Image: g.jpg
// Type: ? ''
// Position: 12
pieces[83] = new Piece(new char[] {'G','B','B','Y','Y','B',' ',' '}, count++);
// Next highest type: O
// Image: h.jpg
// Type: ? ''
// Position: 1
pieces[84] = new Piece(new char[] {' ',' ',' ',' ',' ',' ','B','R'}, count++);
// Image: h.jpg
// Type: ? ''
// Position: 2
pieces[85] = new Piece(new char[] {' ',' ','O',' ',' ','Y',' ',' '}, count++);
// Image: h.jpg
// Type: ? ''
// Position: 3
pieces[86] = new Piece(new char[] {'Y','O','O',' ',' ','O',' ',' '}, count++);
// Image: h.jpg
// Type: ? ''
// Position: 4
pieces[87] = new Piece(new char[] {'R',' ',' ',' ',' ',' ','R',' '}, count++);
// Image: h.jpg
// Type: ? '='
// Position: 5
pieces[88] = new Piece(new char[] {'R','B',' ',' ','B','R',' ',' '}, count++);
// Image: h.jpg
// Type: ? ''
// Position: 6
pieces[89] = new Piece(new char[] {'B','G',' ',' ','G','B',' ',' '}, count++);
}
//
// Add all of the pieces back onto the available pieces.
//
public void resetAvailablePieces(){
available.clear();
for (int i = 0; i < pieces.length; i++) {
available.add(pieces[i]);
}
}
//
// (Re-)Initialise the layout grid.
//
public void clearLayout() {
for (int i = 0; i < 90; i++){
for (int j = 0; j < 90; j++){
layout[i][j] = null;
}
}
}
//
// Print debug messages if the level is greater than 0.
//
public void printDebug(String str){
if (debugLevel > 0) {
System.out.print(str);
}
}
//
// Print debug messages with a newline if the level is greater
// than 0.
//
public void printDebugln(String str){
if (debugLevel > 0) {
System.out.println(str);
}
}
//
//
//
public void setHTMLoutput(boolean isHTML){
outputHTML = isHTML;
}
//
// Print a small representation of the entire layout where pieces
// are inidicated by an 'X'. This gives a quick overview of the
// maps shape.
//
// This could use an offset like the larger map although it may be
// interesting to see how the resulting layout is positioned in
// the overall grid (which is currently only 90x90 characters
// anyway).
//
public void printMiniMap() {
System.out.println("Mini Map:");
for (int i = 0; i < 90; i++){
System.out.print("-");
}
System.out.print("\n");
for (int i = 0; i < 90; i++){
for (int j = 0; j < 90; j++){
if (layout[j][i] == null) {
System.out.print(" ");
}
else {
System.out.print("X");
}
}
System.out.print("\n");
}
for (int i = 0; i < 90; i++){
System.out.print("-");
}
System.out.print("\n");
}
//
// This is a convenience method used for printing a piece that
// returns either the top/bottom bar or a blank row.
//
public String getEmptyRow(int row) {
if (row == 0 || row == 4) {
return "+------";
}
else {
return "| ";
}
}
//
// Find the row containing the top-most piece
//
public int topIndex(){
for (int i = 0; i < 90; i++){
for (int j = 0; j < 90; j++){
if (layout[j][i] != null){
return i;
}
}
}
return -1;
}
//
// Find the column containing the left-most piece for this layout
//
public int leftIndex(int topIndex) {
int leftIndex = 90;
for (int i = topIndex; i < 90; i++){
for (int j = 0; j < leftIndex; j++){
if (layout[j][i] != null){
leftIndex = j;
}
}
}
return leftIndex;
}
//
// Find the column of the right-most piece for this layout.
//
// Finding the rightmost and lowest pieces could be useful for
// determing how "big" a layout is if we are looking for the most
// compact layout.
//
public int rightIndex(int top) {
int rightIndex = 0;
for (int i = top; i < 90; i++){
for (int j = rightIndex; j < 90; j++){
if (layout[j][i] != null){
if (j > rightIndex){
rightIndex = j;
}
}
}
}
return rightIndex;
}
//
// Find the row of the lowest piece
//
public int bottomIndex(int topIndex){
int bottom = topIndex;
for (int i = topIndex; i < 90; i++){
for (int j = 0; j < 90; j++){
if (layout[j][i] != null){
bottom = i;
}
}
}
return bottom;
}
//
// Print a map representing the layout of the pieces to standard output
//
public void printMap() {
if (outputHTML){
return;
}
// find index of topmost piece
int top = topIndex();
printMap(top, leftIndex(top), bottomIndex(top), rightIndex(top));
}
//
// This version of printMap takes the position of the topmost and
// leftmost pieces and aligns the map to the top left position to
// minimise wasted space in the layout.
//
public void printMap(int top, int left, int bottom, int right) {
System.out.println("Map: (offset " + left + "," + top + ") " +
piecesTried + " pieces tried.");
for (int i = top; i <= bottom; i++){
for (int j = 0; j < 5; j++){
for (int k = left; k <= right; k++){
if (layout[k][i] == null) {
System.out.print(getEmptyRow(j));
//printDebug(getEmptyRow(j));
System.out.print(" ");
}
else {
System.out.print(layout[k][i].getRow(j));
}
}
System.out.print("\n");
}
}
}
//
// Output the opening HTML markup for colour layout map(s)
//
public void printHTMLHeader() {
System.out.print("<html>\n" +
"<head>\n" +
"<style>\n" +
".r { background-color: red; }\n" +
".y { background-color: yellow; }\n" +
".g { background-color: green; }\n" +
".b { background-color: blue; }\n" +
".o { background-color: orange; }\n" +
".w { background-color: white; }\n" +
".blank{ background-color: black; }\n" +
".code {font: 100% courier,monospace; overflow: auto; " +
"background-color: black;}\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div class=\"code\">\n");
// ".code {font: 100% courier,monospace; overflow: auto; " +
// "overflow-x: auto; overflow-x: auto; background-color: black;}\n" +
}
//
// Output the closing HTML markup for colour layout map(s)
//
public void printHTMLFooter() {
System.out.print("<br></div>" +
"</body>" +
"</html>");
}
//
// Output the HTML markup for a colour map and remove any emtpy
// rows or columns.
//
public void printHTMLMap() {
// find index of topmost piece
int top = topIndex();
printHTMLMap(top, leftIndex(top), bottomIndex(top), rightIndex(top));
}
//
// Output the HTML markup for a map wth the specified dimensions
//
public void printHTMLMap(int top, int left, int bottom, int right) {
System.out.println("<p class=\"w\">Map with offset (" + left + ","
+ top + ")</p><br>");
for (int i = top; i <= bottom; i++){
for (int j = 0; j < 5; j++){
System.out.print(" "); // add a leading space
for (int k = left; k <= right; k++){
if (layout[k][i] == null) {
System.out.print(" ");
}
else {
System.out.print(layout[k][i].getRowHTML(j));
}
}
System.out.print("<br>\n");
}
}
}
//
// Try to fit the given piece at the specified position.
//
public void tryPiece(Piece piece, int posX, int posY) {
if (layout[posX][posY] != null) {
//System.out.println("There is already a piece at " + posX + "," +
// posY + "! *************");
return;
}
// does it fit?
if (!alignPiece(piece, posX, posY)){
System.out.println("This piece does not fit at " + posX + "," +
posY + ":");
return;
//System.out.println(piece);
// break|exit|return here?
}
// add this piece at this location
layout[posX][posY] = piece;
printDebugln("Adding piece at " + posX + "," + posY);
//printMiniMap();
// remove it from the available list
available.removeElement(piece);
// check for each of the sides
if (layout[posX][posY - 1] == null) {
if (!((piece.getOffsetColPos(0) == ' ') &&
(piece.getOffsetColPos(1) == ' '))) {
tryMatches(posX, posY - 1);
}
}
if (layout[posX + 1][posY] == null) {
if (!((piece.getOffsetColPos(2) == ' ') &&
(piece.getOffsetColPos(3) == ' '))) {
tryMatches(posX + 1, posY);
}
}
if (layout[posX][posY + 1] == null) {
if (!((piece.getOffsetColPos(4) == ' ') &&
(piece.getOffsetColPos(5) == ' '))){
tryMatches(posX, posY + 1);
}
}
if (layout[posX - 1][posY] == null) {
if (!((piece.getOffsetColPos(6) == ' ') &&
(piece.getOffsetColPos(7) == ' '))) {
tryMatches(posX - 1, posY);
}
}
// Note that there are 5 pieces drawn in the comments at the
// start of Pieces.java which have more than one matching side
// and therefore more than one orientation (although one is a
// mirror so only 4 may effect the possible layout outcomes
}
//
// Look for a possible match for this position.
//
public void tryMatches(int posX, int posY){
// check the list of possible pieces for matches
Vector matches = getMatches(posX, posY);
//System.out.println("Trying " + matches.size() + " match(es) for " + posX +
// "," + posY);
Iterator possiblePieces = matches.iterator();
Piece currentPiece;
while(possiblePieces.hasNext()) {
currentPiece = (Piece) possiblePieces.next();
tryPiece(currentPiece, posX, posY);
// add the piece back again here? (or in tryPiece ?)
//available.addElement(currentPiece);
}
}
//
// Return a shuffled vector of possible matching pieces for this position.
//
public Vector getMatches(int posX, int posY) {
Vector possiblePieces = new Vector();
// create a match array for the surrounding non-empty pieces
char[] match = getMatchArray(posX, posY);
// check the list of available pieces for possible matches
Iterator availablePieces = available.iterator();
Piece currentPiece;
while(availablePieces.hasNext()) {
currentPiece = (Piece) availablePieces.next();
// test this piece
// print for debugging
/*
System.out.println("Testing piece:\n" + currentPiece);
System.out.print("[");
for (int i = 0; i < 4; i++) {
System.out.print(currentPiece.getColPos(i * 2) + "" +
currentPiece.getColPos((i * 2) + 1));
}
System.out.println("] <- current piece");
for (int j = 0; j < 8; j = j + 2) {
System.out.print("[");
for (int i = 0; i < 4; i++) {
System.out.print(match[(j + (i * 2)) % 8] + ""
+ match[((j + (i * 2)) % 8) + 1]);
}
System.out.println("] j=" + j);
}
*/
Boolean matched = true;
outer:
for (int j = 0; j < 8; j = j + 2) {
for (int i = 0; i < 4; i++) {
if (match[(j + (i * 2)) % 8] != '-') { // only check non-blank sides!
// check any non-blank sides
if ((currentPiece.getColPos(i * 2) != match[(j + (i * 2)) % 8]) ||
(currentPiece.getColPos((i * 2) + 1) != match[((j + (i * 2)) % 8) + 1])){
matched = false;
//System.out.println("no match on j=" + j + ", i=" + i);
break; // no need to keep testing
}
else {
//System.out.println("matched on j=" + j + ", i=" + i);
}
}
else {
//System.out.println("blank side on j=" + j + ", i=" + i);
}
}
if (matched) {
//System.out.print("Possible piece for [" + posX + "][" + posY +
// "] is\n" + currentPiece);
possiblePieces.add(currentPiece);
break outer;
}
else {
matched = true; // reset the flag and rotate
}
}
}
// shuffle pieces
Vector shuffledPieces = new Vector(possiblePieces.size());
Random rnd = new Random();
//System.out.println("Possible: " + possiblePieces.toString());
while (possiblePieces.size() > 0) {
shuffledPieces.add((Piece) possiblePieces.remove(rnd.nextInt(possiblePieces.size())));
}
//System.out.println("Shuffled: " + shuffledPieces.toString());
//return possiblePieces;
return shuffledPieces;
}
//
// Check the sides of surrounding non-empty pieces to use when we
// look or possble matching pieces.
//
public char[] getMatchArray(int posX, int posY) {
// create a match array from surrounding non-empty pieces
char[] match = new char[] {'-','-','-','-','-','-','-','-'};
// check piece above
if (layout[posX][posY - 1] != null) {
match[0] = layout[posX][posY - 1].opposite(0);
match[1] = layout[posX][posY - 1].opposite(1);
}
// check piece right
if (layout[posX + 1][posY] != null) {
match[2] = layout[posX + 1][posY].opposite(2);
match[3] = layout[posX + 1][posY].opposite(3);
}
// check piece below
if (layout[posX][posY + 1] != null) {
match[4] = layout[posX][posY + 1].opposite(4);
match[5] = layout[posX][posY + 1].opposite(5);
}
// check piece left
if (layout[posX - 1][posY] != null) {
match[6] = layout[posX - 1][posY].opposite(6);
match[7] = layout[posX - 1][posY].opposite(7);
}
//System.out.print("Match array for [" + posX + "][" + posY + "] = |");
// for (int i = 0; i < match.length; i++) {
// System.out.print(match[i]);
//}
//System.out.print("|\n");
return match;
}
//
// This method rotates the piece to match so that it fits with any
// already existing pieces surrounding it. It returns false if
// this is not possible.
//
public Boolean alignPiece(Piece piece, int posX, int posY) {
//System.out.println("Rotating piece in position " + posX + ", " + posY + " :");
//System.out.println(piece);
char[] match = getMatchArray(posX, posY);
Boolean matched = true;
outer:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (match[j * 2] != '-') { // only check non-blank sides!
// check any non-blank sides
if ((piece.getOffsetColPos(j * 2) != match[j * 2]) ||
(piece.getOffsetColPos((j * 2) + 1) != match[(j * 2) + 1])){
matched = false;
//System.out.println("no match on j=" + j + ", i=" + i);
break; // no need to keep testing
}
else {
//System.out.println("matched on j=" + j + ", i=" + i);
}
}
else {
//System.out.println("blank side on j=" + j + ", i=" + i);
}
}
if (matched) {
//System.out.println("Piece aligned in position " + posX +
// ", " + posY + " :");
printDebug(piece.toString());
return true;
}
else {
matched = true; // reset the flag
piece.rotate(); // rotate the piece and try again
}
}
return false;
}
//
// Choose a random piece and then try to find a layout using all
// 90 pieces. Try to find layouts by trying each piece in turn
// as a starting piece and checking it in all 4 orientatons.
//
public void solve() {
setHTMLoutput(true);
printHTMLHeader();
Piece first = null;
for (int i = 0; i < pieces.length; i++) { // try all pieces!
first = pieces[i];
// try all rotations of this piece!
for (int rot = 0; rot < 4; rot++) {
tryPiece(first, 45, 45); // place piece in the center
printDebugln("Starting with piece " + i +
" leaves " + available.size() + " pieces.");
if (available.size() == 0) {
System.out.println("Starting with piece " + i);
printHTMLMap();
//printMiniMap();
//printMap();
System.out.println(++mapsFound + " map(s) found!\n");
}
clearLayout();
resetAvailablePieces();
first.rotate();
}
}
printHTMLFooter();
}
//
// Create a puzzle and start looking for solutions!
//
public static void main(String args[]) {
LineUp l = new LineUp();
l.solve();
// Testing the class:
/*
l.layout[2][1] = l.pieces[6]; // a.jpg piece 7
l.layout[2][1].rotate(Piece.TOP, Piece.RIGHT);
l.layout[1][2] = l.pieces[2]; // a.jpg piece 3
l.layout[3][2] = l.pieces[9]; // a.jpg piece 10
l.layout[3][2].rotate(Piece.TOP, Piece.LEFT);
System.out.println(l.available.size() + " pieces available.");
// Text output
l.printMiniMap();
l.printMap();
Vector v = null;
v = l.getMatches(1,1);
v = l.getMatches(3,1);
v = l.getMatches(2,2);
v = l.getMatches(1,3);
// HTML output
//l.printHTMLHeader();
//l.printHTMLMap();
//l.printHTMLFooter();
l.alignPiece(l.pieces[8], 1, 1);
l.pieces[10].rotate();
l.alignPiece(l.pieces[10], 2, 2);
l.alignPiece(l.pieces[17], 4, 4);
*/
}
}
|
/*
* 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 ejemplointerface;
/**
*
* @author Nicolas Vargas
*/
public interface PersonaAsalariada
{
public double calcularSalario();
public String imprimirInformacion();
}
|
package d_fourthexp;
/*
*
* @程序名: ReverseString.java
* @编程人: 陈若楠 (学号: 1512480434)
* @编程日期: 2017-10-25
* @修改日期: 2017-10-25
*
*/
import java.util.Scanner;
// 编写一个方法用于验证指定的字符串是否为反转字符,返回true和false。请用递归算法实现。(反转字符串样式为"abcdedcba")
public class ReverseString {
private static int lengthOfArray;
private static boolean flag = true;
private static void checkReverseString(char[] arr, int i) {
if (i < lengthOfArray / 2) {
return;
}
if (arr[i - 1] == arr[lengthOfArray - i]) {
checkReverseString(arr, i - 1);
} else {
flag = false;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
scanner.close();
char[] arr = str.toCharArray();
lengthOfArray = arr.length;
checkReverseString(arr,lengthOfArray);
System.out.println(flag);
}
}
|
package com.bunny.taskapi.service;
import com.bunny.taskapi.domain.Tasks;
public interface TaskCommandService {
public Tasks upsertTasks(Tasks tasks);
}
|
package ru.itis.javalab.config;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import javax.sql.DataSource;
import java.util.Objects;
/**
* ApplicationConfig
* created: 23-01-2021 - 20:20
* project: 11.CSRF
*
* @author dinar
* @version v0.1
*/
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "ru.itis.javalab")
@PropertySource("classpath:database/db.properties")
public class ApplicationConfig {
public final Environment environment;
@Autowired
public ApplicationConfig(Environment environment) {
this.environment = environment;
}
@Bean
public HikariConfig hikariConfig() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(environment.getProperty("db.jdbc.url"));
config.setUsername(environment.getProperty("db.jdbc.username"));
config.setPassword(environment.getProperty("db.jdbc.password"));
config.setDriverClassName(environment
.getProperty("db.jdbc.driver.classname"));
config.setMaximumPoolSize(Integer.parseInt(
Objects.requireNonNull(environment
.getProperty("db.jdbc.hikari.max-pool-size"))));
return config;
}
@Bean
public DataSource dataSource() {
return new HikariDataSource(hikariConfig());
}
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
return configurer;
}
@Bean
public FreeMarkerViewResolver freeMarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftlh");
return resolver;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
public SimpleJdbcInsert simpleJdbcInsert() {
return new SimpleJdbcInsert(jdbcTemplate());
}
}
|
/*******************************************************************************
* Copyright 2020 Grégoire Martinetti
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.fields;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.EnumSpecification;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.TypeExpression;
public class ClassAbstractEnumField extends AbstractTypedField {
EnumSpecification enumType;
@Override
public EnumSpecification getTypeExpression() {
return enumType;
}
public <T extends EnumSpecification> void setTypeExpression(T typeExpression) {
this.enumType = typeExpression;
}
@Override
public <T extends TypeExpression> void setTypeExpression(T typeExpression) {
this.enumType = (EnumSpecification) typeExpression;
}
public ClassAbstractEnumField(String name, boolean isOptional) {
super(name, isOptional);
}
public ClassAbstractEnumField(String name, boolean isOptional, EnumSpecification typeExpression) {
this(name, isOptional);
this.enumType = typeExpression;
}
@Override
public boolean isAbstract() {
return true;
}
}
|
package com.project.linkedindatabase.repository.model.post;
import com.project.linkedindatabase.domain.BaseEntity;
import com.project.linkedindatabase.domain.Profile;
import com.project.linkedindatabase.domain.post.Comment;
import com.project.linkedindatabase.domain.post.Post;
import com.project.linkedindatabase.jsonToPojo.CommentJson;
import com.project.linkedindatabase.jsonToPojo.ProfileJson;
import com.project.linkedindatabase.repository.BaseRepository;
import com.project.linkedindatabase.service.model.ProfileService;
import com.project.linkedindatabase.service.model.post.LikeCommentService;
import com.project.linkedindatabase.utils.DateConverter;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
@Service
public class CommentRepository extends BaseRepository<Comment,Long> {
private final LikeCommentService likeCommentService;
private final ProfileService profileService;
public CommentRepository(LikeCommentService likeCommentService, ProfileService profileService) throws SQLException {
super(Comment.class);
this.likeCommentService = likeCommentService;
this.profileService = profileService;
}
@Override
public void save(Comment object) throws SQLException{
PreparedStatement savingPs = this.conn.prepareStatement("INSERT INTO " + this.tableName + "(profileId, postId, reCommentId, body, createdDate)" +
" VALUES(?,?,?,?,?)");
savingPs.setLong(1, object.getProfileId());
savingPs.setLong(2, object.getPostId());
if (object.getReCommentId() != null){
savingPs.setLong(3, object.getReCommentId());}
else
{
savingPs.setNull(3, Types.BIGINT);
}
savingPs.setString(4, object.getBody());
savingPs.setString(5, DateConverter.convertDate(object.getCreatedDate(), "yyyy-MM-dd HH:mm:ss"));
savingPs.execute();
}
@Override
public void createTable() throws SQLException {
PreparedStatement createTablePs = this.conn.prepareStatement("CREATE TABLE IF NOT EXISTS " + this.tableName + "(" +
"id BIGINT NOT NULL AUTO_INCREMENT,"+
"profileId BIGINT NOT NULL," +
"FOREIGN KEY (profileId) REFERENCES " + BaseEntity.getTableName(Profile.class) + "(id),"+
"postId BIGINT NOT NULL," +
"FOREIGN KEY (postId) REFERENCES " + BaseEntity.getTableName(Post.class) + "(id),"+
"reCommentId BIGINT ," +
"FOREIGN KEY (reCommentId) REFERENCES " + BaseEntity.getTableName(Comment.class) + "(id),"+
"body TEXT NOT NULL,"+
"createdDate NVARCHAR(255) NOT NULL,"+
"PRIMARY KEY (id)"+
");"
);
createTablePs.execute();
}
@SneakyThrows
@Override
public Comment convertSql(ResultSet resultSet) throws SQLException {
Comment comment = new Comment();
comment.setId(resultSet.getLong("id"));
comment.setProfileId(resultSet.getLong("profileId"));
comment.setPostId(resultSet.getLong("postId"));
comment.setReCommentId(resultSet.getLong("reCommentId"));
comment.setBody( resultSet.getString("body"));
comment.setCreatedDate(DateConverter.parse(resultSet.getString("createdDate"), "yyyy-MM-dd HH:mm:ss"));
return comment;
}
public List<Comment> findByPostId(Long postId) throws SQLException {
PreparedStatement ps = conn.prepareStatement("select * from "+this.getTableName()+ " where postId = ?");
ps.setLong(1,postId);
ResultSet resultSet = ps.executeQuery();
List<Comment> allObject = new ArrayList<>();
while (resultSet.next()) {
allObject.add(convertSql(resultSet));
}
return allObject;
}
public List<CommentJson> findByPostIdJson(Long id) throws SQLException {
List<Comment> allObject = findByPostId(id);
List<CommentJson> commentJsonList = new ArrayList<>();
for (Comment i : allObject)
{
CommentJson commentJson = CommentJson.convertToJson(i);
likeCommentService.setAllLikeComment(commentJson);
Profile profile = profileService.findById(commentJson.getProfileId());
commentJson.setProfileJson(ProfileJson.convertToJson(profile));
commentJsonList.add(commentJson);
}
//create tree
List<CommentJson> tree = new ArrayList<>();
//simple explanation
// if it has reComment -> it has father so we find it and add to father
// if it has not reComment id -> it is root so we add to tree
for (CommentJson i :commentJsonList)
{
if (i.getReCommentId() == null || i.getReCommentId() == 0)
{
tree.add(i);
continue;
}
for (CommentJson j : commentJsonList)
{
if (j.getId() == i.getReCommentId())
{
j.getCommentJsonsChild().add(i);
}
}
}
return tree;
}
}
|
package com.example.muh_r.uangkita;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
public class AdapterListTransaksiDay extends RecyclerView.Adapter <AdapterListTransaksiDay.TransaksiViewHolder> {
LayoutInflater mInflater;
ArrayList<Transaksi> transaksi;
Context _context;
private IHost iHost;
//konstruktor
public AdapterListTransaksiDay(Context context, ArrayList<Transaksi> transaksi) {
this.mInflater = LayoutInflater.from(context);
this.transaksi = transaksi;
this._context = context;
}
public AdapterListTransaksiDay(Context context, ArrayList<Transaksi> transaksi, IHost iHost) {
this.mInflater = LayoutInflater.from(context);
this.transaksi = transaksi;
this._context = context;
this.iHost = iHost;
}
@NonNull
@Override
public AdapterListTransaksiDay.TransaksiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.activity_item_list_transaksi_day, parent, false);
return new TransaksiViewHolder(itemView, this);
}
@Override
public void onBindViewHolder(@NonNull AdapterListTransaksiDay.TransaksiViewHolder holder, int position) {
Transaksi current = transaksi.get(position);
// Add the data to the view
holder.pengeluaran_textView.setText(current.pengeluaran);
holder.pemasukan_textView.setText(current.pemasukan);
holder.tanggal_textView.setText(current.tanggal);
holder.arrow.setOnClickListener(even-> {
iHost.openDetailBasedOnDate(Calendar.getInstance().getTime());
});
}
@Override
public int getItemCount() {
return transaksi.size();
}
class TransaksiViewHolder extends RecyclerView.ViewHolder {
TextView pengeluaran_textView, pemasukan_textView, tanggal_textView;
ImageView arrow;
AdapterListTransaksiDay mAdapter;
public TransaksiViewHolder(View itemView, AdapterListTransaksiDay adapter) {
super(itemView);
pengeluaran_textView = (TextView) itemView.findViewById(R.id.pengeluaran);
pemasukan_textView = (TextView) itemView.findViewById(R.id.pemasukan);
tanggal_textView = (TextView) itemView.findViewById(R.id.tanggal);
arrow = itemView.findViewById(R.id._iv_details);
this.mAdapter = adapter;
//telepon_textView.setOnClickListener(this);
}
}
}
|
package com.milos;
import com.milos.domain.logger.PrimitiveLogger;
public class MockedLogger implements PrimitiveLogger {
@Override
public void debug(String message) {
}
@Override
public void info(String message) {
}
@Override
public void warn(String message) {
}
@Override
public void error(String message) {
}
}
|
package com.tencent.tencentmap.mapsdk.a;
public class bm extends bj {
public bm(String str) {
super(str);
}
public bm(String str, Exception exception) {
super(str, exception);
}
}
|
package consulting.ross.demo.osgi.adapter.rest.envmon;
import consulting.ross.demo.osgi.envmon.EnvironmentMonitor;
import consulting.ross.demo.osgi.rest.envmon.EnvironmentMonitorResource;
//import consulting.ross.demo.osgi.envmon.SurveyResult;
import consulting.ross.demo.osgi.rest.envmon.Result;
/**
* Implementation of a REST resource that exposes some
* {@linkplain EnvironmentMonitor} functionality via
* JSON/HTTP.
*/
public class EnvironmentMonitorResourceAdapter implements EnvironmentMonitorResource
{
// We adapt to the real service
volatile EnvironmentMonitor delegate;
@Override
public Result performSurvey()
{
return new Result(
delegate.performSurvey() );
}
@Override
public void resetAlarms()
{
delegate.resetAlarms();
}
}
|
/*
* Copyright 2014, Stratio.
*
* 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.stratio.cassandra.index.service;
import com.stratio.cassandra.index.schema.Columns;
import com.stratio.cassandra.index.schema.Schema;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.DataRange;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.Row;
import org.apache.cassandra.db.composites.CellName;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
/**
* {@link RowMapper} for skinny rows.
*
* @author Andres de la Pena <adelapena@stratio.com>
*/
public class RowMapperSkinny extends RowMapper {
/**
* Builds a new {@link RowMapperSkinny} for the specified column family metadata, indexed column definition and
* {@link Schema}.
*
* @param metadata The indexed column family metadata.
* @param columnDefinition The indexed column definition.
* @param schema The mapping {@link Schema}.
*/
RowMapperSkinny(CFMetaData metadata, ColumnDefinition columnDefinition, Schema schema) {
super(metadata, columnDefinition, schema);
}
/**
* {@inheritDoc}
*/
@Override
public Columns columns(Row row) {
Columns columns = new Columns();
columns.addAll(partitionKeyMapper.columns(row));
columns.addAll(regularCellsMapper.columns(row));
return columns;
}
/**
* {@inheritDoc}
*/
@Override
public Document document(Row row) {
DecoratedKey partitionKey = row.key;
Document document = new Document();
tokenMapper.addFields(document, partitionKey);
partitionKeyMapper.addFields(document, partitionKey);
schema.addFields(document, columns(row));
return document;
}
/**
* Returns the Lucene {@link Sort} to get {@link Document}s in the same order that is used in Cassandra.
*
* @return The Lucene {@link Sort} to get {@link Document}s in the same order that is used in Cassandra.
*/
public Sort sort() {
return new Sort(tokenMapper.sortFields());
}
/**
* {@inheritDoc}
*/
@Override
public final Query query(DataRange dataRange) {
return tokenMapper.query(dataRange);
}
/**
* {@inheritDoc}
*/
@Override
public CellName makeCellName(ColumnFamily columnFamily) {
return metadata.comparator.makeCellName(columnDefinition.name.bytes);
}
/**
* {@inheritDoc}
*/
@Override
public RowComparator naturalComparator() {
return new RowComparatorNatural();
}
/**
* {@inheritDoc}
*/
@Override
public SearchResult searchResult(Document document, ScoreDoc scoreDoc) {
DecoratedKey partitionKey = partitionKeyMapper.partitionKey(document);
return new SearchResult(partitionKey, null, scoreDoc);
}
}
|
import java.io.Serializable;
import java.util.*;
public class GestaoVeiculo implements Serializable {
// variaveis instancia
private HashMap<String,Veiculo> veiculos; // String = matricula
// construtores
public GestaoVeiculo(){
this.veiculos = new HashMap();
}
public GestaoVeiculo (HashMap<String,Veiculo> veiculosAux){
this.veiculos = new HashMap<String,Veiculo>();
for(Veiculo v: veiculosAux.values())
this.veiculos.put(v.getMatricula(),v.clone());
}
public GestaoVeiculo(GestaoVeiculo g){
this.veiculos = g.getVeiculo();
}
// get's e set's
public HashMap<String,Veiculo> getVeiculo() {
HashMap<String,Veiculo> aux = new HashMap<>();
for(Veiculo v: this.veiculos.values())
aux.put(v.getMatricula(),v.clone());
return aux;
}
public void setVeiculo(HashMap<String,Veiculo> veiculos) {
this.veiculos = new HashMap<>();
for(Veiculo v : veiculos.values())
this.veiculos.put(v.getMatricula(),v.clone());
}
// metodos equals, clone e toString
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
GestaoVeiculo aux = (GestaoVeiculo) object;
return aux.getVeiculo().equals(this.getVeiculo());
}
public GestaoVeiculo clone(){
return new GestaoVeiculo(this);
}
// funcionalidade
public void addVeiculo(Veiculo v){
this.veiculos.put(v.getMatricula(),v.clone());
}
public boolean verifica(String e){
return(veiculos.containsKey(e));
}
public String procuraMaisBarato(Ponto destino){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco)){
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Bicicleta) result = v.getMatricula();
else {
if (v instanceof Gasolina) {
Gasolina aux = new Gasolina();
aux = (Gasolina) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
if (v instanceof Eletrico) {
Eletrico aux = new Eletrico();
aux = (Eletrico) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
if (v instanceof Hibridos) {
Hibridos aux = new Hibridos();
aux = (Hibridos) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
if (v instanceof Prancha) {
Prancha aux = new Prancha();
aux = (Prancha) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
}
return result;
}
public String procuraMaisBaratoGasolina(Ponto destino){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Gasolina) {
Gasolina aux = new Gasolina();
aux = (Gasolina) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
return result;
}
public String procuraMaisBaratoHibrido(Ponto destino){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Hibridos) {
Hibridos aux = new Hibridos();
aux = (Hibridos) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
return result;
}
public String procuraMaisBaratoEletrico(Ponto destino){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Eletrico) {
Eletrico aux = new Eletrico();
aux = (Eletrico) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
return result;
}
public String procuraMaisBaratoPrancha(Ponto destino){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Prancha) {
Prancha aux = new Prancha();
aux = (Prancha) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
return result;
}
public String procuraMaisBaratoBicicleta(){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l) {
if ((v.getPrecoKm() < preco) && (v instanceof Bicicleta)) result = v.getMatricula();
preco = v.getPrecoKm();
}
return result;
}
public String procuraMaisPerto(Ponto cliente,Ponto destino){
double dist = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getLocalizacao().distanciaPonto(cliente) < dist)){
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Bicicleta) result = v.getMatricula();
else {
if (v instanceof Gasolina) {
Gasolina aux = new Gasolina();
aux = (Gasolina) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);
}
if (v instanceof Eletrico) {
Eletrico aux = new Eletrico();
aux = (Eletrico) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);
}
if (v instanceof Hibridos) {
Hibridos aux = new Hibridos();
aux = (Hibridos) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);
}
if (v instanceof Prancha) {
Prancha aux = new Prancha();
aux = (Prancha) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);
}
}
}
return result;
}
public String procuraMaisPertoGasolina(Ponto destino,Ponto cliente){
double dist = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getLocalizacao().distanciaPonto(cliente) < dist)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Gasolina) {
Gasolina aux = new Gasolina();
aux = (Gasolina) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);
}
}
return result;
}
public String procuraMaisPertoHibrido(Ponto destino,Ponto cliente){
double dist = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getLocalizacao().distanciaPonto(cliente) < dist)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Hibridos) {
Hibridos aux = new Hibridos();
aux = (Hibridos) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);
}
}
return result;
}
public String procuraMaisPertoEletrico(Ponto destino,Ponto cliente){
double dist = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getLocalizacao().distanciaPonto(cliente) < dist)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Eletrico) {
Eletrico aux = new Eletrico();
aux = (Eletrico) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);
}
}
return result;
}
public String procuraMaisPertoPrancha(Ponto destino,Ponto cliente){
double dist = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getLocalizacao().distanciaPonto(cliente) < dist)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Prancha) {
Prancha aux = new Prancha();
aux = (Prancha) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);
}
}
return result;
}
public String procuraMaisPertoBicicleta(Ponto cliente){
double dist = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l){
if ((v.getLocalizacao().distanciaPonto(cliente) < dist) && (v instanceof Bicicleta)) result = v.getMatricula();
dist = v.getLocalizacao().distanciaPonto(cliente);}
return result;
}
public String procuraMaisBaratoDist(Ponto destino,Ponto cliente,double dist){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco) && (v.getLocalizacao().distanciaPonto(cliente)<=dist)){
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Bicicleta) {
result = v.getMatricula();
preco = v.getPrecoKm();
}
else {
if (v instanceof Gasolina) {
Gasolina aux = new Gasolina();
aux = (Gasolina) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
if (v instanceof Eletrico) {
Eletrico aux = new Eletrico();
aux = (Eletrico) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
if (v instanceof Hibridos) {
Hibridos aux = new Hibridos();
aux = (Hibridos) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
if (v instanceof Prancha) {
Prancha aux = new Prancha();
aux = (Prancha) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
}
return result;
}
public String procuraMaisBaratoGasolinaDist(Ponto destino,Ponto cliente,double dist){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco) && (v.getLocalizacao().distanciaPonto(cliente)<=dist)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Gasolina) {
Gasolina aux = new Gasolina();
aux = (Gasolina) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
return result;
}
public String procuraMaisBaratoHibridoDist(Ponto destino,Ponto cliente, double dist){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco) && (v.getLocalizacao().distanciaPonto(cliente)<=dist)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Hibridos) {
Hibridos aux = new Hibridos();
aux = (Hibridos) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
return result;
}
public String procuraMaisBaratoEletricoDist(Ponto destino,Ponto cliente,double dist){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco) && (v.getLocalizacao().distanciaPonto(cliente)<=dist)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Eletrico) {
Eletrico aux = new Eletrico();
aux = (Eletrico) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
return result;
}
public String procuraMaisBaratoPranchaDist(Ponto destino,Ponto cliente , double dist){
double preco = 9999999999999999999.99999999999 ;
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
for(Veiculo v : l)
if ((v.getPrecoKm() < preco) && (v.getLocalizacao().distanciaPonto(cliente)<=dist)) {
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Prancha) {
Prancha aux = new Prancha();
aux = (Prancha) v;
if (aux.getAutonomia() > distancia && aux.getCondicao() == true) result = aux.getMatricula();
preco = v.getPrecoKm();
}
}
return result;
}
public String procuraMaisBaratoBicicletaDist(Ponto cliente, double dist ){
// ver melhor solucao para isto
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
double preco = 99999999999999999999.9999999999;
for(Veiculo v : l)
if ((v.getPrecoKm() < preco) && (v instanceof Bicicleta)&& (v.getLocalizacao().distanciaPonto(cliente)<=dist)) {
result = v.getMatricula();
preco = v.getPrecoKm();
}
return result;
}
public String procuraAutonomia(Ponto destino,double autonomia){
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
Iterator it = l.iterator();
while (it.hasNext() && result.equals("")){
Veiculo v = (Veiculo)it.next();
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Gasolina) {
Gasolina aux = new Gasolina();
aux = (Gasolina) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true && aux.getAutonomia()>autonomia) result = aux.getMatricula();
}
if (v instanceof Eletrico) {
Eletrico aux = new Eletrico();
aux = (Eletrico) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true && aux.getAutonomia()>autonomia) result = aux.getMatricula();
}
if (v instanceof Hibridos) {
Hibridos aux = new Hibridos();
aux = (Hibridos) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true && aux.getAutonomia()>autonomia) result = aux.getMatricula();
}
if (v instanceof Prancha) {
Prancha aux = new Prancha();
aux = (Prancha) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true && aux.getAutonomia()>autonomia) result = aux.getMatricula();
}
}
return result;
}
public String procuraAutonomiaGasolina(Ponto destino,double autonomia){
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
Iterator it = l.iterator();
while (it.hasNext() && result.equals("")){
Veiculo v = (Veiculo)it.next();
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Gasolina) {
Gasolina aux = new Gasolina();
aux = (Gasolina) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true && aux.getAutonomia()>autonomia) result = aux.getMatricula();
}
}
return result;
}
public String procuraAutonomiaHibrido(Ponto destino,double autonomia){
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
Iterator it = l.iterator();
while (it.hasNext() && result.equals("")){
Veiculo v = (Veiculo)it.next();
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Hibridos) {
Hibridos aux = new Hibridos();
aux = (Hibridos) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true && aux.getAutonomia()>autonomia) result = aux.getMatricula();
}
}
return result;
}
public String procuraAutonomiaEletrico(Ponto destino,double autonomia){
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
Iterator it = l.iterator();
while (it.hasNext() && result.equals("")){
Veiculo v = (Veiculo)it.next();
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Eletrico) {
Eletrico aux = new Eletrico();
aux = (Eletrico) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true && aux.getAutonomia()>autonomia) result = aux.getMatricula();
}
}
return result;
}
public String procuraAutonomiaPrancha(Ponto destino,double autonomia){
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
Iterator it = l.iterator();
while (it.hasNext() && result.equals("")){
Veiculo v = (Veiculo)it.next();
double distancia = destino.distanciaPonto(v.getLocalizacao());
if (v instanceof Prancha) {
Prancha aux = new Prancha();
aux = (Prancha) v;
if (aux.getAutonomia()>distancia && aux.getCondicao() == true && aux.getAutonomia()>autonomia) result = aux.getMatricula();
}
}
return result;
}
public String procuraAutonomiaBicicleta(Ponto destino){
String result = "";
ArrayList<Veiculo> l = new ArrayList<Veiculo>(this.getVeiculo().values());
Iterator it = l.iterator();
while (it.hasNext() && result.equals("")){
Veiculo v = (Veiculo)it.next();
if (v instanceof Bicicleta) {
Bicicleta aux = new Bicicleta();
aux = (Bicicleta) v;
result = aux.getMatricula();
}
}
return result;
}
// atualiza veiculo apos viagem
public void atualizaVeiculo(String m, Ponto dest){
HashMap<String,Veiculo> gv = new HashMap<String,Veiculo>(this.getVeiculo());
Veiculo v = gv.get(m);
if (v instanceof Bicicleta){
((Bicicleta)v).atualizaB(dest);
};
if (v instanceof Hibridos){
((Hibridos)v).atualizaH(dest);
};
if (v instanceof Gasolina){
((Gasolina)v).atualizaG(dest);
};
if (v instanceof Prancha){
((Prancha)v).atualizaP(dest);
};
if (v instanceof Eletrico){
((Eletrico)v).atualizaE(dest);
}
this.setVeiculo(gv);
}
public void setCombustivel(String matriculaAux){
if (this.veiculos.get(matriculaAux) instanceof Gasolina){
((Gasolina)this.veiculos.get(matriculaAux)).calculaCombustivelG();
}
if (this.veiculos.get(matriculaAux) instanceof Eletrico){
((Eletrico)this.veiculos.get(matriculaAux)).calculaCombustivelE();
}
if (this.veiculos.get(matriculaAux) instanceof Hibridos){
((Hibridos)this.veiculos.get(matriculaAux)).calculaCombustivelH();
}
if (this.veiculos.get(matriculaAux) instanceof Prancha){
((Prancha)this.veiculos.get(matriculaAux)).calculaCombustivelP();
}
}
public void atualizaClassificacaoVeiculo(double c, Veiculo v){
if (this.veiculos.get(v.getMatricula()).getNrClassificacoes() == 0 ) {
this.veiculos.get(v.getMatricula()).setClassificacao(c);
this.veiculos.get(v.getMatricula()).setNrClassificacoes(1);
}
else {
this.veiculos.get(v.getMatricula()).setClassificacao(((c)+ (this.veiculos.get(v.getMatricula()).getClassificacao() * this.veiculos.get(v.getMatricula()).getNrClassificacoes())) / (this.veiculos.get(v.getMatricula()).getNrClassificacoes() +1)) ;
this.veiculos.get(v.getMatricula()).setNrClassificacoes(this.veiculos.get(v.getMatricula()).getNrClassificacoes() + 1);
}
}
}
|
package com.tencent.mm.plugin.appbrand.config;
import com.tencent.mm.plugin.appbrand.config.d.b;
class d$c {
public b fpA;
public d$a fpz;
public String name;
public boolean success;
private d$c(d$a d_a, b bVar, boolean z, String str) {
this.fpz = d_a;
this.fpA = bVar;
this.success = z;
this.name = str;
}
}
|
package com.lingnet.vocs.dao.equipment;
import com.lingnet.common.dao.BaseDao;
import com.lingnet.vocs.entity.EquipmentUsageLog;
public interface EquipmentUsagelogDao extends BaseDao<EquipmentUsageLog, String> {
}
|
/*
* 27 août 2008
*
* Copyright 2008 Exane All rights reserved.
*/
package spi.movieorganizer.display.table.column;
import java.util.MissingResourceException;
import javax.swing.Action;
import javax.swing.Icon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spi.movieorganizer.display.resources.MovieOrganizerStaticResources;
import exane.osgi.jexlib.common.annotation.injector.ResourceInjector;
import exane.osgi.jexlib.common.swing.table.column.AbstractExaneTableColumn;
import exane.osgi.jexlib.common.swing.tools.resources.ImageResourceManager;
import exane.osgi.jexlib.data.object.ExaneDataObject;
import exane.osgi.jexlib.data.object.ExaneDataType;
/**
* @author Tribondeau Brian
* @version 27 août 2008
* @param <K>
* Column type
*/
@SuppressWarnings("unchecked")
public abstract class AbstractMovieOrganizerTableColumn<T, V extends ExaneDataObject> extends AbstractExaneTableColumn<T, V> {
private static final long serialVersionUID = -8913608996797130927L;
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractMovieOrganizerTableColumn.class);
public static final String ID_COLUMN = "TableColumn.";
public static final String COLUMN_NAME = "." + Action.NAME;
public static final String COLUMN_DESCRIPTION = "." + "Description";
public static final String COLUMN_ICON = "." + Action.SMALL_ICON;
public static final String COLUMN_GROUP = "." + "Group";
public static final String GROUP_SEPARATOR_REGEXP = "\\|";
public static final boolean IS_ALWAYS_UPDATE = true;
public AbstractMovieOrganizerTableColumn(final ExaneDataType... changeItems) {
super(changeItems);
}
public String getResourcePath() {
return MovieOrganizerStaticResources.PROPERTIES_TABLES;
}
public abstract ColumnCategory getCategory();
@Override
public String computeId() {
return AbstractMovieOrganizerTableColumn.ID_COLUMN + getCategory().toString() + "." + this.getClass().getSimpleName();
}
@Override
public String[] computeGroup() {
final String searchString = getId() + AbstractMovieOrganizerTableColumn.COLUMN_GROUP;
try {
ResourceInjector.useSilentForNextGet();
final String groupStr = ResourceInjector.getString(getClass(), getResourcePath(), searchString, (String) null);
if (groupStr != null)
return groupStr.split(AbstractMovieOrganizerTableColumn.GROUP_SEPARATOR_REGEXP);
} catch (final MissingResourceException mre) {
AbstractMovieOrganizerTableColumn.LOGGER.error("Unable to load column group from common bundle", mre);
}
return super.getGroup();
}
@Override
public String computeDescription() {
final String searchString = getId() + AbstractMovieOrganizerTableColumn.COLUMN_DESCRIPTION;
try {
final String descStr = ResourceInjector.getString(getClass(), getResourcePath(), searchString, (String) null);
if (descStr != null)
return descStr;
} catch (final MissingResourceException mre) {
AbstractMovieOrganizerTableColumn.LOGGER.error("Unable to load column description from common bundle", mre);
}
return "No description";
}
public Icon getIcon() {
return ImageResourceManager.getEmptyIcon(16, 16);
}
@Override
public boolean isRealTime() {
return true;
}
@Override
public String computeName() {
final String searchString = getId() + AbstractMovieOrganizerTableColumn.COLUMN_NAME;
String nameStr = null;
try {
nameStr = ResourceInjector.getString(getClass(), getResourcePath(), searchString, (String) null);
if (nameStr != null)
return nameStr;
} catch (final MissingResourceException mre) {
AbstractMovieOrganizerTableColumn.LOGGER.error("Unable to load column name from common bundle", mre);
}
return "#Undef";
}
}
|
package com.spbsu.flamestream.runtime.master.acker;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.testkit.TestProbe;
import com.spbsu.flamestream.core.data.meta.EdgeId;
import com.spbsu.flamestream.core.data.meta.GlobalTime;
import com.spbsu.flamestream.runtime.master.acker.api.MinTimeUpdate;
import org.testng.annotations.Test;
import java.util.ArrayList;
import static org.testng.Assert.*;
public class MinTimeUpdaterTest {
@Test
public void testOnShardMinTimeUpdate() {
final ActorSystem system = ActorSystem.apply("test");
final ActorRef shard1 = TestProbe.apply(system).ref(), shard2 = TestProbe.apply(system).ref();
final ArrayList<ActorRef> shards = new ArrayList<>();
shards.add(shard1);
shards.add(shard2);
final MinTimeUpdater minTimeUpdater = new MinTimeUpdater(shards, 0);
final String id = "";
final EdgeId edgeId = new EdgeId("", "");
assertNull(minTimeUpdater.onShardMinTimeUpdate(
shard2,
new MinTimeUpdate(0, new GlobalTime(2, edgeId), new NodeTimes().updated(id, 1))
));
final MinTimeUpdate minTimeUpdate = minTimeUpdater.onShardMinTimeUpdate(
shard1,
new MinTimeUpdate(0, new GlobalTime(1, edgeId), new NodeTimes().updated(id, 3))
);
assertNotNull(minTimeUpdate);
assertEquals(minTimeUpdate.minTime(), new GlobalTime(1, edgeId));
}
}
|
package com.example.dm2.ex20181109_1eval;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import java.util.ArrayList;
public class AltaUsu extends AppCompatActivity {
private EditText textoNombre , textoApellido;
private RadioButton masculino , femenino;
private CheckBox arte , ciencia , otros;
private String sexo="algo";
private ArrayList<String> museo = new ArrayList<String>();
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_altausu );
setTitle( "NUEVO USUARIO" );
textoNombre = (EditText) findViewById ( R.id.nombre );
textoApellido = (EditText) findViewById ( R.id.apellido );
masculino = (RadioButton) findViewById ( R.id.masc );
femenino = (RadioButton) findViewById ( R.id.fem );
arte = (CheckBox) findViewById ( R.id.arte );
ciencia = (CheckBox) findViewById ( R.id.ciencia );
otros = (CheckBox) findViewById ( R.id.otros );
}
public void cancelar( View view ) {
finish();
}
public void alta( View view ) {
sexo = (masculino.isChecked() ) ?"Masculino":"Femenino";
if( arte.isChecked() ){
museo.add(arte.getText().toString() );
}
if( ciencia.isChecked() ){
museo.add( ciencia.getText().toString());
}
if( otros.isChecked() ){
museo.add( otros.getText().toString());
}
Intent verDatos = new Intent( this, VerDatos.class );
verDatos.putExtra("nombre" , textoNombre.getText().toString() );
verDatos.putExtra("apellido" , textoApellido.getText().toString() );
verDatos.putExtra("sexo" , sexo );
verDatos.putExtra("museos" , museo);
startActivity( verDatos );
}
public EditText getTextoNombre() {
return textoNombre;
}
public void setTextoNombre( EditText textoNombre ) {
this.textoNombre = textoNombre;
}
public EditText getTextoApellido() {
return textoApellido;
}
public void setTextoApellido( EditText textoApellido ) {
this.textoApellido = textoApellido;
}
public RadioButton getMasculino() {
return masculino;
}
public void setMasculino( RadioButton masculino ) {
this.masculino = masculino;
}
public RadioButton getFemenino() {
return femenino;
}
public void setFemenino( RadioButton femenino ) {
this.femenino = femenino;
}
public CheckBox getArte() {
return arte;
}
public void setArte( CheckBox arte ) {
this.arte = arte;
}
public CheckBox getCiencia() {
return ciencia;
}
public void setCiencia( CheckBox ciencia ) {
this.ciencia = ciencia;
}
public CheckBox getOtros() {
return otros;
}
public void setOtros( CheckBox otros ) {
this.otros = otros;
}
}
|
package exception;
public class MyDataException extends Exception {
public MyDataException(String string) {
// TODO Auto-generated constructor stub
}
}
|
package kr.ds.custom;
import kr.ds.mylotto.R;
import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;
public class LottoPrice extends LinearLayout{
private Context mContext;
private int Row = 5;
private int Col = 3;
private final int NUM = 0;//등
private final int PRICE = 1;//가격
private final int PERSON = 2;//인원
private final int PERSONPRICE = 3;//인당 가격
private LinearLayout mTotalLinearLayout;
private LinearLayout mLinearLayout[] = new LinearLayout[Row];
private LinearLayout mSubLinearLayout[] = new LinearLayout[Col];
private TextView mTextView[] = new TextView[Col];
public LottoPrice(Context context) {
super(context);
mContext = context;
// TODO Auto-generated constructor stub
}
public LinearLayout init(String data1,String data2,String data3,String data4,String data5){
mTotalLinearLayout = new LinearLayout(mContext);
mTotalLinearLayout.setOrientation(VERTICAL);
for(int i=0; i< Row; i++){
String mData = "";
if(i == 0){
mData = data1;
}else if(i == 1){
mData = data2;
}else if(i == 2){
mData = data3;
}else if(i == 3){
mData = data4;
}else if(i == 4){
mData = data5;
}
mLinearLayout[i] = new LinearLayout(mContext);
if(i== 0){
mLinearLayout[i].setBackgroundResource(R.color.colorPrimary);
}else{
mLinearLayout[i].setBackgroundResource(R.color.white);
}
mLinearLayout[i].setOrientation(HORIZONTAL);
for(int j=0; j<Col; j++){
mSubLinearLayout[j] = new LinearLayout(mContext);
mSubLinearLayout[j].setOrientation(HORIZONTAL);
mTextView[j] = new TextView(mContext);
mTextView[j].setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f);
if(i == 0){
mTextView[j].setTextColor(0xffffffff);
}else{
mTextView[j].setTextColor(0xffff0000);
}
if(j == 0){
mTextView[j].setText(getPrice(mData, NUM));
mTextView[j].setPadding(0, dipToInt(2), 0, dipToInt(2));
mSubLinearLayout[j].setGravity(Gravity.CENTER);
mSubLinearLayout[j].setLayoutParams(getLayoutParamsWeight(0.1f));
}else if(j == 1){
mTextView[j].setText(getPrice(mData, PERSON));
mTextView[j].setSingleLine();
mTextView[j].setPadding(0, dipToInt(2), 0, dipToInt(2));
mSubLinearLayout[j].setGravity(Gravity.RIGHT);
mSubLinearLayout[j].setLayoutParams(getLayoutParamsWeight(0.5f));
}else if(j == 2){
mTextView[j].setText(getPrice(mData, PERSONPRICE));
mTextView[j].setSingleLine();
mTextView[j].setPadding(0, dipToInt(2), dipToInt(2), dipToInt(2));
mSubLinearLayout[j].setGravity(Gravity.RIGHT);
mSubLinearLayout[j].setLayoutParams(getLayoutParamsWeight(0.4f));
}
mSubLinearLayout[j].addView(mTextView[j]);
mLinearLayout[i].addView(mSubLinearLayout[j]);
}
mTotalLinearLayout.addView(mLinearLayout[i]);
}
return mTotalLinearLayout;
}
public String getPrice(String data, int type){//번호, 데이터, 구분
String str = "";
String[] mData = data.split("\\|");//특수문자\\삽입해야함
if(type == NUM){//번호
str = mData[type];
}else if(type == PRICE){//금액
str = mData[type];
}else if(type == PERSON){//인원
if(mData.length == 6){
str = mData[type]+"명 ( "+mData[5]+ ")";
}else{
str = mData[type]+"명";
}
}else if(type == PERSONPRICE){
str = mData[type];
}
return str;
}
public LinearLayout.LayoutParams getLayoutParamsWeight(Float weight) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
0, LayoutParams.WRAP_CONTENT, weight);
return params;
}
public int dipToInt(int number) {
int num = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
number, getResources().getDisplayMetrics());
return num;
}
public int spToInt(int number) {
int num = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
number, mContext.getResources().getDisplayMetrics());
return num;
}
}
|
package br.com.scd.demo.session;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
import br.com.scd.demo.enums.TopicResultEnum;
import br.com.scd.demo.enums.VoteEnum;
import br.com.scd.demo.vote.VoteEntity;
public class SessionEntityTest {
@Test
public void shouldGetEndDate() {
LocalDateTime now = LocalDateTime.now();
SessionEntity sessionEntity = new SessionEntity();
ReflectionTestUtils.setField(sessionEntity, "dateAdded", now);
sessionEntity.setDurationInMinutes(10);
assertThat(sessionEntity.getEndDate()).isEqualTo(now.plusMinutes(10));
}
@Test
public void shouldGetIsClosedTrue() {
LocalDateTime now = LocalDateTime.now();
SessionEntity sessionEntity = new SessionEntity();
ReflectionTestUtils.setField(sessionEntity, "dateAdded", now.minusMinutes(5));
sessionEntity.setDurationInMinutes(2);
assertTrue(sessionEntity.isClosed());
}
@Test
public void shouldGetIsClosedFalse() {
LocalDateTime now = LocalDateTime.now();
SessionEntity sessionEntity = new SessionEntity();
ReflectionTestUtils.setField(sessionEntity, "dateAdded", now);
sessionEntity.setDurationInMinutes(1);
assertFalse(sessionEntity.isClosed());
}
@Test
public void shouldGetTotalVotes() {
SessionEntity sessionEntity = new SessionEntity();
VoteEntity voteX = new VoteEntity();
voteX.setVote(VoteEnum.SIM);
VoteEntity voteY = new VoteEntity();
voteY.setVote(VoteEnum.SIM);
VoteEntity voteZ = new VoteEntity();
voteZ.setVote(VoteEnum.NAO);
ReflectionTestUtils.setField(sessionEntity, "votes", Arrays.asList(voteX, voteY, voteZ));
Map<VoteEnum, Long> totalVotesExpected = new HashMap<>();
totalVotesExpected.put(VoteEnum.NAO, 1l);
totalVotesExpected.put(VoteEnum.SIM, 2l);
assertThat(sessionEntity.getTotalVotes()).isEqualToComparingFieldByFieldRecursively(totalVotesExpected);
}
@Test
public void shouldGetSessionResultNenhumVoto() {
assertThat(new SessionEntity().getSessionResult()).isEqualTo(TopicResultEnum.NENHUM_VOTO);
}
@Test
public void shouldGetSessionResultEmpate() {
SessionEntity sessionEntity = new SessionEntity();
VoteEntity voteX = new VoteEntity();
voteX.setVote(VoteEnum.SIM);
VoteEntity voteZ = new VoteEntity();
voteZ.setVote(VoteEnum.NAO);
ReflectionTestUtils.setField(sessionEntity, "votes", Arrays.asList(voteX, voteZ));
assertThat(sessionEntity.getSessionResult()).isEqualTo(TopicResultEnum.EMPATE);
}
@Test
public void shouldGetSessionResultAprovada() {
SessionEntity sessionEntity = new SessionEntity();
VoteEntity voteX = new VoteEntity();
voteX.setVote(VoteEnum.SIM);
ReflectionTestUtils.setField(sessionEntity, "votes", Arrays.asList(voteX));
assertThat(sessionEntity.getSessionResult()).isEqualTo(TopicResultEnum.APROVADA);
}
@Test
public void shouldGetSessionResultReprovada() {
SessionEntity sessionEntity = new SessionEntity();
VoteEntity voteX = new VoteEntity();
voteX.setVote(VoteEnum.NAO);
ReflectionTestUtils.setField(sessionEntity, "votes", Arrays.asList(voteX));
assertThat(sessionEntity.getSessionResult()).isEqualTo(TopicResultEnum.REPROVADA);
}
}
|
package com.example.group.adapter;
import java.util.ArrayList;
import com.example.group.R;
import com.example.group.bean.GoodsInfo;
import com.example.group.widget.RecyclerExtras.OnItemClickListener;
import com.example.group.widget.RecyclerExtras.OnItemLongClickListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("DefaultLocale")
public class RecyclerLinearAdapter extends RecyclerView.Adapter<ViewHolder> implements
OnItemClickListener, OnItemLongClickListener {
private final static String TAG = "RecyclerLinearAdapter";
private Context mContext; // 声明一个上下文对象
private ArrayList<GoodsInfo> mPublicArray;
public RecyclerLinearAdapter(Context context, ArrayList<GoodsInfo> publicArray) {
mContext = context;
mPublicArray = publicArray;
}
// 获取列表项的个数
public int getItemCount() {
return mPublicArray.size();
}
// 创建列表项的视图持有者
public ViewHolder onCreateViewHolder(ViewGroup vg, int viewType) {
// 根据布局文件item_linear.xml生成视图对象
View v = LayoutInflater.from(mContext).inflate(R.layout.item_linear, vg, false);
return new ItemHolder(v);
}
// 绑定列表项的视图持有者
public void onBindViewHolder(ViewHolder vh, final int position) {
ItemHolder holder = (ItemHolder) vh;
holder.iv_pic.setImageResource(mPublicArray.get(position).pic_id);
holder.tv_title.setText(mPublicArray.get(position).title);
holder.tv_desc.setText(mPublicArray.get(position).desc);
// 列表项的点击事件需要自己实现
holder.ll_item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v, position);
}
}
});
// 列表项的长按事件需要自己实现
holder.ll_item.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mOnItemLongClickListener != null) {
mOnItemLongClickListener.onItemLongClick(v, position);
}
return true;
}
});
}
// 获取列表项的类型
public int getItemViewType(int position) {
// 这里返回每项的类型,开发者可自定义头部类型与一般类型,
// 然后在onCreateViewHolder方法中根据类型加载不同的布局,从而实现带头部的网格布局
return 0;
}
// 获取列表项的编号
public long getItemId(int position) {
return position;
}
// 定义列表项的视图持有者
public class ItemHolder extends RecyclerView.ViewHolder {
public LinearLayout ll_item; // 声明列表项的线性布局
public ImageView iv_pic; // 声明列表项图标的图像视图
public TextView tv_title; // 声明列表项标题的文本视图
public TextView tv_desc; // 声明列表项描述的文本视图
public ItemHolder(View v) {
super(v);
ll_item = v.findViewById(R.id.ll_item);
iv_pic = v.findViewById(R.id.iv_pic);
tv_title = v.findViewById(R.id.tv_title);
tv_desc = v.findViewById(R.id.tv_desc);
}
}
// 声明列表项的点击监听器对象
private OnItemClickListener mOnItemClickListener;
public void setOnItemClickListener(OnItemClickListener listener) {
this.mOnItemClickListener = listener;
}
// 声明列表项的长按监听器对象
private OnItemLongClickListener mOnItemLongClickListener;
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
this.mOnItemLongClickListener = listener;
}
// 处理列表项的点击事件
public void onItemClick(View view, int position) {
String desc = String.format("您点击了第%d项,标题是%s", position + 1,
mPublicArray.get(position).title);
Toast.makeText(mContext, desc, Toast.LENGTH_SHORT).show();
}
// 处理列表项的长按事件
public void onItemLongClick(View view, int position) {
String desc = String.format("您长按了第%d项,标题是%s", position + 1,
mPublicArray.get(position).title);
Toast.makeText(mContext, desc, Toast.LENGTH_SHORT).show();
}
}
|
package com.butyter.contact;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.butyter.contact.core.db.dao.ContactDAO;
import io.swagger.client.ApiClient;
import io.swagger.client.ApiException;
import io.swagger.client.api.ContactsApi;
import io.swagger.client.model.ContactDTO;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ApplicationConfig.class })
@WebAppConfiguration
public class ContactSwaggerTest {
private static final String BASE_TARGET = "http://localhost:9000";
private static ContactsApi contactApi;
private static int startContactListSize;
private static ContactDTO contact;
@Autowired
private ContactDAO contactDAO;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ApiClient client = new ApiClient();
client.setBasePath(BASE_TARGET);
contactApi = new ContactsApi(client);
contact = new ContactDTO();
contact.setId(0);
contact.setFirstName("TestFirstName");
contact.setLastName("TestLastName");
contact.setPhone("067-7777777");
}
@Test
public void test01GetContactList() throws ApiException {
contactDAO.deleteContact(6);
List<ContactDTO> contacts = contactApi.getAllContacts();
// assertEquals(Response.Status.OK.getStatusCode(),
// response.getStatus());
startContactListSize = contacts.size();
assertTrue(startContactListSize > 0);
}
@Test
public void test02CreateContact() throws ApiException {
List<String> location = contactApi.createContactWithHttpInfo(contact).getHeaders().get("Location");
contact.setId(Integer.parseInt(location.get(0).substring(location.get(0).lastIndexOf('/') + 1)));
// Response response =
// client.target(BASE_TARGET).request(MediaType.APPLICATION_JSON)
// .post(Entity.entity(contact, MediaType.APPLICATION_JSON));
// assertEquals(Response.Status.CREATED.getStatusCode(),
// response.getStatus());
// contact.setId(Integer.parseInt(
// response.getLocation().getPath().substring(response.getLocation().getPath().lastIndexOf('/')
// + 1)));
assertEquals(startContactListSize + 1, getContactsSize());
}
@Test
public void test03UpdateContact() throws ApiException {
contact.setFirstName("newFirstName");
// Response response =
// client.target(BASE_TARGET).path(String.valueOf(contact.getId()))
// .request(MediaType.APPLICATION_JSON).put(Entity.entity(contact,
// MediaType.APPLICATION_JSON));
// assertEquals(Response.Status.OK.getStatusCode(),
// response.getStatus());
assertTrue(contact.equals(contactApi.updateContact(contact.getId(), contact)));
}
@Test
public void test04GetContactById() throws ApiException {
// Response response =
// client.target(BASE_TARGET).path(String.valueOf(contact.getId()))
// .request(MediaType.APPLICATION_JSON).get();
// assertEquals(Response.Status.OK.getStatusCode(),
// response.getStatus());
assertTrue(contact.equals(contactApi.getContactById(contact.getId())));
}
@Test
public void test05DeleteContact() throws ApiException {
// Response response =
// client.target(BASE_TARGET).path(String.valueOf(contact.getId())).request().delete();
// assertEquals(Response.Status.NO_CONTENT.getStatusCode(),
// response.getStatus());
contactApi.deleteContact(contact.getId());
assertEquals(startContactListSize, getContactsSize());
}
private int getContactsSize() throws ApiException {
return contactApi.getAllContacts().size();
}
}
|
//package second;
//
//import java.util.Scanner;
//
//public class Employee {
// public int add(int x, int y){
// return x+y;
// }
// public static void main(String[] args) {
// Department d= new Department(1,"ME");
// d.details();
// Scanner scan = new Scanner(System.in);
// System.out.print("Enter value : ");
// int a=scan.nextInt();
// System.out.print("Enter value : ");
// int b=scan.nextInt();
// Employee e =new Employee();
// System.out.println(e.add(a,b));
//// System.out.print("Enter string : ");
//// String s=scan.nextLine();
//// System.out.println("Entered string is "+s);
// }
//}
|
package asu.shell.sh.commands;
import static asu.shell.sh.util.EnvManager.ASU_SHELL_PAGE;
import asu.shell.sh.History;
import asu.shell.sh.Jobs;
import asu.shell.sh.PagedPrintStream;
import asu.shell.sh.util.Util;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public abstract class Command {
private InputStream in = null;
private PrintStream out = null;
private PrintStream err = null;
private boolean redirectIn = false;
private boolean redirectOut = false;
private final ThreadLocal<Map> context = new ThreadLocal();
public Command() {
this.context.set(new HashMap());
}
private Map getContext() {
Map m = (Map) this.context.get();
if (m == null) {
m = new HashMap();
this.context.set(m);
}
return m;
}
public void addContext(String key, Object value) {
getContext().put(key, value);
}
public void addContext(Map map) {
getContext().putAll(map);
}
public Object getContextValue(String key) {
return getContext().get(key);
}
public abstract void execute(String... paramVarArgs)
throws Exception;
public void executeBg(String... paramArrayOfString)
throws Exception {
execute(paramArrayOfString);
}
public void usage() {
out().println("help not available for " + rmPackName(getClass().getName()));
}
protected final InputStream in() {
if (this.in == null) {
this.in = System.in;
}
return this.in;
}
protected final PrintStream out() {
if (this.out == null) {
this.out = System.out;
if (System.getProperty(ASU_SHELL_PAGE).equals("true")) {
this.out = new PagedPrintStream(this.out);
}
}
return this.out;
}
protected final PrintStream err() {
if (this.err == null) {
this.err = System.err;
if (System.getProperty(ASU_SHELL_PAGE).equals("true")) {
this.err = new PagedPrintStream(this.err);
}
}
return this.err;
}
protected void checkForInterruption()
throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
public static Properties properties() {
return System.getProperties();
}
public static String property(String paramString) {
return System.getProperty(paramString);
}
public static void property(String paramString1, String paramString2) {
System.getProperties().put(paramString1, paramString2);
}
public static void removeProperty(String paramString) {
System.getProperties().remove(paramString);
}
public final void finish() {
closeIn();
closeOut();
closeErr();
}
public static void connectOutputToInput(Command paramObject1, Command paramObject2)
throws IOException {
PipedOutputStream localPipedOutputStream = new PipedOutputStream();
PipedInputStream localPipedInputStream = new PipedInputStream(localPipedOutputStream);
paramObject1.out = new PrintStream(localPipedOutputStream);
paramObject1.redirectOut = true;
paramObject2.in = localPipedInputStream;
paramObject2.redirectIn = true;
}
protected void printHistory(int n) {
History.getInstance().printLast(n, out());
}
protected void printJobs() {
Jobs.getInstance().print(out());
}
protected void killJobs(int[] paramArrayOfInt) {
Jobs.getInstance().kill(paramArrayOfInt);
}
protected boolean isFlag(String paramString) {
return paramString.charAt(0) == Util.systemProperty("asu.shell.flag").charAt(0);
}
protected String flag(String paramString) {
return Util.systemProperty("asu.shell.flag") + paramString;
}
private void closeIn() {
if (this.in != null) {
try {
if (this.redirectIn) {
this.in.close();
}
} catch (IOException localIOException) {
}
}
}
private void closeOut() {
if (this.out != null) {
this.out.flush();
if (this.redirectOut) {
this.out.close();
}
}
}
private void closeErr() {
if (this.err != null) {
this.err.flush();
}
}
private String rmPackName(String paramString) {
int i = paramString.lastIndexOf(".");
return i < 0 ? paramString : paramString.substring(i + 1);
}
}
|
/*
* Copyright 2018 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 com.siemens.mp.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import javax.microedition.util.ContextHolder;
import ru.playsoftware.j2meloader.util.FileUtils;
public class File {
public static final int INSIDE_STORAGE_PATH = 1;
public static final int OUTSIDE_STORAGE_PATH = 0;
public static final String STORAGE_DRIVE = "a:";
private final static String ROOT_SEP_STR = ":/";
private FileInputStream inputStream;
private FileOutputStream outputStream;
public int close(int fileDescriptor) throws IOException {
if (inputStream != null && outputStream != null) {
inputStream.close();
outputStream.close();
return 1;
} else {
return -1;
}
}
public static int copy(String source, String dest) throws IOException {
FileUtils.copyFileUsingChannel(getFile(source), getFile(dest));
return 1;
}
public static int debugWrite(String fileName, String infoString) throws IOException {
FileWriter writer = new FileWriter(getFile(fileName), true);
writer.append(infoString).close();
return 1;
}
public static int delete(String fileName) {
if (getFile(fileName).delete()) {
return 1;
} else {
return -1;
}
}
public static int exists(String fileName) throws IOException {
java.io.File file = getFile(fileName);
if (file.exists()) {
return 1;
} else {
return -1;
}
}
public static boolean getIsHidden(String fileName) throws IOException {
java.io.File file = getFile(fileName);
return file.isHidden();
}
public static long getLastModified(String fileName) throws IOException {
java.io.File file = getFile(fileName);
return file.lastModified();
}
public static boolean isDirectory(String fileName) throws IOException {
java.io.File file = getFile(fileName);
return file.isDirectory();
}
public int length(int fileDescriptor) throws IOException {
return inputStream.available();
}
public static String[] list(String pathName) throws IOException {
return list(pathName, false);
}
public static String[] list(String pathName, boolean includeHidden) throws IOException {
java.io.File[] files = getFile(pathName).listFiles();
Arrays.sort(files);
ArrayList<String> list = new ArrayList<>();
for (java.io.File file : files) {
if (!includeHidden || !file.isHidden()) {
list.add(file.getName());
}
}
return list.toArray(new String[0]);
}
public int open(String fileName) throws IOException {
java.io.File file = getFile(fileName);
if (!file.exists()) {
file.createNewFile();
}
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file);
return 1;
}
public int read(int fileDescriptor, byte[] buf, int offset, int numBytes) throws IOException {
return inputStream.read(buf, offset, numBytes);
}
public static int rename(String source, String dest) {
if (getFile(source).renameTo(getFile(dest))) {
return 1;
} else {
return -1;
}
}
public int write(int fileDescriptor, byte[] buf, int offset, int numBytes) throws IOException {
outputStream.write(buf, offset, numBytes);
return 1;
}
private static java.io.File getFile(String fileName) {
if (!fileName.contains(":/")) {
return ContextHolder.getFileByName(fileName);
} else {
fileName = fileName.replace(OUTSIDE_STORAGE_PATH + ROOT_SEP_STR, "");
return new java.io.File(System.getProperty("user.home"), fileName);
}
}
}
|
package mw.albumpodrozniczy;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.annotation.DrawableRes;
import android.view.View;
import android.widget.ImageView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.File;
import java.io.FileFilter;
import java.util.regex.Pattern;
/**
* Created by mstowska on 4/11/2016.
*/
public class LadowanieZdjecDoMarkera extends AsyncTask<String, Void, MarkerOptions[]> {
private ImageView mMarkerImageView;
private int pozycja;
private Context context;
private View mCustomMarkerView;
private GoogleMap googleMap;
private double[] tablicaSzerokosciAlbumow;
private double[] tablicaDlugosciAlbumow;
private boolean trybaEdycja;
private String sciezkaDoZdjecia;
private DatabaseAdapter databaseAdapter;
public LadowanieZdjecDoMarkera(Context context, int pozycja, View mCustomMarkerView, ImageView mMarkerImageView, GoogleMap googleMap, boolean trybEdycja) {
this.pozycja = pozycja;
this.mMarkerImageView = mMarkerImageView;
this.context = context;
this.mCustomMarkerView = mCustomMarkerView;
this.googleMap = googleMap;
this.trybaEdycja = trybEdycja;
}
@Override
protected void onPreExecute() {
databaseAdapter = new DatabaseAdapter(context);
databaseAdapter.open();
tablicaSzerokosciAlbumow = databaseAdapter.pobranieTablicyWszystkichWspolrzedneAlbumu(pozycja, "szerokosc");
tablicaDlugosciAlbumow = databaseAdapter.pobranieTablicyWszystkichWspolrzedneAlbumu(pozycja, "dlugosc");
}
@Override
protected MarkerOptions[] doInBackground(String... nazwaMarkera) {
MarkerOptions[] opcjeMarkerow = new MarkerOptions[nazwaMarkera.length];
for(int i=0; i<nazwaMarkera.length; i++) {
LatLng wspolrzedne = new LatLng(tablicaSzerokosciAlbumow[i], tablicaDlugosciAlbumow[i]);
sciezkaDoZdjecia = getFirstPhotoInAlbum(nazwaMarkera[i]);
if(trybaEdycja == true) {
opcjeMarkerow[i] = new MarkerOptions().alpha(70).position(wspolrzedne).draggable(true).icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(mCustomMarkerView, mMarkerImageView, R.drawable.folder_multiple_image, sciezkaDoZdjecia))).title("Zobacz tylko te zdjęcia");
}
else {
opcjeMarkerow[i] = new MarkerOptions().alpha(70).position(wspolrzedne).draggable(false).icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(mCustomMarkerView, mMarkerImageView, R.drawable.folder_multiple_image, sciezkaDoZdjecia))).title("Zobacz tylko te zdjęcia");
}
}
return opcjeMarkerow;
}
@Override
protected void onPostExecute(MarkerOptions[] opcjeMarkerow) {
for(int i=0; i<opcjeMarkerow.length; i++){
googleMap.addMarker(opcjeMarkerow[i]);
}
databaseAdapter.close();
}
private int obliczanieOptymalnegoRozmiaruZdjecia(BitmapFactory.Options opcje, int maxSzerokosc,int maxWysokosc ) {
int wysokosc = opcje.outHeight;
int szerokosc = opcje.outWidth;
int wspolczynnik = 1;
if (wysokosc > maxWysokosc || szerokosc > maxSzerokosc) {
int polowaWysokosci = wysokosc / 2;
int polowaSzerokosci = szerokosc / 2;
while ((polowaWysokosci / wspolczynnik) > maxWysokosc
&& (polowaSzerokosci / wspolczynnik) > maxSzerokosc) {
wspolczynnik *= 2;
}
}
return wspolczynnik;
}
private Bitmap dekodowanieBitmapy(String sciezkaDoZdjecia, int maxSzerokosc,int maxWysokosc) {
BitmapFactory.Options opcje = new BitmapFactory.Options();
opcje.inJustDecodeBounds = true;
BitmapFactory.decodeFile(sciezkaDoZdjecia, opcje);
opcje.inSampleSize = obliczanieOptymalnegoRozmiaruZdjecia(opcje, maxSzerokosc,maxWysokosc);
opcje.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(sciezkaDoZdjecia, opcje);
}
public String getFirstPhotoInAlbum(String marker) {
String sciezkaDoZdjecia = "";
String nazwaPodrozy = databaseAdapter.pobranieWartosciZTabeli(databaseAdapter.DB_TABLE_MAIN, DatabaseAdapter.KEY_TITLE, (int) pozycja);
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "Album podróżniczy" + File.separator+ nazwaPodrozy);
if (file.isDirectory()) {
// listFile = file.listFiles();
final Pattern regex = Pattern.compile(marker + ".*");
File[] flists = file.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return regex.matcher(file.getName()).matches();
}
});
if(flists.length>0) {
sciezkaDoZdjecia = flists[0].getAbsolutePath();
}
}
return sciezkaDoZdjecia;
}
private Bitmap getMarkerBitmapFromView(View view, ImageView mMarkerImageView, @DrawableRes int resId, String nazwaAlbumu) {
//View customMarkerView = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.element_marker, null);
// ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.miniaturka_marker);
if(nazwaAlbumu!="") {
Bitmap bitmap = dekodowanieBitmapy(sciezkaDoZdjecia, 40, 40);
//Bitmap bitmap = BitmapFactory.decodeFile(sciezkaDoZdjecia);
//
try {
ExifInterface exif = new ExifInterface(sciezkaDoZdjecia);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
//Bitmap bitmap = BitmapFactory.decodeFile(sciezka[obecneZdjecie]);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); // rotating bitmap
mMarkerImageView.setImageBitmap(bitmap);
mMarkerImageView.setMaxWidth(60);
mMarkerImageView.setMaxHeight(60);
mMarkerImageView.setMinimumWidth(57);
mMarkerImageView.setMinimumHeight(57);
// markerImageView.setImageBitmap(bitmap);
// Toast.makeText(context, "bitmapa wgrana", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {}
}
// markerImageView.setImageResource(R.drawable.folder_multiple_image);
// markerImageView.setImageResource(context.getResources().getIdentifier("folder_multiple_image", "drawable", context.getPackageName()));
//markerImageView.setImageResource(context.getResources().getIdentifier("folder_multiple_image", "drawable", context.getPackageName()));
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = view.getBackground();
if (drawable != null)
drawable.draw(canvas);
view.draw(canvas);
return returnedBitmap;
}
}
|
package com.keeptrack.domain.entity.base;
import javax.persistence.Column;
import javax.persistence.Transient;
public abstract class ResourceEntity extends BaseEntity {
/**
*
*/
@Transient
private static final long serialVersionUID = 201603271155L;
/**
* deprecated temporally
*/
@Column(name="name", nullable=false, length=100)
private String name;
@Column(name="name", nullable=false, length=100)
private String resourceType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ResourceEntity other = (ResourceEntity) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (resourceType == null) {
if (other.resourceType != null)
return false;
} else if (!resourceType.equals(other.resourceType))
return false;
return true;
}
}
|
package penowl.plugin.migs;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.UUID;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Barrel;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.Plugin;
@SuppressWarnings("unused")
public class InvManagement {
public static String $migs = ChatColor.GREEN + "[MIGS] " + ChatColor.RESET;
private static Plugin plugin;
@SuppressWarnings("static-access")
public InvManagement(Plugin plugin)
{
this.plugin = plugin;
}
public static ItemStack mmai(Material type, int amount, short dmg, String name) {
ItemStack item = new ItemStack(type, amount);
setName(item,name);
return item;
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public static ItemStack setName(ItemStack items, String name){
ItemMeta meta = items.getItemMeta();
meta.setDisplayName(name);
items.setItemMeta(meta);
return items;
}
public static Inventory createOwnerInventory(World ilw, int ilx, int ily, int ilz) {
DecimalFormat df = new DecimalFormat("#0.00");
String configloc = "shops."+String.valueOf(ilw)+"."+String.valueOf(ilx)+"."+String.valueOf(ily)+"."+String.valueOf(ilz);
Inventory temp = Bukkit.createInventory(new FakeHolder(new Location(ilw,ilx,ily,ilz), "Owner Interface"), 45, "Owner Interface");
for(int x = 0; x < 45; x = x + 1) {
ItemStack blank = setName(new ItemStack(Material.BLACK_STAINED_GLASS_PANE, 1)," ");
temp.setItem(x, blank);
}
temp.setItem(2, ifbook("Prices","To change prices by major amounts,","left-click.","To change prices by minor amounts,","shift-click."));
temp.setItem(28, mmai(Material.HOPPER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price adjust: " + ChatColor.RESET + "-1"));
temp.setItem(15, ifbook("Buy/Sell","A buy shop will let players buy","the first item in the chest from you.", "A sell shop will let players sell","their items until the chest is full."));
temp.setItem(29, mmai(Material.HOPPER, 10, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price adjust: " + ChatColor.RESET + "-10"));
temp.setItem(30, mmai(Material.HOPPER, 50, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price adjust: " + ChatColor.RESET + "-50"));
temp.setItem(10, mmai(Material.GUNPOWDER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price adjust: " + ChatColor.RESET + "+1"));
temp.setItem(11, mmai(Material.GUNPOWDER, 10, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price adjust: " + ChatColor.RESET + "+10"));
temp.setItem(12, mmai(Material.GUNPOWDER, 50, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price adjust: " + ChatColor.RESET + "+50"));
temp.setItem(20, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price: " + df.format(plugin.getConfig().getDouble(configloc+".price"))));
temp.setItem(24, sbwool(plugin.getConfig().getBoolean(configloc+".buy")));
// temp.setItem(5, mmai(Material.WEB, 1, (short) 0, ChatColor.RESET + "Filter?"));
// temp.setItem(14, tfwool(plugin.getConfig().getBoolean(configloc+".filter")));
return temp;
}
public static ItemStack setOwner(OfflinePlayer name) {
ItemStack skull = new ItemStack(Material.PLAYER_HEAD, 1);
SkullMeta meta = (SkullMeta) skull.getItemMeta();
meta.setOwningPlayer(name);
meta.setDisplayName(ChatColor.GREEN + "Owner: " + ChatColor.RESET + "" + name.getName());
skull.setItemMeta(meta);
return skull;
}
@SuppressWarnings("deprecation")
public static OfflinePlayer getName(String configloc) {
if (plugin.getConfig().getString(configloc+".owner").length() > 16) {
UUID kl = UUID.fromString(plugin.getConfig().getString(configloc+".owner"));
OfflinePlayer player = Bukkit.getOfflinePlayer(kl);
return player;
} else {
return Bukkit.getOfflinePlayer("Admin");
}
}
public static ItemStack head(String codc) {
return setOwner(getName(codc));
}
public static ItemStack fetchCurItem(Location loc) {
Block b = loc.getBlock();
ItemStack base = null;
if (b.getState() instanceof Chest) {
Inventory cinv;
if (loc.getBlock().getState() instanceof Barrel) {
Barrel chdata = (Barrel) loc.getBlock().getState();
cinv = chdata.getInventory();
} else {
Chest chdata = (Chest) loc.getBlock().getState();
cinv = chdata.getBlockInventory();
}
String name = null;
ItemStack c = null;
for (int scan = 0; scan < 27; scan++) {
if ((cinv.getItem(scan) == null || c != null)) {
} else {
c = cinv.getItem(scan);
}
}
ItemStack[] inv = cinv.getContents();
int count = 0;
for(int i = 0; i < inv.length; i++) {
if(inv[i] != null){
if(inv[i].isSimilar(c)) {
int temp = inv[i].getAmount();
count= count + temp;
}
}
}
if (c != null) {
base = cinv.getItem(cinv.first(c)).clone();
base.setAmount(count);
} else {
base = mmai(Material.BARRIER,1,(short) 0,"Out of stock");
}
}
if (b.getState() instanceof Barrel) {
Barrel cht = (Barrel) b.getState();
Inventory cinv = cht.getInventory();
String name = null;
ItemStack c = null;
for (int scan = 0; scan < 27; scan++) {
if ((cinv.getItem(scan) == null || c != null)) {
} else {
c = cinv.getItem(scan);
}
}
ItemStack[] inv = cinv.getContents();
int count = 0;
for(int i = 0; i < inv.length; i++) {
if(inv[i] != null){
if(inv[i].isSimilar(c)) {
int temp = inv[i].getAmount();
count= count + temp;
}
}
}
if (c != null) {
base = cinv.getItem(cinv.first(c)).clone();
base.setAmount(count);
} else {
base = mmai(Material.BARRIER,1,(short) 0,"Out of stock");
}
}
return base;
}
public static ItemStack fetchCurItemp(Player p) {
ItemStack base = null;
Inventory cinv = p.getInventory();
String name = null;
ItemStack c = null;
for (int scan = 0; scan < 36; scan++) {
if ((cinv.getItem(scan) == null || c != null)) {
} else {
c = cinv.getItem(scan);
}
}
return base;
}
public static ItemStack taa(ItemStack is, int amount) {
ItemStack kg = is.clone();
kg.setAmount(amount);
return kg;
}
public static Inventory createCustomerInventory(World ilw, int ilx, int ily, int ilz) {
DecimalFormat df = new DecimalFormat("#0.00");
String configloc = "shops."+String.valueOf(ilw)+"."+String.valueOf(ilx)+"."+String.valueOf(ily)+"."+String.valueOf(ilz);
Inventory temp = Bukkit.createInventory(new FakeHolder(new Location(ilw,ilx,ily,ilz), "Customer Interface"), 18, "Customer Interface");
for(int x = 0; x < 18; x = x + 1) {
ItemStack blank = setName(new ItemStack(Material.YELLOW_STAINED_GLASS_PANE, 1),"BUY");
temp.setItem(x, blank);
}
Location chestloc = new Location(Bukkit.getWorld(plugin.getConfig().getString(configloc + ".chestw")), plugin.getConfig().getInt(configloc + ".chestx"), plugin.getConfig().getInt(configloc + ".chesty"), plugin.getConfig().getInt(configloc + ".chestz"));
ItemStack selling = fetchCurItem(chestloc);
if (selling.getAmount()>7) {
temp.setItem(4, taa(selling, 8));
}
if (selling.getAmount()>63) {
temp.setItem(5, taa(selling, 64));
}
temp.setItem(3, taa(selling, 1));
temp.setItem(0, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price: " + df.format(plugin.getConfig().getDouble(configloc + ".price"))));
temp.setItem(12, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price: " + df.format(plugin.getConfig().getDouble(configloc + ".price")*1)));
temp.setItem(13, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price: " + df.format(plugin.getConfig().getDouble(configloc + ".price")*8)));
temp.setItem(14, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Price: " + df.format(plugin.getConfig().getDouble(configloc + ".price")*64)));
temp.setItem(17, head(configloc));
return temp;
}
public static Inventory createSellerInventory(World ilw, int ilx, int ily, int ilz, Player player) {
DecimalFormat df = new DecimalFormat("#0.00");
String configloc = "shops."+String.valueOf(ilw)+"."+String.valueOf(ilx)+"."+String.valueOf(ily)+"."+String.valueOf(ilz);
Inventory temp = Bukkit.createInventory(new FakeHolder(new Location(ilw,ilx,ily,ilz), "Seller Interface"), 18, "Seller Interface");
for(int x = 0; x < 18; x = x + 1) {
ItemStack blank = setName(new ItemStack(Material.PURPLE_STAINED_GLASS_PANE, 1),"SELL");
temp.setItem(x, blank);
}
Location chestloc = new Location(Bukkit.getWorld(plugin.getConfig().getString(configloc + ".chestw")), plugin.getConfig().getInt(configloc + ".chestx"), plugin.getConfig().getInt(configloc + ".chesty"), plugin.getConfig().getInt(configloc + ".chestz"));
ItemStack selling = fetchCurItem(chestloc);
Inventory chest;
if (chestloc.getBlock().getState() instanceof Barrel) {
Barrel chdata = (Barrel) chestloc.getBlock().getState();
chest = chdata.getInventory();
} else {
Chest chdata = (Chest) chestloc.getBlock().getState();
chest = chdata.getBlockInventory();
}
if (getSpace(chest,selling)>=8) {
temp.setItem(4, taa(selling, 8));
} else {
temp.setItem(4, mmai(Material.BARRIER,1,(short) 0,"Not enough space"));
}
if (getSpace(chest,selling)>=64) {
temp.setItem(5, taa(selling, 64));
} else {
temp.setItem(5, mmai(Material.BARRIER,1,(short) 0,"Not enough space"));
}
if (getSpace(chest,selling)>=1) {
temp.setItem(3, taa(selling, 1));
} else {
temp.setItem(3, mmai(Material.BARRIER,1,(short) 0,"Not enough space"));
}
temp.setItem(0, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Value: " + df.format(plugin.getConfig().getDouble(configloc + ".price"))));
temp.setItem(12, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Value: " + df.format(plugin.getConfig().getDouble(configloc + ".price")*1)));
temp.setItem(13, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Value: " + df.format(plugin.getConfig().getDouble(configloc + ".price")*8)));
temp.setItem(14, mmai(Material.SUNFLOWER, 1, (short) 0, ChatColor.RESET + "" + ChatColor.GREEN + "Value: " + df.format(plugin.getConfig().getDouble(configloc + ".price")*64)));
temp.setItem(17, head(configloc));
return temp;
}
public static ItemStack tfwool(boolean bln) {
if (bln) {
return mmai(Material.LIME_WOOL, 1, (short) 5, ChatColor.RESET + "" + ChatColor.GREEN + "TRUE");
} else {
return mmai(Material.RED_WOOL, 1, (short) 14, ChatColor.RESET + "" + ChatColor.RED + "FALSE");
}
}
public static int getSpace(Inventory inventory, ItemStack cur) {
int count = 0;
for(int x = 0; x < inventory.getSize(); x++) {
if (inventory.getItem(x)==null) {
count = count + cur.getMaxStackSize();
} else if (inventory.getItem(x).isSimilar(cur)) {
count = count + cur.getMaxStackSize() - inventory.getItem(x).getAmount();
}
}
return count;
}
public static ItemStack sbwool(boolean bln) {
if (bln) {
return mmai(Material.YELLOW_WOOL, 1, (short) 4, ChatColor.RESET + "" + ChatColor.YELLOW + "BUY");
} else {
return mmai(Material.PURPLE_WOOL, 1, (short) 10, ChatColor.RESET + "" + ChatColor.DARK_PURPLE + "SELL");
}
}
public static Boolean removeItems(ItemStack is, int amount, Inventory ch, int tick) {
ItemStack[] backup = ch.getContents();
ItemStack c1 = is.clone();
Boolean suc = true;
ItemStack c2 = null;
ItemStack k = null;
fail:
for (int sd = 0; sd != amount; sd++) {
if1:
for (int c = 0; c < tick; c++) {
if (ch.getItem(c) != null) {
c2 = ch.getItem(c).clone();
if (c1.isSimilar(c2)) {
k = ch.getItem(c).clone();
k.setAmount(ch.getItem(c).getAmount()-1);
ch.setItem(c, k);
break if1;
}
}
if (c == tick - 1) {
suc = false;
break fail;
}
}
}
if (!suc) {
ch.setContents(backup);
}
return suc;
}
public static ItemStack ifbook(String name, String s1, String s2, String s3, String s4) {
ItemStack item = mmai(Material.BOOK, 1, (short) 0, ChatColor.RESET+""+ChatColor.AQUA+name);
ItemMeta meta = item.getItemMeta();
ArrayList<String> lore = new ArrayList<String>();
lore.add(ChatColor.RESET+""+ChatColor.GRAY+s1);
lore.add(ChatColor.RESET+""+ChatColor.GRAY+s2);
lore.add(ChatColor.RESET+""+ChatColor.GRAY+s3);
lore.add(ChatColor.RESET+""+ChatColor.GRAY+s4);
meta.setLore(lore);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
meta.addEnchant(Enchantment.FROST_WALKER, 1, true);
item.setItemMeta(meta);
return item;
}
public static void inverror(String error, Player player) {
Inventory temp = Bukkit.createInventory(new FakeHolder(new Location(null,0,0,0), "Error"), 18, "Error");
for(int x = 0; x < 18; x = x + 1) {
ItemStack blank = setName(new ItemStack(Material.RED_STAINED_GLASS_PANE, 1),error);
temp.setItem(x, blank);
}
player.closeInventory();
player.openInventory(temp);
}
}
|
package com.yaochen.address.data.domain.address;
import java.util.Date;
public class AdTreeAudit extends AdTree{
/**
* 审核时间.
*/
private Date auditTime;
public Date getAuditTime() {
return auditTime;
}
public void setAuditTime(Date auditTime) {
this.auditTime = auditTime;
}
}
|
package DesktopApp;
import static java.net.URLEncoder.encode;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Η κλάση modifyGrade παρέχει το βασικό GUI της σελίδας και εκτελεί τις βασικές
* μεθόδους για να είναι λειτουργική η δυνατότητα αλλαγής ενός βαθμού. Η λειτουργία της
* είναι όμοια με την κλάση modifyFromFile με μόνη ειδοποιό διαφορά ότι εδώ δεν εμπεριέχεται
* η χρήση αρχείου.Αντ'αυτού η μορφοποίηση ενός βαθμού γίνεται προσωπικά για κάποιον χρήστη
* @author Ioulios Tsiko: cs131027
* @author Theofilos Axiotis: cs131011
*/
public class modifyGrade extends javax.swing.JFrame {
String key;
adminMain adm;
public modifyGrade(adminMain obj) {
adm=obj;
initComponents();
setResizable(false);
}
public modifyGrade() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jComboBox2 = new javax.swing.JComboBox<>();
jButton4 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText(" ");
jTextField3.setText(" ");
jButton1.setText("Modify");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Student:");
jLabel2.setText("Lesson:");
jLabel3.setText("Grade:");
jButton3.setText("Πίσω");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
initComboBox("0");
jButton4.setText("OK");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jLabel4.setText(" ");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel3))
.addGap(18, 18, 18))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addComponent(jTextField3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4)))
.addContainerGap(36, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jButton4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton3))
.addGap(27, 27, 27)
.addComponent(jLabel4)
.addContainerGap(56, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JsonBuilderFactory factory=Json.createBuilderFactory(null);
JsonObjectBuilder jsonB = factory.createObjectBuilder()
.addNull("Initializer");
JsonArrayBuilder jsonA = factory.createArrayBuilder();
JsonObject myJson;
//json που κρατά ΑΜ και βαθμό προς αλλαγή
jsonA= jsonA.add(factory.createObjectBuilder()
.add("am", Integer.parseInt(jTextField1.getText().trim()))
.add("grade", Integer.parseInt(jTextField3.getText().trim())));
//debugging
System.out.println("am : "+jTextField1.getText()+" grade : "+ jTextField3.getText());
String lesson=(String) jComboBox2.getSelectedItem();
//προσθήκη επιλεγμένου μαθήματος απο jComboBoc
jsonB.add("lessonID",lesson.substring(0,1));
//προσθήκη πίνακα jsonA με το key Grades στο αντικείμενο jsonB
jsonB= jsonB.add("Grades", jsonA);
myJson=jsonB.build();
//debugging
System.out.println(myJson.toString());
String BASE_URI = "http://localhost:8080/WebServices/webresources";
Client client=javax.ws.rs.client.ClientBuilder.newClient();
WebTarget webTarget= client.target(BASE_URI);
WebTarget resource = webTarget.path("modifyFromFile");
//encoding για μεταφορά μέσω URI
String url=encode(myJson.toString());
resource = resource.queryParam("usr", User.getUsername());
resource = resource.queryParam("key",User.getKey());
resource = resource.queryParam("info", url);//δεδομένα προς αλλαγή
Invocation.Builder build = resource.request(javax.ws.rs.core.MediaType.TEXT_PLAIN);
System.out.println(build.get(String.class));
client.close();
jLabel4.setText("Grade modified succesfully");
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
this.setVisible(false);
adm.setVisible(true);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
initComboBox(jTextField1.getText().trim());
}//GEN-LAST:event_jButton4ActionPerformed
/**
* Η initComboBox κανει τις απαρραιτητες ενεργειες ωστε να κληθει το service
* getLessons και να επιστρεψει τα μαθηματα που υπαρχουν. Αφου γινει αυτο ,
* επομενο βημα ειναι η διαμορφωση του επιστρεφομενου json kai η προσηθκη
* των μαθηματων στο comboBox
*/
public void initComboBox(String usr)
{
String BASE_URI = "http://localhost:8080/WebServices/webresources";
Client client=javax.ws.rs.client.ClientBuilder.newClient();
WebTarget webTarget= client.target(BASE_URI);
WebTarget resource = webTarget.path("getLessons");
resource = resource.queryParam("usr",User.getUsername());
resource = resource.queryParam("key",User.getKey());
//εδώ δίνεται ως παράμετρος το username του φοιτητή και επιστρέφονται με αυτόν τον τρόπο
//μόνο τα δικά του μαθήματα. Αν η τιμή info ήταν 0 θα επιστρέφονταν όλα τα μαθήματα.
resource = resource.queryParam("info",usr);
Invocation.Builder build = resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON);
//αποθήκευση της επιστρεφόμενης τιμής
String js=build.get(String.class);
//αποδόμηση json
if(js.startsWith("{"))
{
jComboBox2.removeAllItems();
JSONObject json=new JSONObject(js);
JSONArray lessonsArray=json.getJSONArray("lessons");
//προσθήκη των δεδομένων στο comboBox
for (int i=0;i<lessonsArray.length();i++)
{
String lessName=lessonsArray.getJSONObject(i).getString("name");
String lessID=lessonsArray.getJSONObject(i).getString("lessid");
jComboBox2.addItem(lessID+" "+lessName);
}
}
client.close();
}
/**
* @param args the command line arguments
*/
public void init(){
// public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(modifyGrade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(modifyGrade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(modifyGrade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(modifyGrade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JComboBox<String> jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField3;
// End of variables declaration//GEN-END:variables
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.